From hexamorph at gmx.net Tue Jul 31 21:29:05 2007 From: hexamorph at gmx.net (Hexamorph) Date: Wed, 01 Aug 2007 03:29:05 +0200 Subject: Iteration over strings In-Reply-To: <46AFCB8C.9060800@jayloden.com> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> <46AF7A49.3040804@jayloden.com> <46AF8046.7090702@gmx.net> <496954360707311307y7d503b8eybd72795c8e699104@mail.gmail.com> <46AF9B2D.8040501@jayloden.com> <46AF9F55.20105@gmx.net> <46AFA1D9.1010707@gmx.net> <46AFCB8C.9060800@jayloden.com> Message-ID: <46AFE1E1.8000604@gmx.net> Jay Loden schrieb: > Well, I don't want to start a flamewar or anything like that Nothing like that intended here either :) OTOH, on most forums, lists, boards, etc, I am active, the constant fear about "flamewars" annoys me somewhat. As long as it doesn't get insulting, derogative or bull-headed it should be perfectly OK (even when it becomes somewhat hot-blooded) > [... ]What I don't like is how frequently I run into things that just aren't documented *well* ;) As an example, reading the docs for the "socket" module repeatedly tells you things like 'see the UNIX manual' instead of just documenting the appropriate information. I realize these are simply thin wrappers for C sockets, but that still assumes your audience is rather intimately familiar with socket programming in C on UNIX. Well, OK, but that's the drawback of a language with it's origin in the Unix scene. The other way, imagine some VisualBasic for Linux implementation.... (and try to get some info about some COM object) Anyway, we are going OT... From rodperson at verizon.net Sat Jul 7 11:19:14 2007 From: rodperson at verizon.net (Rod Person) Date: Sat, 07 Jul 2007 11:19:14 -0400 Subject: FreeBSD/Linux X11 determine which window manager is active Message-ID: <1183821554.849.2.camel@atomizer.opensourcebeef.net> I'm looking for a way to determine which window manager is running using python. I can't seem to find a system variable that hold this info. -- Rod "it takes an unusual mind to see the obvious." - Alfred Whitehead -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 194 bytes Desc: This is a digitally signed message part URL: From stephane.larouche at polymtl.ca Fri Jul 6 13:51:15 2007 From: stephane.larouche at polymtl.ca (=?utf-8?b?U3TDqXBoYW5l?= Larouche) Date: Fri, 6 Jul 2007 17:51:15 +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: > > > >If I call the methods in the C++ modules from the Python main thread, I > >don't have any problem. However, they are usually called from another > >Python thread (using the threading module) to keep the GUI responsive > >and, then, Python crashes. > > The question is whether your C++ code is designed to be called from > multiple threads. That is, if you call your C++ code from a *single* > non-main thread, does it work? Thank you for the quick answer. It does work if I call it from a single non-main thread. But everything must be called from that thread, including the import of the module. I still do not understand what is the problem. The C++ code is not thread safe, but I call it from 1 Python thread at a time. Anyway, I have always called it from multiple Python threads without any problem. Having put a few printf in the module, I can say that it crashes exactly when it tries to create C threads. Am I missing something? From dabu11et at rock.com Mon Jul 9 19:29:55 2007 From: dabu11et at rock.com (dabu11et at rock.com) Date: Mon, 09 Jul 2007 16:29:55 -0700 Subject: having problems in changing directories doing ftp in python In-Reply-To: <1184017065.872866.209340@q75g2000hsh.googlegroups.com> References: <1183812119.335649.292470@w3g2000hsg.googlegroups.com> <1184017065.872866.209340@q75g2000hsh.googlegroups.com> Message-ID: <1184023795.742604.115390@22g2000hsm.googlegroups.com> On Jul 9, 4:37 pm, "tedpot... at gmail.com" wrote: > Hi, > > Thank you for your cfomment, also I forgot about the case issue, yes > my web server is unix, not windows > > On Jul 9, 4:12 am, "Gabriel Genellina" wrote: > > > > > En Sat, 07 Jul 2007 09:41:59 -0300, tedpot... at gmail.com > > escribi?: > > > > I'm trying to write aftpin python to send files to my webserverr. > > > Curtly I will change the directory to the folder name, down load the > > > file, then do a chnag dir ..\ to go back to the root diretory, chnag > > > the directory, save the file, do a ../. > > > > Instad of going back one directory by doing ..\, could I just go to > > > the root directory? Currtly I get a error saying file does not exist. > > > Use the pwd command to see exactly which is your current directory. > > > > When I log onto my server using myftpprogram, > > > The current path reads /home/admin/ > > > I change the directory to mainwebsite_html. > > > The line that tells you the current directory now reads VAR/WWW/HTML. > > > > When I use python, I > > > 1. change the directory to mainwebsite_html > > > 2. change the directory to ted > > > 3. try to go back by changing the directory to "var/www/html" in which > > > I get an error saying it does not exist. > > > If your server file system is case sensitive (likely if it's a linux/unix > > server), VAR/WWW/HTML is not the same thing as var/www/html > > > -- > > Gabriel Genellina- Hide quoted text - > > - Show quoted text - www.hf.com From duncan.booth at invalid.invalid Tue Jul 3 04:00:19 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Jul 2007 08:00:19 GMT Subject: Probably simple syntax error References: <1183351228.878746.233430@o61g2000hsh.googlegroups.com> <1183367775.360977.201520@m37g2000prh.googlegroups.com> <1183386455.746792.154610@q69g2000hsb.googlegroups.com> Message-ID: ptn wrote: > PASCAL --> PYTHON > 5 div 2 --> 5/2 better: 5//2 The behaviour of 5/2 varies according to command line options and/or __future__ imports. e.g. If you start Python with the -Qwarn option 5/2 will generate a warning; if you start Python with -Qnew (or use "from __future__ import division") then 5/2 will give you 2.5. It is best, if you mean integer division, to always use the integer division operator. > 5 mod 2 --> 5 % 2 > 5/2 --> 5/2. (Notice the little dot at the end) Also note that those relationships only hold where both operands are positive. Python: -3//2 ---> -2 Pascal: -3 div 2 ---> either -1 or -2 is allowed by the standard. Python: 3 % -2 ---> -1 Pascal: 3 mod -2 --> error From wgwigw at gmail.com Tue Jul 31 23:46:37 2007 From: wgwigw at gmail.com (momobear) Date: Wed, 01 Aug 2007 03:46:37 -0000 Subject: Any way to monitor windows network connection? Message-ID: <1185939997.135825.310080@z24g2000prh.googlegroups.com> 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. From robert.rawlins at thinkbluemedia.co.uk Wed Jul 4 06:59:46 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 4 Jul 2007 11:59:46 +0100 Subject: Which Python Version In-Reply-To: <468B77FA.3050907@timgolden.me.uk> References: <00ac01c7be22$01202d80$03608880$@rawlins@thinkbluemedia.co.uk> <468B77FA.3050907@timgolden.me.uk> Message-ID: <000001c7be2a$9399e9f0$bacdbdd0$@rawlins@thinkbluemedia.co.uk> Thanks Tim, Greatly appreciated, I've been having a few problems with one of my apps recently crashing at all sorts of odd intervals without throwing an error or anything like that, So I'm upgrading to 2.5 to see if they'll make life any simpler. Thanks mate, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Tim Golden Sent: 04 July 2007 11:36 Cc: python-list at python.org Subject: Re: Which Python Version Robert Rawlins - Think Blue wrote: > Is there a command I can run to confirm which version of python I'm running? From outside Python: python -V (that's a capital V) From inside Python: import sys print sys.version (and a couple of more easily parseable alternatives; look at the sys module docs) TJG -- http://mail.python.org/mailman/listinfo/python-list From bignose+hates-spam at benfinney.id.au Sat Jul 28 20:20:59 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 29 Jul 2007 10:20:59 +1000 Subject: Test-driven design (was: Comparing Dictionaries) References: <87abtih7x0.fsf@benfinney.id.au> <46ab480e$0$10721$e4fe514c@dreader21.news.xs4all.nl> Message-ID: <87wswkdpqs.fsf_-_@benfinney.id.au> "Martin P. Hellwig" writes: > But the funny thing that I have seen in the development scene is > that writing tests first and code later is a lot easier when you > have a technical specification to base it on. A technical > specification is of course based on a functional design. A > functional design is written on the base of the assignment and the > scope definition. This is, to my mind, one of the greatest advantages of test-driven development: if you're not clear on how the code will be used, you can't write the test, and (by the discipline of TDD) you can't write the code either. Therefore, you're forced to confront the fuzziness of your design *before* it causes you to write meaningless code ? but only to the extent necessary to write the code at hand. If understanding the code you're about to write requires some more extensive design thinking, that's all to the good; but if you have enough understanding to write a test for the small area you're on, you don't need to do a huge amount of design. The stark confrontation of needing to write the unit test up front shows you the difference, at exactly the time it's most useful. There are many who call TDD "test-driven design" for this same reason. -- \ "A child of five could understand this. Fetch me a child of | `\ five." -- Groucho Marx | _o__) | Ben Finney From willmaier at ml1.net Wed Jul 18 21:22:32 2007 From: willmaier at ml1.net (Will Maier) Date: Wed, 18 Jul 2007 20:22:32 -0500 Subject: Interpreting os.lstat() In-Reply-To: <1184806559.224636.266500@e9g2000prf.googlegroups.com> References: <1184806559.224636.266500@e9g2000prf.googlegroups.com> Message-ID: <20070719012232.GL12728@lass.lfod.us> On Wed, Jul 18, 2007 at 05:55:59PM -0700, Adrian Petrescu wrote: > I can see some correspondence between the "stat" call and os.lstat > (for example, I'm guessing os.lstat(path)[6] represents the filesize), > but I can't see the correspondence between some of the other fields. > What does os.lstat(path)[0] represent? Are those last three the > created/modified/accessed times in unix time or what? Basically, what > does each field of os.lstat(path) represent? There's a whole module available explicitly for "interpreting results of os.stat() and os.lstat()." http://www.python.org/doc/current/lib/module-stat.html -- [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] From max at alcyone.com Tue Jul 31 00:54:33 2007 From: max at alcyone.com (Erik Max Francis) Date: Mon, 30 Jul 2007 21:54:33 -0700 Subject: [2.5] Reading a two-column file into an array? In-Reply-To: References: Message-ID: <7q2dnerzN-IUXTPbnZ2dnUVZ_g2dnZ2d@speakeasy.net> Gilles Ganault wrote: > I'm sure there's a much easier way to read a two-column, CSV file into > an array, but I haven't found it in Google. > > Should I use the Array module instead? The csv module? Or just .rstrip and .split? -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis I get my kicks above the wasteline, sunshine -- The American, _Chess_ From fred at adventistcare.org Wed Jul 18 09:02:48 2007 From: fred at adventistcare.org (Sells, Fred) Date: Wed, 18 Jul 2007 09:02:48 -0400 Subject: best SOAP module Message-ID: I need to talk to a vendor side via SOAP, Googling is overwhelming and many hits seem to point to older attempts. Can someone tell me which SOAP module is recommended. I'm using Python 2.4. --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From horpner at yahoo.com Wed Jul 25 16:01:29 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 25 Jul 2007 20:01:29 GMT Subject: is_iterable function. References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> <5uNpi.36822$G23.3430@newsreading01.news.tds.net> Message-ID: On 2007-07-25, Carsten Haese wrote: > On Wed, 2007-07-25 at 19:26 +0000, Neil Cerutti wrote: >> Speaking of the iter builtin function, is there an example of the >> use of the optional sentinel object somewhere I could see? > > Example 1: If you use a DB-API module that doesn't support direct cursor > iteration with "for row in cursor", you can simulate it this way: > > for row in iter(cursor.fetchone, None): > # do something > > Example 2: Reading a web page in chunks of 8kB: > > f = urllib.urlopen(url) > for chunk in iter(lambda:f.read(8192), ""): > # do something Ah! Thanks for the examples. That's much simpler than I was imagining. It's also somewhat evil, but I suppose it conserves a global name to do it that way. -- Neil Cerutti From adam at atlas.st Tue Jul 3 21:59:31 2007 From: adam at atlas.st (Adam Atlas) Date: Tue, 03 Jul 2007 18:59:31 -0700 Subject: Plugging a pseudo-memory leak Message-ID: <1183514371.042373.162020@k29g2000hsd.googlegroups.com> I have a program that seemed to be leaking memory, but after debugging, it seemed it just wasn't getting around to collecting the objects in question often enough. The objects are very long-lived, so they probably end up in generation 2, and don't get collected for a long time. Is there any way I can force collection of these objects? I know in Python 2.5 there's gc.collect(2), but I want to keep it compatible with previous versions of Python. From bj_666 at gmx.net Mon Jul 30 06:56:56 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Jul 2007 10:56:56 GMT Subject: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why? References: <1185791793.141118.44080@x35g2000prf.googlegroups.com> Message-ID: <5h5ufoF3hmufcU4@mid.uni-berlin.de> On Mon, 30 Jul 2007 03:36:33 -0700, Gilbert Fine wrote: > This is a very strange exception raised from somewhere in our program. > I have no idea how this happen. And don't know how to reproduce. It > just occurs from time to time. Maybe different `Decimal`\s? Here's how to reproduce such a traceback: In [20]: from decimal import Decimal In [21]: a = Decimal() In [22]: class Decimal(object): ....: pass ....: In [23]: b = Decimal() In [24]: a - b Traceback (most recent call last) /home/bj/ in () : unsupported operand type(s) for -: 'Decimal' and 'Decimal' Ciao, Marc 'BlackJack' Rintsch From attn.steven.kuo at gmail.com Sun Jul 29 01:31:36 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Sat, 28 Jul 2007 22:31:36 -0700 Subject: Split a string based on change of character In-Reply-To: References: Message-ID: <1185687096.830640.319110@z28g2000prd.googlegroups.com> On Jul 28, 9:46 pm, Andrew Savige wrote: > Python beginner here. > > For a string 'ABBBCC', I want to produce a list ['A', 'BBB', 'CC']. > That is, break the string into pieces based on change of character. > What's the best way to do this in Python? > > Using Python 2.5.1, I tried: > > import re > s = re.split(r'(?<=(.))(?!\1)', 'ABBBCC') > for e in s: print e > > but was surprised when it printed: > > ABBBCC > > I expected something like: > > A > A > BBB > B > CC > C > > (the extra fields because of the capturing parens). Using itertools: import itertools s = 'ABBBCC' print [''.join(grp) for key, grp in itertools.groupby(s)] Using re: import re pat = re.compile(r'((\w)\2*)') print [t[0] for t in re.findall(pat, s)] By the way, your pattern seems to work in perl: $ perl -le '$, = " "; print split(/(?<=(.))(?!\1)/, "ABBBCC");' A A BBB B CC C Was that the type of regular expressions you were expecting? -- Hope this helps, Steven From samwyse at gmail.com Sat Jul 28 09:16:41 2007 From: samwyse at gmail.com (samwyse) Date: Sat, 28 Jul 2007 13:16:41 -0000 Subject: Python 2.5.1 can't find win32file? Message-ID: <1185628601.992750.55990@e16g2000pri.googlegroups.com> I just upgraded from 2.4.something to 2.5.1. I get the stuff below. I tried easy-installing pywin32; same results. Anyone know what's going on? Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.2.1 ==== No Subprocess ==== >>> import win32file Traceback (most recent call last): File "", line 1, in import win32file ImportError: DLL load failed: The specified module could not be found. >>> import sys >>> sys.path ['C:\\Documents and Settings\\dentos\\Desktop\\scripting', 'C:\ \Python25\\Lib\\idlelib', 'C:\\Python25\\lib\\site-packages\ \setuptools-0.6c6-py2.5.egg', 'C:\\Python25\\lib\\site-packages\ \sqlalchemy-0.3.10-py2.5.egg', 'C:\\Python25\\lib\\site-packages\ \pil-1.1.6-py2.5-win32.egg', 'C:\\Python25\\lib\\site-packages\ \epydoc-3.0beta1-py2.5-win32.egg', 'C:\\Python25\\lib\\site-packages\ \pywin32-210-py2.5-win32.egg', 'C:\\WINNT\\system32\\python25.zip', 'C: \\Python25\\DLLs', 'C:\\Python25\\lib', 'C:\\Python25\\lib\\plat-win', 'C:\\Python25\\lib\\lib-tk', 'C:\\Python25', 'C:\\Python25\\lib\\site- packages'] From tjreedy at udel.edu Wed Jul 11 16:42:35 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Jul 2007 16:42:35 -0400 Subject: bool behavior in Python 3000? References: <5ficp9F3cram2U2@mid.individual.net><469472f4$0$1293$9b622d9e@news.freenet.de> Message-ID: "Ed Leafe" wrote in message news:C5AEB4C0-273B-411F-B14E-2B45E0881549 at leafe.com... | I think that the assignability to the names 'True' and 'False' is | incorrect, or at the very least subject to all sorts of odd results. It is necessary for 2.x to not break older code. I believe they will somehow be reserved, like None, in 3.0. tjr From stargaming at gmail.com Tue Jul 3 07:21:24 2007 From: stargaming at gmail.com (Stargaming) Date: Tue, 03 Jul 2007 13:21:24 +0200 Subject: newbie-question In-Reply-To: <468a2607$0$14903$9b622d9e@news.freenet.de> References: <468a2607$0$14903$9b622d9e@news.freenet.de> Message-ID: <468a313b$0$1934$9b622d9e@news.freenet.de> TK wrote: > how can I implement a socket timeout? Risking an inadequate answer (since your description was not that detailled, try to express a little more exact!), I can suggest http://starship.python.net/crew/theller/pyhelp.cgi to browse the documentation. If you enter "timeout", the first match will be a good pointer. Look through the socket manual (http://docs.python.org/lib/module-socket.html) for timeout. HTH, Stargaming From mailmaverick666 at gmail.com Thu Jul 5 03:26:39 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Thu, 5 Jul 2007 12:56:39 +0530 Subject: ['a', 'b'][True] results 'b' But how? In-Reply-To: <1183618481.636297.96080@e9g2000prf.googlegroups.com> References: <1183618481.636297.96080@e9g2000prf.googlegroups.com> Message-ID: <180b672e0707050026w18e24539n1786486973030c28@mail.gmail.com> True stands for 1 and False stands for 0 so list[True] is equivalent to list[1] and list[False] is equivalent to list[0] On 7/5/07, kath wrote: > > Hi, > > Can any one please tell me how is the following code is working? > ['a','b'] is a list of string, and [True] is list of boolean value. > How is it making effect....? > > > >>> ['a','b] [True] > 'b' > >>> ['a','b'] [False] > 'a' > >>> ['a','b']['some_string' == r'some_string'] > 'b' > >>> ['a','b']['some_string' == r'somestring'] > 'a' > > > > > Thanks in advance, > regards, > kath. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Regards-- Rishi Pathak National PARAM Supercomputing Facility Center for Development of Advanced Computing(C-DAC) Pune University Campus,Ganesh Khind Road Pune-Maharastra -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Jul 3 14:01:22 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Jul 2007 20:01:22 +0200 Subject: error return without exception set References: <468a6d19$0$27861$db0fefd9@news.zen.co.uk> Message-ID: Will McGugan wrote: > Can anyone suggest a likely cause for the following exception... > > Exception exceptions.SystemError: 'error return without exception set' > in ignored The "Exception ... ignored" part is probably caused by an exception in a finally block during garbage collection: >>> def f(): ... try: ... yield 42 ... finally: ... 1/0 ... >>> g = f() >>> g.next() 42 >>> del g Exception exceptions.ZeroDivisionError: 'integer division or modulo by zero' in ignored The "error return without exception set" part looks like a failed consistency check in ceval.c -- perhaps caused by a broken extension written in C. But you'd have to give some more context. Peter From bj_666 at gmx.net Fri Jul 6 13:46:16 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Jul 2007 17:46:16 GMT Subject: Expandable 2D Dictionaries? References: <1183736635.415927.208450@57g2000hsv.googlegroups.com> <1183738955.861587.186370@c77g2000hse.googlegroups.com> Message-ID: <5f7df8F3b25tsU4@mid.uni-berlin.de> On Fri, 06 Jul 2007 16:22:35 +0000, Robert Dailey wrote: > On Jul 6, 11:09 am, Jean-Paul Calderone wrote: >> This gets much easier if you change your structure around a bit: >> >> d = {} >> d["cat", "paw"] = "some string" >> >> Jean-Paul > > I like this format. I'm not familiar with it however. In my research > of python I was not aware it was legal to have comma operators inside > of the brackets. What does this mean? Is there some terminology that I > can search for to research this concept? Thanks. It's mapping the tuple ('cat', 'paw') to 'some string'. Commas make tuples. The parenthesis are just necessary for the literal empty tuple and if the syntax would be ambiguous otherwise. Ciao, Marc 'BlackJack' Rintsch From malkarouri at gmail.com Wed Jul 18 20:11:25 2007 From: malkarouri at gmail.com (malkarouri) Date: Wed, 18 Jul 2007 17:11:25 -0700 Subject: how to implementation latent semantic indexing in python.. In-Reply-To: References: Message-ID: <1184803885.142218.152490@g12g2000prg.googlegroups.com> On 13 Jul, 17:18, 78ncp wrote: > hi... > how to implementation algorithm latent semantic indexing in python > programming...?? > > thank's for daniel who answered my question before.. > > -- > View this message in context:http://www.nabble.com/how-to-implementation-latent-semantic-indexing-... > Sent from the Python - python-list mailing list archive at Nabble.com. IIRC, there was some explanation of Latent Semantic Analysis (with Python code) in an IEEE ReadyNotes document called "Introduction to Python for Artificial Intelligence". It wasn't free I am afraid. Of course you are aware that LSA is patented.. Muhammad From nogradi at gmail.com Thu Jul 26 08:46:02 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 26 Jul 2007 14:46:02 +0200 Subject: first, second, etc line of text file In-Reply-To: <1185394350.032814.262990@d55g2000hsg.googlegroups.com> References: <1185394350.032814.262990@d55g2000hsg.googlegroups.com> Message-ID: <5f56302b0707260546l3a4ca776j226f535c35028cf5@mail.gmail.com> > > A very simple question: I currently use a cumbersome-looking way of > > getting the first, second, etc. line of a text file: > > > > for i, line in enumerate( open( textfile ) ): > > if i == 0: > > print 'First line is: ' + line > > elif i == 1: > > print 'Second line is: ' + line > > ....... > > ....... > > > > I thought about f = open( textfile ) and then f[0], f[1], etc but that > > throws a TypeError: 'file' object is unsubscriptable. > > > > Is there a simpler way? > > If all you need is sequential access, you can use the next() method of > the file object: > > nextline = open(textfile).next > print 'First line is: %r' % nextline() > print 'Second line is: %r' % nextline() > ... > > For random access, the easiest way is to slurp all the file in a list > using file.readlines(). Thanks! This looks the best, I only need the first couple of lines sequentially so don't need to read in the whole file ever. From bscrivener42 at gmail.com Mon Jul 9 06:15:45 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Mon, 09 Jul 2007 03:15:45 -0700 Subject: Learning Basics In-Reply-To: <1183914604.792954.80260@c77g2000hse.googlegroups.com> References: <1183914604.792954.80260@c77g2000hse.googlegroups.com> Message-ID: <1183976145.913659.179120@o61g2000hsh.googlegroups.com> On Jul 8, 12:10 pm, Brad wrote: > So I'd appreciate some good feedback or ideas. I addition to Dan's suggestions, you could add a Tk text entry box to make it easier to enter text. I can send you some code if you'd like, as Steve Holden just generously helped me make a text entry box for my quote database. Or you can make your own starting here: Alan Gauld's "GUI Programming with Tkinter" http://www.freenetpages.co.uk/hp/alan.gauld/tutgui.htm These also came in very handy for cutting and pasting. Jeff Eppler's clp post - 3 August 2005 cut and paste text between Tkinter widgets" http://tinyurl.com/2d97gj rd From ricaraoz at gmail.com Tue Jul 31 14:34:18 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 31 Jul 2007 15:34:18 -0300 Subject: What is the "functional" way of doing this? In-Reply-To: References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> <1185838434.596591.132640@d30g2000prg.googlegroups.com> <7x3az5wjfa.fsf@ruckus.brouhaha.com> <1185839713.412656.242950@i13g2000prf.googlegroups.com> Message-ID: <46AF80AA.7030809@bigfoot.com> 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. From pingmaximus at gmail.com Tue Jul 31 21:42:38 2007 From: pingmaximus at gmail.com (Maximus Decimus) Date: Wed, 01 Aug 2007 01:42:38 -0000 Subject: Extending Python by Adding Keywords & Data types In-Reply-To: <5h9n66F3j641tU5@mid.uni-berlin.de> References: <1185913739.879602.212950@w3g2000hsg.googlegroups.com> <5h9n66F3j641tU5@mid.uni-berlin.de> Message-ID: <1185932558.472578.103690@o61g2000hsh.googlegroups.com> 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. Thanks in advance. On Jul 31, 5:16 pm, Marc 'BlackJack' Rintsch wrote: > On Tue, 31 Jul 2007 20:28:59 +0000, Maximus Decimus wrote: > > II want to add some more KEYWORDS and DATATYPES into the python script > > apart from the existing ones. > > New data types are easy: Just implement the classes. > > Why do you need new keywords? Can't the problem at hand be expressed in > functions and classes/methods? > > Ciao, > Marc 'BlackJack' Rintsch From martin at see.sig.for.address Sun Jul 1 12:47:36 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Sun, 01 Jul 2007 17:47:36 +0100 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> Message-ID: Roedy Green wrote: > > To add to the confusion you have GPS, Loran and Julian day also used > as scientific times. > GPS time is UTC time and I'd assume the same is true for Loran. Both are primarily for navigation and so are on Zulu time, which is another name for UTC. Zulu is the international radio word for the letter Z. I've never seen Julian time used outside the world of IBM mainframes. I'd be interested to know who else uses it. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From jstroud at mbi.ucla.edu Mon Jul 30 20:15:34 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 30 Jul 2007 17:15:34 -0700 Subject: Help text embedding in C code? In-Reply-To: References: Message-ID: Carsten Haese wrote: > On Mon, 2007-07-30 at 16:24 -0700, James Stroud wrote: > >>Hello All, >> >>I have a python module I wrote in C some time ago and I have since >>forgotten how to use my functions and so I wanted to add some >>doc-strings such that "help(function_name)" would give some help in the >>interactive interpreter. [...] Is it possible to >>embed this information in the C source directly [...] ? > > > Yes. A doc-string can be provided in the fourth slot of the PyMethodDef > entry. See e.g. /path/to/python/source/Modules/cPickle.c for a randomly > chosen module that has doc strings embedded in the C source. > > HTH, > Thanks! -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From walterbyrd at iname.com Wed Jul 25 13:42:54 2007 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 25 Jul 2007 10:42:54 -0700 Subject: Why PHP is so much more popular for web-development Message-ID: <1185385374.866372.198520@x35g2000prf.googlegroups.com> "Once you start down the Dark path, forever will it dominate your desiny. Consume you, it will." - Yoda I'm fairly new to web-development, and I'm trying out different technologies. Some people wonder why PHP is so popular, when the language is flawed in so many ways. To me, it's obvious: it's because it's much easier to get started with PHP, and once somebody gets started with a particular language, that person is likely to stay with that language. Before you can even get started with Python web-development, you have to understand this entire alphabit soup of: CGI, FASTCGI, MOD_PYTHON, FLUP, WSGI, PASTE, etc. For me, configuring fastcgi has been the most difficult part of getting django to work. PHP developers don't have to bother with anything like that. With PHP, you just throw some code in the middle of your html file. Also, PHP, and PHP frameworks, are supported everywhere. If you going to use a PHP MVC framework, like codeignitor, you would have a hard time finding a hoster that didn't support it - all you need is php4 and mysql. Dollar-hosting, for $10 a year, should work just fine with codeignitor. With codeignitor, just copy your files to whatever host, and that's it, you're done. By contrast, the most popular Python frameworks have sky-high system requirements. Take a look at the requirements and/or recomendations for popular Python frameworks like Django, TurboGears, or CherryPy: Apache 2.0, mod_python (latest version), fastcgi (at least), command line access, PostgreSQL. And a lot of low-cost hosters don't support Python at all. Don't get me wrong: I am not saying that PHP is better than Python for web-development. But, I sometimes think that Python could learn a few things from PHP. All JMHO, of course. From deets at nospam.web.de Mon Jul 30 07:42:13 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 30 Jul 2007 13:42:13 +0200 Subject: Cross platform Python app deployment References: <46adbbec$0$15210$fa0fcedb@news.zen.co.uk> Message-ID: <5h614lF3j21toU1@mid.uni-berlin.de> Will McGugan wrote: > Hi, > > Is there some reference regarding how to package a Python application > for the various platforms? I'm familiar with Windows deployment - I use > Py2Exe & InnoSetup - but I would like more information on deploying on > Mac and Linux. On mac, there is py2app that allows to create application-bundles you can then install. Either including a python interpreter, or using an installed one. Diez From santi_anti at yahoo.com Fri Jul 13 04:20:17 2007 From: santi_anti at yahoo.com (78ncp) Date: Fri, 13 Jul 2007 01:20:17 -0700 (PDT) Subject: how to call bluebit... Message-ID: <11575281.post@talk.nabble.com> helo... i'm so glad can join to this website... i want to ask.. how to import bluebit matrik calculator that result of singular value decomposition (SVD) in python programming.. thank's for your answer. -- View this message in context: http://www.nabble.com/how-to-call-bluebit...-tf4072919.html#a11575281 Sent from the Python - python-list mailing list archive at Nabble.com. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jul 4 04:29:47 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 04 Jul 2007 10:29:47 +0200 Subject: ignoring a part of returned tuples In-Reply-To: <1183536536.324939.236910@c77g2000hse.googlegroups.com> References: <1183536536.324939.236910@c77g2000hse.googlegroups.com> Message-ID: <468b5a9d$0$2228$426a74cc@news.free.fr> noamtm a ?crit : > Hi, > > Some functions, like os.walk(), return multiple items packed as a > tuple: > > for (dirpath, dirnames, filenames) in os.walk(...): > > Now, if you don't care about one of the tuple members, is there a > clean way to ignore it, Yes : just ignore it !-) > in a way that no unused variable is being > created? the term 'variable' in Python can be somewhat misleading. You have objects, and you have names bound to objects. In your case, whether you bind it to a name or not, the object will be created, so it wont make much differences. > What I wanted is: > for (dirpath, , filenames) in os.walk(...): > > But that doesn't work. A common idiom is to use '_' for unused values, ie: for (dirpath, _, filenames) in os.walk(...): You could also just bind the whole tuple to a ssinngle name then subscript it: for infos in os.walk(...): # now dirpath is infos[0] and filenames is infos[2] but this won't buy you much... From http Wed Jul 25 12:33:26 2007 From: http (Paul Rubin) Date: 25 Jul 2007 09:33:26 -0700 Subject: Flatten a list/tuple and Call a function with tuples References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> Message-ID: <7xzm1kqw89.fsf@ruckus.brouhaha.com> beginner writes: > I know the * operator. However, a 'partial unpack' does not seem to work. A few other posters have mentioned ways around this, but you might ask yourself what coding situation makes you want to do this stuff in the first place. I won't say there's never a reason for it, but a lot of times, a list containing a mixture of scalars and lists/tuples is a sign that your underlying data representation is contorted. Things are logically single values or they are logically lists of values, and that mixed representation is often a sign that the item logically should be a list, and you're hairing up the program with special treatment of the case where the list has exactly one element. I.e. instead of [[1,2,], 3, [5,6,]] maybe you really want [[1,2,], [3,], [5,6]] without the special treatment and flattening. From phishboh at gmail.com Fri Jul 13 16:52:17 2007 From: phishboh at gmail.com (phishboh at gmail.com) Date: Fri, 13 Jul 2007 13:52:17 -0700 Subject: Numpy array index handling In-Reply-To: References: <1184352981.493615.18040@k79g2000hse.googlegroups.com> Message-ID: <1184359937.326180.107370@g4g2000hsf.googlegroups.com> Thanks a lot for your reply. I'll have a look at the numpy-discussion for future issues. FYI, I'm using Python 2.4.3 for Windows (Enthought Edition) and the included IPython shell. I found my mistake; importing of pylab. E.g., this works from pylab import * ; from scipy import * ; y = arange(3) ; y[y>1] = 0 but not from scipy import * ; from pylab import * ; z = arange(3) ; z[z>1] = 0 Using the 'whos' command, I can see that y is an ndarray type, whereas z is an array type. (I also see a lot of functions, etc. How can I list just the variables?) It seems a bit risky to use 'from scipy import *'. Maybe it's better to use 'import scipy' and then scipy.arange, to be sure what is actually being used? Would there be any disadvanages with that approach, other than more use of the keyboard? From hniksic at xemacs.org Mon Jul 9 08:39:10 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 09 Jul 2007 14:39:10 +0200 Subject: What is the most efficient way to test for False in a list? References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <7x7ipajvst.fsf@ruckus.brouhaha.com> <5fejp2F3cp3igU1@mid.individual.net> <5feju0F3c7pd1U1@mid.uni-berlin.de> Message-ID: <87tzsd21ld.fsf@mulj.homelinux.net> "Diez B. Roggisch" writes: >>>> but what is your best way to test for for False in a list? [...] >>> status = all(list) >> Am I mistaken, or is this no identity test for False at all? > > You are mistaken. > all take an iterable and returns if each value of it is true. Testing for truth is not the same as an identity test for False. OP's message doesn't make it clear which one he's looking for. This illustrates the difference: >>> False in [3, 2, 1, 0, -1] True # no False here >>> all([3, 2, 1, 0, -1]) False # false value present, not necessarily False From alet at librelogiciel.com Tue Jul 24 16:28:31 2007 From: alet at librelogiciel.com (Jerome Alet) Date: Tue, 24 Jul 2007 22:28:31 +0200 Subject: [ANNOUNCE] PyKota v1.26 is out Message-ID: Hi there, I'm pleased to announce the immediate availability of PyKota v1.26 PyKota is a centralized and extensible print accounting and print quotas enforcement solution for CUPS, distributed under the terms of the GNU General Public License v2 or, at your option, any higher version. PyKota can be downloaded freely using subversion from svn://svn.librelogiciel.com/pykota (http://svn.librelogiciel.com/cgi-bin/viewcvs.cgi/pykota/) You can also download Official tarballs, deb or RPM packages for several distributions for a 25 EURO (os US$) fee, giving access to all existing and future releases. The packages you pay for remain redistributable under the terms of the GNU GPL. Summary of changes : http://www.pykota.com/Members/jerome/pykota126 Lisf of features : http://www.pykota.com/software/pykota/features Thanks you for reading. Jerome Alet From http Mon Jul 23 03:36:18 2007 From: http (Paul Rubin) Date: 23 Jul 2007 00:36:18 -0700 Subject: Lazy "for line in f" ? References: <1185120650.412694.314280@o61g2000hsh.googlegroups.com> <1185143634.778056.227720@g4g2000hsf.googlegroups.com> <1185173778.656660.195650@n60g2000hse.googlegroups.com> Message-ID: <7xbqe3efm5.fsf@ruckus.brouhaha.com> Alexandre Ferrieux writes: > So I'll reiterate the question: *why* does the Python library add that > extra layer of (hard-headed) buffering on top of stdio's ? readline? From robert.rawlins at thinkbluemedia.co.uk Mon Jul 16 04:51:39 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 16 Jul 2007 09:51:39 +0100 Subject: Access Object From 2 Applications or Fix Scheduler In-Reply-To: <00a501c7c776$900ba8a0$03000080@hendrik> References: <015201c7c71a$2be05df0$83a119d0$@rawlins@thinkbluemedia.co.uk> <00a501c7c776$900ba8a0$03000080@hendrik> Message-ID: <018a01c7c786$86e52de0$94af89a0$@rawlins@thinkbluemedia.co.uk> Thanks Hendrik & Alex for your suggestions, I'm glad to see that there are lots of options for me here, and I'll give them all of a decent exploration to see what my best option is, starting the second app in a named pipe sounds like a fair solution, but I've not don't this before, how easy is it to have the second application ready to receive the new dictionary data? Just out of interest though I'd still like to know why my first application schedules didn't work properly, should I be starting them all in their own thread? Would that work better? 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 Hendrik van Rooyen Sent: 16 July 2007 07:29 To: python-list at python.org Subject: Re: Access Object From 2 Applications or Fix Scheduler Robert Rawlins - Think Blue wrote: >Hello Guys, > >I have two applications which I need to get talking and sharing an >object, what s the best way to do this? Basically my >first application parses an XML document into a bunch of lists and tuples etc, and I need to access the data in these lists >and tuples from my second application. Is this possible? And whats the simplest method? > >This problem all evolves from a hack/work around Ive had to place >together as I have been having problems with >sched, these two applications used to be a single one to start with but for some reason when scheduling tasks using the >sched module they wouldnt ever run when supposed too, so Id schedule >it to run every 2 minutes and it would run >between 3 and 15 minutes :-s so I ripped it out into its own application and it now runs every 2 minutes exactly. > >I either need to fix my sched issues or the memory share, either way >Im quite happy, just need to get it working >smoothly. > >Any ideas? > You have already split the thing, so I would: schedule the XML parser and make it do its stuff. then pickle the results using cPickle then from this first thing, either: write the pickles to temp files and start the second thing using eg os.system() or start the second thing and use a named pipe to pass the pickles over for unpickling and processing, or use one of the popens, or have a look at Pyro, or start the second thing as a thread and use a Queue.. of course this whole scheme will fall apart if the combined processing takes longer than the scheduling interval. HTH - Hendrik From shuang at ercot.com Mon Jul 30 16:36:52 2007 From: shuang at ercot.com (Huang, Shun-Hsien) Date: Mon, 30 Jul 2007 15:36:52 -0500 Subject: win32 question in Python Message-ID: Hi, I am new in Python. I have one question in the database application in python. I have one excel file that I want to save in the database table. In the Microsoft access, I can easy do this one by using Docmd ...... How do I use this one in Python? I already know how to connect to a database through Python, but how do I copy a excel file into database table by using Python? Best Regards. Shun-Hsien Huang (Fred) -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Tue Jul 24 14:31:24 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 24 Jul 2007 18:31:24 -0000 Subject: Problem in Socket..... References: <1185299582.776366.17970@d55g2000hsg.googlegroups.com> Message-ID: <13achbsi0a3d82f@corp.supernews.com> On 2007-07-24, Clement wrote: > Is it possible to close the socket connection immediately in > Python...... Sure. Just call the socket's close() method. [You really ought to get that sticky '.' key fixed.] > Because i am getting error even though i close it after > all the transfer.... You're going to have to be a bit more specific if you want useful suggestions. > I read from one article it is possible in C socket.... Whether > is it possible in Python? Yes. The socket's close() method just calls libc's close() on the socket. -- Grant Edwards grante Yow! And then we could sit at on the hoods of cars at visi.com stop lights! From martin at v.loewis.de Sun Jul 1 11:20:27 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 01 Jul 2007 17:20:27 +0200 Subject: object references/memory access In-Reply-To: <1183247524.662884.153830@n60g2000hse.googlegroups.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> Message-ID: <4687c63b$0$22513$9b622d9e@news.freenet.de> > I have searched a good deal about this topic and have not found > any good information yet. It seems that the people asking all want > something a bit different than what I want and also don't divulge much > about their intentions. I wish to improve the rate of data transfer > between two python programs on the same machine. I don't understand why you want exactly this. Wouldn't it be sufficient/better if the response time for a request as seen by the client web browser would improve? Why is it necessary to start optimizing at the data transfer rate? As a starting point, I would try to eliminate the CGI part. There are two ways to do that: a) run the Python code inside the Apache process, and b) use a single Python server (possibly shared with the database process), and connect this to Apache through the reverse proxy protocol. The cost you observe might be in the repeated creation of new processes, and the repeated establishment of new TCP connections. Either solution would drop some of that overhead. > I am fairly ignorant of how Apache works with the > CGI module but here is what I'd like to do. I want to somehow let the > server print out to the user's browser instead of the search script in > order to cut out the time of sending the results over the socket. That is not possible. The CGI script does not "print out to the user's browser". Instead, it prints to its stdout, which is a pipe being read by Apache; Apache then copies all data to the socket going to the user's browser (possibly after manipulating the headers also). > Mainly, I'd like > to know if there is any kind of descriptor or ID that can be passed > and used by another process to print output to the user's browser > instead of the script that Apache invoked. No. The CGI script has a file handle, and it is not possible to pass a file handle to a different process. > If there is not a good Pythonic way to do the above, I am open to > mixing in some C to do the job if that is what it takes. No, it's not Python that fails to support that - it's the operating system. See above for solutions that avoid one such copying in the first place. Regards, Martin From istvan.albert at gmail.com Thu Jul 26 21:25:00 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 27 Jul 2007 01:25:00 -0000 Subject: zip() function troubles In-Reply-To: <7xir86wx0p.fsf@ruckus.brouhaha.com> References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> <7xir86wx0p.fsf@ruckus.brouhaha.com> Message-ID: <1185499500.807041.60580@g4g2000hsf.googlegroups.com> On Jul 26, 7:44 pm, Paul Rubin wrote: > Istvan Albert writes: > > exceeded 10 million the zip function slowed to a crawl. Note that > > there was memory available to store over 100 million items. > > How many bytes is that? Maybe the items (heap-allocated boxed > integers in your code example) are bigger than you expect. while I don't have an answer to this the point that I was trying to make is that I'm fairly certain that it is not a memory issue (some sort of swapping) because the overall memory usage with the OS included is about 1Gb (out of available 2Gb) I tested this on a linux server system with 4Gb of RAM a = [ 0 ] * 10**7 takes miliseconds, but say the b = zip(a,a) will take a very long time to finish: atlas:~$ time python -c "a = [0] * 10**7" real 0m0.165s user 0m0.128s sys 0m0.036s atlas:~$ time python -c "a = [0] * 10**7; b= zip(a,a)" real 0m55.150s user 0m54.919s sys 0m0.232s Istvan From jadestar at idiom.com Fri Jul 13 17:49:35 2007 From: jadestar at idiom.com (James T. Dennis) Date: Fri, 13 Jul 2007 21:49:35 -0000 Subject: Trying to choose between python and java References: Message-ID: <1184363375.352036@smirk> Hamilton, William wrote: >> From: Beliavsky > On May 15, 1:30 am, Anthony Irwin wrote: >> >>> #5 someone said that they used to use python but stopped because the >>> language changed or made stuff depreciated (I can fully remember >>> which) and old code stopped working. Is code written today likely to >>> still work in 5+ years or do they depreciate stuff and you have to >> update? The word is "deprecated." ("Depreciated" would be a financial term, not a term of art in computer science). >> Because Python 3 will change the syntax of print to disallow >> print "Hello, world." Python 3 is an exception case because it's the only time that the BFDL has specifically and intentionally declared that backward compability was NOT a goal for that version. Essentially you can consider Python 3 to be a fork ... a departure from Python 2.x and earlier. This specific change, for example, is intended to remove a consistency wart in the language. The "print" statement in Python is a special case. It's not a normal built-in function and it's not an expression. You can start writing all your code now as: print() --- calling the statement as if it were a function. Then you're future Python 3 work would consist of simply defining a suitable function named print() (if one isn't provided or the one provided isn't suited to your needs). >> a substantial fraction of Python programs in existence, including all >> of my programs, will be broken. Draw your own conclusions. Python 3 will be a different language. It'll be similar, perhaps to the disruption between Perl 4 and Perl 5; or between Perl 5 and the proposed changes to Perl 6. Keep in mind that Java has had a number of features deprecated as well. The disruption from Java 1.x to Java2 and thence to Java5 is probably greater than the level of disruption between Python 1.x and Python 2.5.x (which as been a roughly equivalent length of time --- over a decade in both cases). > No, they'll work just fine. They just won't work with Python 3. It's not > like the Python Liberation Front is going to hack into your computer in the > middle of the night and delete you 2.x installation. > --- > -Bill Hamilton Yes, considering this to be more like a fork then an upgrade is the wise approach. Many Linux distributions, for example, will probably ship and concurrently install Python 2.x and Python 3.x for a several years after Python 3 ships. -- Jim Dennis, Starshine: Signed, Sealed, Delivered From montyphyton at gmail.com Fri Jul 20 18:27:51 2007 From: montyphyton at gmail.com (montyphyton at gmail.com) Date: Fri, 20 Jul 2007 15:27:51 -0700 Subject: Sorting dict keys Message-ID: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> Consider the following: >>> a = {1:2, 3:4, 2:5} Say that i want to get the keys of a, sorted. First thing I tried: >>> b = a.keys().sort() >>> print b None Doesn't work. Probably because I am actually trying to sort the keys of the dictionary without copying them first. If that is the case, fine. Next thing I do: >>> b = a.keys() >>> b.sort() [1, 2, 3] Works fine, but I would really like it if I could somehow do it in one line. As the problem seems to be copying the object, i try the following: >>> import copy >>> b = copy.copy(a.keys()).sort() >>> print b None Hmmm, why doesn't it work? Also, >>> b = copy.deepcopy(a.keys()).sort() >>> print b None (not that I thought that deepcopy will work since shallow didn't, I understand the difference :) ) Obviously, I am missing something here. What am I thinking wrong? Why doesn't copying the object work? Thanks for all the help From jonshan at winlab.rutgers.edu Fri Jul 6 17:40:16 2007 From: jonshan at winlab.rutgers.edu (Jonathan Shan) Date: Fri, 06 Jul 2007 14:40:16 -0700 Subject: Repeating Thread Error Message-ID: <1183758016.776354.241620@g4g2000hsf.googlegroups.com> Hello, I am trying to call a function every 5 seconds. My understanding of time.sleep() is during the sleep time everything "stops". However, in my application, there are background processes that must be running continuously during the five second interval. Thus, threading.Timer seems like a good function. Here is the relevant code: # background processes t = threading.Timer(5.0, function_name, [arguments]) while True: # Do background processes run inside while loop? t.start() The above code generates an error: AssertionError: thread already started Any hints on how to fix the error? Also, do background processes run inside while loops? Thanks in advance, Jonathan Shan From oren.tsur at gmail.com Tue Jul 24 10:30:04 2007 From: oren.tsur at gmail.com (oren.tsur at gmail.com) Date: Tue, 24 Jul 2007 14:30:04 -0000 Subject: Parsing XML with ElementTree (unicode problem?) In-Reply-To: <1185279975.254458.7510@57g2000hsv.googlegroups.com> References: <1185200976.082516.105420@57g2000hsv.googlegroups.com> <1185279975.254458.7510@57g2000hsv.googlegroups.com> Message-ID: <1185287404.060182.314750@57g2000hsv.googlegroups.com> > How about trying > root = ElementTree.parse(urlopen(query), encoding ='utf-8') > this specific thing is not working, however, parsing the url is not problematic. the problem is that after parsing the xml at the url I save some of the fields to a local file and the local file is not being parsed properly due to the non-ascii characters Sauni\xc3\xa8re (french name: Sauni?re). an example of the file can be found in the first posting, you could copy+paste+save it to your machine then try to parse it. I'm quite new to xml and python so I guess there must be something wrong or dumb in the way I save the file (maybe I miss some important tags?) or in the way I re-open it but I can't find whats wrong. From ejensen at visi.com Fri Jul 6 16:28:33 2007 From: ejensen at visi.com (Ed Jensen) Date: Fri, 06 Jul 2007 20:28:33 -0000 Subject: The best platform and editor for Python References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183646799.400176.144570@k79g2000hse.googlegroups.com> <1183655933.475488.157270@m36g2000hse.googlegroups.com> <1183670009.035673.256680@w5g2000hsg.googlegroups.com> <1i0so61.10qnto712c7dhpN%aleax@mac.com> Message-ID: <138t9fhlcdq1nf8@corp.supernews.com> Alex Martelli wrote: > Calling all vi/vim users (and we'll heartily appreciate the support of > TextMate fans, BBEdit ones, etc, etc) -- we're at risk being defined out > of existence, since we're neither happy with Emacs nor wanting anything > like Visual Studio, and yet Kay claims that people in either category > make up the whole (one half plus the other half) and so that WE DON'T > EXIST!!! A ridiculous claim to be sure, but we'd better let Herr > Schluehr know that in no uncertain terms... vi/vim/gvim user here... :) From gaurkuber at gmail.com Sat Jul 7 13:43:34 2007 From: gaurkuber at gmail.com (K Gaur) Date: Sat, 07 Jul 2007 17:43:34 -0000 Subject: problem with pickle Message-ID: <1183830214.845484.116090@o11g2000prd.googlegroups.com> hello everybody I've just started learning python . i stumbled upon this broad spectrum function 'pickle' but it is not getting executed as it should this is what the python interpreter returns on giving the basic command >>>pickle.dump(x,f) where x is a tuple and f is a file object Traceback (most recent call last): File "", line 1, in ? NameError: name 'pickle' is not defined kindly elucidate what's wrong thanks From edreamleo at charter.net Mon Jul 30 11:36:46 2007 From: edreamleo at charter.net (Edward K Ream) Date: Mon, 30 Jul 2007 10:36:46 -0500 Subject: Bug? exec converts '\n' to newline in docstrings!? Message-ID: It looks like both exec and execfile are converting "\n" to an actual newline in docstrings! Start idle: Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win32 [rest of signon deleted] >>> s = '''\ strings = 'abc'.split("\n") ''' >>> print s strings = 'abc'.split(" ") I see this in my own calls to exec and execfile. Is this a bug or am I missing something? Edward ------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From deets at nospam.web.de Sun Jul 1 06:33:12 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 01 Jul 2007 12:33:12 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <4686b9b0$0$27140$426a74cc@news.free.fr> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <5engo8F38jdgaU1@mid.uni-berlin.de> <4686b9b0$0$27140$426a74cc@news.free.fr> Message-ID: <5epe7aF39ugprU1@mid.uni-berlin.de> > > """ > Because of the different flight path, a data conversion from a 64-bit > floating point to 16-bit signed integer value caused a hardware > exception (more specifically, an arithmetic overflow, as the floating > point number had a value too large to be represented by a 16-bit signed > integer). > """ > > As far as I'm concerned, it surely qualifies as a runtime type error - > "data conversion from a floating point to a 16-bit signed int" should > not be allowed when unsafe, isn't it ? I wouldn't say so. The conversion is a partial function. It _has_ to be a partial function, as you can't cram 64 bit into 16 without losses. If you could, infinite compression would be possible. So - you _have_ to allow such a conversion. That has nothing to do with types, the types were proper. The values weren't. > """ > Efficiency considerations had led to the disabling of the software > handler (in Ada code) for this error trap. > """ > > Which implies that even in ADA, runtime type errors are in fact expected > - else there would be no handler for such a case. Well, yes, runtime errors occur - in statically typed languages as well. That's essentially the halting-problem. > But what, how could an ADA module not be correct if it compiles - the > ADA type system is here to "prove the absence of certain bugs", isn't > it ?-) Yes, certain bugs. Not those though. In the same sense as the python compiler pukes statically on me if I write def f(): n = x * 2 x = n The whole point of the Ariane failure was that nobody believed in the code because the type analyzer had woven it through - but because the specs and a mathematical analysis of the code had shown it was to be trusted. For the old rocket, that was. The question is not if static typing that prevents certain errors is a bad thing. It's not. But it comes with a pricetag - the lack of flexibility. And usually, I'm not willing to pay that price, because it makes my whole design much more cumbersome and thus often error-prone - as line numbers increase. But in a constrained environment like the ariane, where you have limited resources, you want as much certainity as you can get, together with operations that run on the native types of your processor in an efficient way. Diez From robin at reportlab.com Thu Jul 5 13:28:45 2007 From: robin at reportlab.com (Robin Becker) Date: Thu, 05 Jul 2007 18:28:45 +0100 Subject: deliberate versus os socket timeout Message-ID: <468D2A4D.2020405@chamonix.reportlab.co.uk> While messing about with some deliberate socket timeout code I got an unexpected timeout after 20 seconds when my code was doing socket.setdefaulttimeout(120). Closer inspection revealed that this error in fact seemed to come from the os (in this case windows xp). By inspection of test cases the error.reason from the deliberate socket timeout looks like 'timed out' whereas the windows caused timeout error.reason looks like '(10060 operation timed out)' it would be nice to know if that is in fact true and whether there is any way to do the attribution of errors more sensibly. Both of these seem to cause urllib2.URLError and presumably appear somewhere in the socket code. It might be nice if the deliberate timeout could be something like 'timed out deliberately after xxx seconds'. More importantly is there anything I can do to avoid these wrong os inspired timeouts? I'm just using urllib2 to read from a remote site inside of a cgi script. I'm not sure it's a big problem, but I have no idea what could cause it. The code I'm using is based on one of jjlee's recipes def httpGet(self): import urllib2, socket from xml.sax.saxutils import escape oto = socket.getdefaulttimeout() try: socket.setdefaulttimeout(self.timeout) self.url = url = self.makeUrl(self.params) try: self.response = r = urllib2.urlopen(url) except urllib2.URLError, e: if hasattr(e, 'reason'): msg = 'HTTP error '+str(e.reason) if 'time' in msg: msg += '(our timeout=%s)' % socket.getdefaulttimeout() return 1,escape(msg) elif hasattr(e, 'code'): return 1, escape('The server couldn\'t fulfill the request.\nError code: '+str(e.code)) else: # everything is fine h = self.headers = {} ........ return 0,...... finally: socket.setdefaulttimeout(oto) -- Robin Becker From musiccomposition at gmail.com Fri Jul 6 16:15:22 2007 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 06 Jul 2007 20:15:22 -0000 Subject: The file executing In-Reply-To: References: <1183426846.550981.11910@m36g2000hse.googlegroups.com> <1183430828.997331.84340@e9g2000prf.googlegroups.com> <1183470421.012591.243300@k79g2000hse.googlegroups.com> Message-ID: <1183752922.290253.8600@q75g2000hsh.googlegroups.com> On Jul 3, 8:56 am, Sebastian Wiesner wrote: > [ Benjamin ] > > > On Jul 2, 9:47 pm, Justin Ezequiel > > > wrote: > > > On Jul 3, 9:40 am, Benjamin wrote: > > > > How does one get the path to the file currently executing (not the > > > > cwd). Thank you > > > > os.path.dirname(sys.argv[0]) > > > The returns the file that was called first, but not the one currently > > executing... > > Use __file__ instead of sys.argv[0] So: if __name__ == "main": currentDir = os.path.dirname(sys.argv[0]) else: currentDir = os.path.dirname(__file__) > > -- > Freedom is always the freedom of dissenters. > (Rosa Luxemburg) > > signature.asc > 1KDownload From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jul 31 16:53:08 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 31 Jul 2007 22:53:08 +0200 Subject: Creating a shared object in python References: Message-ID: <5h9lpkF3kav80U1@mid.individual.net> Delgado, Edgardo CIV NAVAIR 4.1.4.3 wrote: > Is there a way to create a shared object in python? What's a shared object? Do you mean IPC or .so libraries, or something different? Regards, Bj?rn -- BOFH excuse #404: Sysadmin accidentally destroyed pager with a large hammer. From http Tue Jul 31 15:57:13 2007 From: http (Paul Rubin) Date: 31 Jul 2007 12:57:13 -0700 Subject: zip() function troubles References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> <7xfy3ae4lb.fsf@ruckus.brouhaha.com> Message-ID: <7xps28s5wm.fsf@ruckus.brouhaha.com> "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. > 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. From horpner at yahoo.com Thu Jul 26 11:02:39 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 26 Jul 2007 15:02:39 GMT Subject: is_iterable function. References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> <5uNpi.36822$G23.3430@newsreading01.news.tds.net> Message-ID: Based on the discussions in this thread (thanks all for your thoughts), I'm settling for: def is_iterable(obj): try: iter(obj).next() return True except TypeError: return False except KeyError: return False The call to iter will fail for objects that don't support the iterator protocol, and the call to next will fail for a (hopefully large) subset of the objects that don't support the sequence protocol. This seems preferable to cluttering code with exception handling and inspecting tracebacks. But it's still basically wrong, I guess. To repost my use case: def deeply_mapped(func, iterable): """ Recursively apply a function to every item in a iterable object, recursively descending into items that are iterable. The result is an iterator over the mapped values. Similar to the builtin map function, func may be None, causing the items to returned unchanged. >>> import functools >>> flattened = functools.partial(deeply_mapped, None) >>> list(flattened([[1], [2, 3, []], 4])) [1, 2, 3, 4] >>> list(flattened(((1), (2, 3, ()), 4))) [1, 2, 3, 4] >>> list(flattened([[[[]]], 1, 2, 3, 4])) [1, 2, 3, 4] >>> list(flattened([1, [[[2, 3]], 4]])) [1, 2, 3, 4] """ for item in iterable: if is_iterable(item): for it in deeply_mapped(func, item): if func is None: yield it else: yield func(it) else: if func is None: yield item else: yield func(item) -- Neil Cerutti From mccredie at gmail.com Wed Jul 11 01:20:52 2007 From: mccredie at gmail.com (Matimus) Date: Wed, 11 Jul 2007 05:20:52 -0000 Subject: SafeConfigParser can set unsafe values In-Reply-To: References: <46940a3e$0$18464$afc38c87@news.optusnet.com.au> <1184111631.293350.106340@o11g2000prd.googlegroups.com> Message-ID: <1184131252.068248.159390@o11g2000prd.googlegroups.com> > I agree, but that was a trivial example to demonstrate the problem. > Writing the file out to disk writes it exactly as set(), causing a get() > to fail just the same later. No... The above statement is not true. The following code: [code] from ConfigParser import * import sys cp = SafeConfigParser() cp.add_section("sect") cp.set("sect","opt","hello%world") cp.write(sys.stdout) [/code] Produces this output: [sect] opt = hello%world The write method never calls get. However, when you read the file that was output by the above code using .get(...) will raise an error. You can avoid that error by setting the optional 'raw' parameter to True. From bbxx789_05ss at yahoo.com Tue Jul 31 13:45:26 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 31 Jul 2007 10:45:26 -0700 Subject: encode() question In-Reply-To: References: <1185900791.595830.21290@d55g2000hsg.googlegroups.com> Message-ID: <1185903926.955444.43620@22g2000hsm.googlegroups.com> On Jul 31, 11:18 am, "Gabriel Genellina" wrote: > str.decode and unicode.encode should NOT exist, or at least issue a > warning (IMHO). > Yes, that sounds like a good idea. From steve at REMOVE.THIS.cybersource.com.au Fri Jul 20 20:20:56 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 21 Jul 2007 10:20:56 +1000 Subject: Pythonic way for missing dict keys References: Message-ID: On Fri, 20 Jul 2007 19:08:57 +0000, Alex Popescu wrote: > I am wondering what is the most pythonic way of dealing with missing > keys and default values. [snip three versions] Others have already mentioned the collections.defaultdict type, however it seems people have forgotten about the setdefault method of dictionaries. value = somedict.setdefault(key, defaultvalue) The disadvantage of setdefault is that the defaultvalue has to be created up front. The disadvantage of collections.defaultdict is that the "default factory" function takes no arguments, which makes it rather less than convenient. One can work around this using global variables: # The default value is expensive to calculate, and known # only at runtime. >>> expensivefunction = lambda x: str(x) >>> D = collections.defaultdict(lambda : expensivefunction(context)) # lots of code goes here... # set context just before fetching from the default dict >>> context = 42 >>> value = D['key'] >>> print value, D 42 defaultdict( at 0xb7eb4fb4>, {'key': '42'}) but one should be very leery of relying on global variables like that. That suggests the best solution is something like this: def getdefault(adict, key, expensivefunction, context): if key in adict: return adict[key] else: value = expensivefunction(context) adict[key] = value return value -- Steven. From bj_666 at gmx.net Fri Jul 13 12:34:23 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Jul 2007 16:34:23 GMT Subject: Can a low-level programmer learn OOP? References: Message-ID: <5fpnsfF3dm8bpU3@mid.uni-berlin.de> On Fri, 13 Jul 2007 09:06:44 -0700, Chris Carlen wrote: > Perhaps the only thing that may have clicked regarding OOP is that in > certain cases I might prefer a higher-level approach to tasks which > involve dynamic memory allocation. If I don't need the execution > efficiency of C, then OOP might produce working results faster by not > having to worry about the details of memory management, pointers, etc. That's not something tied to OOP. Automatic memory management is also possible with procedural languages. > But I wonder if the OOP programmers spend as much time creating classes > and trying to organize everything into the OOP paradigm as the C > programmer spends just writing the code? Creating classes and organizing the program in an OOP language isn't different from creating structs and organizing the program in C. On one side Python is a very OOP language as everything is an object. On the other side it is possible to write parts of the program in procedural or even functional style. Python is not Java, you don't have to force everything into classes. >From my experience Python makes it easy to "just write the code". Easier than C because I don't have to deal with so much machine details, don't have to manage memory, don't need extra indexes for looping over lists and so on. And the "crashes" are much gentler, telling me what the error is and where instead of a simple "segfault" or totally messed up results. Ciao, Marc 'BlackJack' Rintsch From michele.simionato at gmail.com Sat Jul 14 04:16:09 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Sat, 14 Jul 2007 08:16:09 -0000 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: <1184400969.783113.96890@q75g2000hsh.googlegroups.com> On Jul 14, 8:49 am, James Stroud wrote: > > Any gui more complicated than a few entry fields and some checkbuttons > is going to lend itself to OOP--so if you want to do GUI, learn OOP. Yep, there is nothing to be added to that. Except maybe that if you don't care too much about the look&feel you may consider starting with Tkinter. Pros: 1. it is part of the standard library, and you already have it; 2. it is possibly the easiest/simplest GUI out there; 3. it runs pretty much everywhere with minimal fuss. Michele Simionato From jstroud at mbi.ucla.edu Mon Jul 30 19:24:17 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 30 Jul 2007 16:24:17 -0700 Subject: Help text embedding in C code? Message-ID: Hello All, I have a python module I wrote in C some time ago and I have since forgotten how to use my functions and so I wanted to add some doc-strings such that "help(function_name)" would give some help in the interactive interpreter. In the cPython source, it seems like python wrapper functions provide this documentation in doc-strings. Is this the advisable way? It seems silly to have to write a python wrapper around a python extension just to have doc-strings available. Is it possible to embed this information in the C source directly or is that too much trouble and I should just start typing HTML.reStructuredText for this sort of thing? James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From steve at REMOVE.THIS.cybersource.com.au Fri Jul 6 21:00:32 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 07 Jul 2007 11:00:32 +1000 Subject: How would I write this C code in Python? References: <1183743110.399675.180570@n60g2000hse.googlegroups.com> Message-ID: On Fri, 06 Jul 2007 17:31:50 +0000, DeveloperX wrote: > Python Attempt: Please note that since I can't type TABs online > easily, I am using the @ character to represent TABs in the following > Python code. Why not indent with spaces, just like you did for the example C code? -- Steven. From greg at cosc.canterbury.ac.nz Wed Jul 4 21:53:52 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 05 Jul 2007 13:53:52 +1200 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <1183576255.668414.256990@q69g2000hsb.googlegroups.com> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <138jml0ldeucf32@corp.supernews.com> <1183576255.668414.256990@q69g2000hsb.googlegroups.com> Message-ID: <5f31fvF3asl6lU1@mid.individual.net> James Harris wrote: > With that the time would range to +/- 9000 > quintillion years (18 digits) Use the Big Bang as the epoch, and you won't have to worry about negative timestamps. -- Greg From mensanator at aol.com Fri Jul 13 17:32:03 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Fri, 13 Jul 2007 14:32:03 -0700 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> <1184351416.166930.290710@k79g2000hse.googlegroups.com> Message-ID: <1184362323.476796.22570@w3g2000hsg.googlegroups.com> On Jul 13, 2:52 pm, Wayne Brehaut wrote: > On Fri, 13 Jul 2007 11:30:16 -0700, Paul McGuire > wrote: > > > > > > >On Jul 13, 1:20 pm, Wayne Brehaut wrote: > >> On Mon, 09 Jul 2007 23:51:25 -0700, "mensana... at aol.com" > > >> wrote: > >> >On Jul 9, 11:42?pm, Paul McGuire wrote: > >> >> On Jul 9, 11:21 pm, "Jim Langston" wrote:> In Python 2.5 on intel, the statement > >> >> > 2**2**2**2**2 > >> >> > evaluates to>>> 2**2**2**2**2 > > >> >> > 200352993040684646497907235156025575044782547556975141926501697371089405955 63114 > >> >> > 530895061308809333481010382343429072631818229493821188126688695063647615470 29165 > >> >> > 041871916351587966347219442930927982084309104855990570159318959639524863372 36720 > > >> >> > > >> >> Exponentiation is right associative, so this is the same as: > > >> >> 2**(2**(2**(2**2))) > >> >> 2**2**2**4 > >> >> 2**2**16 > >> >> 2**65536 > > >> >> 2=10**0.3010, so 2**65536 is approx 10**19726 > > >> >> There are 19730 digits in your answer, > > >> >>>> import gmpy > >> >>>> n = 2**2**2**2**2 > >> >>>> gmpy.numdigits(n) > >> >19729 > > >> >Did you count the 'L'? > > >> numdigits(n)? > > >> What? 'L' is a digit in Python? I'm going back to Fortran! > > >> wwwayne > > >> >>so this seems to be at least in > >> >> the ball park. > > >> >> -- Paul- Hide quoted text - > > >> - Show quoted text -- Hide quoted text - > > >> - Show quoted text - > > >'L' counts for 50, but only when you use Roman font. > > WTL?! Not Times New Roman I hope? > > Now I'll have to extend my remarks below to include: > > L**L**L > D**D**D > M**M**M > etc. (since I don't recall what comes next) > > though these (L, D, M, ...) would seem to be numbers rather than > digits: the Romans used a base-1 system No, "base" refers to a Positional Number system for which radix 1 is undefined. You can call Roman Numerals a Tally System of Radix 1. Tally sytems ARE defined for radix 1, but operate completely different from positional systems. > [for purposes of this > argument, at least] so I is the only Roman digit* and the others are > just shorthand for: > > I = 1 > V = IIIII > X = I*10 > L = I*50 > D = I*500 > M = I*1000 > etc. > > --- > For those who don't know which Roman digit I represents: > > | > _\|/__ > > wwwayne > > > > > > >-- Paul From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 10 10:46:25 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 10 Jul 2007 16:46:25 +0200 Subject: Dynamic method In-Reply-To: References: Message-ID: <46939ba9$0$32159$426a74cc@news.free.fr> Daniel Nogradi a ?crit : >> I have an issue I think Python could handle. But I do not have the >> knowledge >> to do it. >> >> Suppose I have a class 'myClass' and instance 'var'. There is function >> 'myFunc(..)'. I have to add (or bind) somehow the function to the >> class, or >> the instance. Any help, info or point of reference is wellcome.... > > How about this (note the first argument 'self' which is the instance > itself in the second case): > > > > def method_for_instance( message ): > print message > > def method_for_class( self, message ): > print message > > class myClass( object ): > pass > > inst = myClass( ) > inst.method = method_for_instance > > inst.method( 'hello' ) This won't work as expected: class Bidule(object): def __init__(self, name): self.name = name def greet(self, who): print "hello %s, my name is %s" % (who, self.name) b = Bidule('Bruno') b.greet = greet b.greet('Daniel') => Traceback (most recent call last): File "", line 1, in File "/tmp/python-23258Nq5.py", line 10, in b.greet('Daniel') TypeError: greet() takes exactly 2 arguments (1 given) The point is that Python functions are descriptor objects that, when looked up, return a (bound or unbound) method object wrapping themselves. So to attach functions as method *on a per-instance basis*, you either need to use new.instancemethod (as explained by Alex), or directly use the descriptor protocol, ie: b.greet = greet.__get__(b) b.greet('Daniel') => hello Daniel, my name is Bruno Note that you don't need this to attach a function as method to a class - the descriptor protocol will then JustWork(tm). HTH From steven.bethard at gmail.com Wed Jul 11 09:14:53 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 11 Jul 2007 07:14:53 -0600 Subject: bool behavior in Python 3000? In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Tue, 10 Jul 2007 17:47:47 -0600, Steven Bethard wrote: >> But I think all you're really saying is that newbies don't expect things >> like +, -, *, etc. to work with bools at all. Which I agree is probably >> true. > > No, what I am saying is that True and False being integers under the hood > is a surprising implementation detail. It has no _inherent_ benefit: it > is merely a practical way to bring bools into the language while > remaining backward compatible. For Python 2.x, that was the least bad > solution to the issue "oops, we should have included a bool type". > > Python 3 is allowed to break backwards compatibility, and there is no > reason I can see to keep the current hack. Remember that while Python 3 is allowed to break backwards compatibility, it's only supposed to do it when there are concrete benefits. Clearly there are existing use cases for treating bools like ints, e.g. from Alexander Schmolck's email: (x < b) * f(x) -1 ** (i == j) If you want to remove this functionality, you're going to need to provide some new use cases that it satisfies that are clearly more important than these existing ones. STeVe From steve at REMOVE.THIS.cybersource.com.au Tue Jul 10 19:17:51 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 11 Jul 2007 09:17:51 +1000 Subject: bool behavior in Python 3000? References: <5ficp9F3cram2U2@mid.individual.net> Message-ID: On Tue, 10 Jul 2007 23:42:01 +0200, Bjoern Schliessmann wrote: > Alan G Isaac wrote: > >> My preference would be for the arithmetic operations *,+,- >> to be given the standard interpretation for a two element >> boolean algebra: >> http://en.wikipedia.org/wiki/Two-element_Boolean_algebra > >>>> [bool(True+True), bool(True+False)] > [True, True] > > Works for me, or did I misunderstand you? It seems to me that you deliberately misunderstood him. Why else would you type-cast the integers 2 and 1 to bools to supposedly demonstrate that there's nothing wrong with operations between bools returning ints? I mean, by that logic, it should be okay if we had False = [] True = [None] because: bool(False + True), bool(True + True) also gives (True, True). But that doesn't justify the choice of bools being lists any more than it justifies the choice of bools being ints. -- Steven. From steve at holdenweb.com Sun Jul 8 09:54:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 08 Jul 2007 09:54:05 -0400 Subject: socket.makefile() buggy? In-Reply-To: <1183892789.434028.15370@x35g2000prf.googlegroups.com> References: <1183892789.434028.15370@x35g2000prf.googlegroups.com> Message-ID: That's a pretty pejorative subject line for someone who's been programming Python [guessing by the date of your first post] for about a month. Perhaps "Incomprehensible behavior from socket.makefile()", or "I have written a buggy network application"? That would at least show that you are considering the possibility you yourself are the cause of the problem ;-) Python has been around for a long time, so you should ask yourself how likely it is that you would be the first to discover such a fundamental flaw? I'd be very surprised if someone doesn't point you at an article on "how to ask smart questions", but I will content myself with that oblique reference. ahlongxp wrote: > socket.makefile() may lose data when "connection reset by peer". > and socket.recv() will never lose the data. > > change the "1" to "0" in the client code to see the difference. > > confirmed on both windows and linux. > > so I guess there is a problem with makefile(). > > # Echo server program > import socket > > HOST = '' # Symbolic name meaning the local host > PORT = 50007 # Arbitrary non-privileged port > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > s.bind((HOST, PORT)) > s.listen(1) > while(1): > conn, addr = s.accept() > print 'Connected by', addr > conn.settimeout(1) > toread = 99 > retrytime = 0 > reads = 0 > while reads < toread and retrytime < 10: > try: > data = conn.recv(min(32,toread-reads)) > if not data: continue > print data > reads += len(data) > except: > retrytime += 1 > print "timeout %d" % retrytime > continue > #conn.shutdown(socket.SHUT_RD)#no more read > if reads == toread: > conn.send("OK") > else: > conn.send("NOT OK") > conn.close() > > # Echo client program > import socket > > HOST = 'localhost' # The remote host > PORT = 50007 # The same port as used by the server > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect((HOST, PORT)) > for i in range(12): > print "time %d" % i > try: > s.send('0123456789') > except socket.error, e: > print "socket error:", e > break > #data = s.recv(1024) > #print "data %d" %i, data > #s.shutdown(socket.SHUT_WR)#no more write > > ''' > try changing 1 to 0. > ''' > if 1: > data=s.recv(1024) > else: > rf = s.makefile("rb") > data = rf.read() > rf.close() > s.close() > print 'Received', repr(data) > > The big problem here seems to be that your server is closing the socket after reading 99 bytes, but the client is actually sending 120. If you change the "99" in the server to "120" you will see that the client works when it uses the makefile().read(). I can't be bothered to debug the exact reason why the 21 bytes of buffered data doesn't cause a problem with the recv() version, but I wouldn't regard the error you are getting as a bug in Python, rather as a bug in your application. The underlying cause of all this appears to be your failure to understand that network protocols should ideally allow the endpoints to determine when a complete message has been transmitted, and to consume all transmitted data. You can't just ignore some or all of a client request and expect it not to cause problems. If you look at some of the better-known TCP-based application protocols you will see they take pains to ensure that clients and servers can deterministically parse each others' messages. In summary, a better protocol design will cause you rather less grief and a little more humility will result in less acidity from crabby old geeks like 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 knipknap at gmail.com Tue Jul 3 11:54:25 2007 From: knipknap at gmail.com (Samuel) Date: Tue, 03 Jul 2007 08:54:25 -0700 Subject: Debugging "broken pipe" (in telnetlib) In-Reply-To: References: <1183464742.148754.120550@w5g2000hsg.googlegroups.com> Message-ID: <1183478065.872544.88680@q69g2000hsb.googlegroups.com> On Jul 3, 3:03 pm, Jean-Paul Calderone wrote: > EPIPE results when writing to a socket for which writing has been shutdown. > This most commonly occurs when the socket has closed. You need to handle > this exception, since you can't absolutely prevent the socket from being > closed. The exception is already caught and logged, but this is really not good enough. By "handling this exception", do you mean that there is a way to handle it such that the connection still works? I found some code that attempts to retry when SIGPIPE was received, but this only results in the same error all over again. Why can this not be prevented (in the general case)? Unless something fancy happened, what can cause the socket to close? Looking at the raw data received by the connected host, the connection gets lost in mid- stream; I can not see anything that might cause the remote side to close the connection (in which case I'd expect a "connection reset by peer" or something). > There might be some other change which would be appropriate, though, > if it is the case that something your application is doing is causing the > socket to be closed (for example, sending a message which the remote side > decides is invalid and causing it to close the socket explicitly from its > end). The program is doing the same thing repeatedly and it works 95% of the time, so I am fairly sure that nothing special is sent. > It's difficult to make any specific suggestions in that area without > knowing exactly what your program does. Unfortunately the application is rather complex and a simple test case is not possible. Basically, it creates a number of daemon threads, each of which creates a (thread local, non-shared) instance of telnetlib and connects to a remote host. Are there any special conditions that must be taken care of when opening a number of sockets in threads? (The code runs on AIX 4.1, where Python supports native OS threads.) -Samuel From bignose+hates-spam at benfinney.id.au Thu Jul 12 07:53:57 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 12 Jul 2007 21:53:57 +1000 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: <873aztltwq.fsf@benfinney.id.au> Ilya Zakharevich writes: > *This* was my question; and with kitchentop book, one cannot expect > to find such an answer. If interested, Wiki looks like a good place > to look it up. I don't know what Wiki[0] has to do with it, but just to check: Nope, can't find any existing page about it. [0] Left unqualified, referring to a site named "Wiki" refers to *the* Wiki, at . If you mean some other subsequent Wiki site, you'll need to be more specific. -- \ "Consider the daffodil. And while you're doing that, I'll be | `\ over here, looking through your stuff." -- Jack Handey | _o__) | Ben Finney From wbrehaut at mcsnet.ca Fri Jul 13 19:47:28 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Fri, 13 Jul 2007 17:47:28 -0600 Subject: A Python newbie ask a simple question References: <1184351716.298630.80670@z28g2000prd.googlegroups.com> Message-ID: <8tuf935iukfb4ugtg526l5jorflqdrud61@4ax.com> On Fri, 13 Jul 2007 14:51:52 -0400, "Jeff McNeil" wrote: >The raw_input built-in returns a string. The '[0]' subscript returns >the first character in the user supplied response as strings support >indexing. > >[GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin >Type "help", "copyright", "credits" or "license" for more information. >>>> mystr = "asdf" >>>> mystr[0] >'a' >>>> > >>>> raw_input("Another one, please: ")[0] >Another one, please: ASDF >'A' >>>> > >-Jeff And, as I'm sure Jeff intended to add, you should always try to answer such questions for yourself by just trying a few examples. An advantage of Python is that it's very quick and easy to test one idea at a time without having to create a complete program skeleton before getting started as you would have to in some other languages (such as Java). It also wouldn't hurt to start with one of the many introductory tutorials, some referenced in similar threads above in this group under topics like: Off Topic: What is the good book to learn Python ? Want to learn Python Start to see what others recommend you start with. Or just take a common suggestion and go to: http://www.python.org/doc/ and check out some of the beginners' resources listed and linked to there, such as the "offical" tutorial: http://docs.python.org/tut/tut.html or the widely used wiki site: http://wiki.python.org/moin/BeginnersGuide or the list of Introductory Books: http://wiki.python.org/moin/IntroductoryBooks It may be that none of these answer the specific question you have, but if you start with some of these you'll possibly get a more efficient and enjoyable start than trying to find details of one particular example--and you'll then also have a number of resources at hand with which to try to find your own answers. In case you still have questions, you can always ask in this friendly group; though perhaps more appropriate for "getting started" questions might be the Python Tutorial list at: http://mail.python.org/mailman/listinfo/tutor I use ActivePython a lot, (from ActiveState at http://aspn.activestate.com/ASPN/Python/Downloads/), and use Help, Python Manuals, Python Documentation instead of having to store, open, and maintain the most commonly used dfocumentation separately. Note that the Tutorial is listed here, so it's conveniently located and easy to copy code and paste into the interactive window to test! Or you can use the usual Help Index facility to find the description of "raw_input": === raw_input( [prompt]) If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised. Example: === Knowing this, and having checked out some of the tutorials so you know that [0] is the first element of any "indexable object" (sequence); or using the Help Index again with "sequence" (since you will probably have noted from your tutorial exercises that strings are one type of sequence) you find that one of the operations on strings is: s[i] i'th item of s, origin 0 so the answer to your question: What does the statement "choice = raw_input(prompt)[0]" mean? is now obvious. And the more tutorials you work through, and the more examples you try, the more such statements will be "obvious" or easy to figure out! Happy pythoning! wwwayne >On 7/13/07, xing93111 at gmail.com wrote: >> what does the statement "choice = raw_input(prompt)[0]" mean? I don't >> know why there is a '[0]' in the statement. >> >> Thank you very much >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> From bbxx789_05ss at yahoo.com Mon Jul 2 16:34:32 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 02 Jul 2007 13:34:32 -0700 Subject: subprocess -- broken pipe error In-Reply-To: References: <1183396350.429008.185200@n2g2000hse.googlegroups.com> <1183397577.959518.264230@g4g2000hsf.googlegroups.com> <1183403782.214378.270510@m36g2000hse.googlegroups.com> Message-ID: <1183408472.222538.206800@57g2000hsv.googlegroups.com> On Jul 2, 2:12 pm, Steve Holden wrote: > a) Who told you pipes should be unbuffered by default, and b) what difference > does that make anyway? > a) The docs. b) If the pipes were buffered then writing a small amount of data like "text3" to the pipe would cause the other side to hang forever thereby providing a possible explanation for the results. > > > It just hangs, and then when I hit Ctrl+C and look in the file, the > > data isn't in there. > > Of course it does, for the reasons mentioned above. file.read() only > returns when it has consumed *all* the data from the file (which means > the write must close the file for the reader to be able to return). > That doesn't seem like a very good explanation, since the only thing written to the file(i.e. stdin) was "text3", and the write() was unbuffered, so the read() could consume all the data without the write() closing the file--there was no more data. From samfeltus at gmail.com Thu Jul 26 14:14:28 2007 From: samfeltus at gmail.com (SamFeltus) Date: Thu, 26 Jul 2007 18:14:28 -0000 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185453726.559470.122480@x40g2000prg.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> <46a7b908$0$32130$426a34cc@news.free.fr> <1185453726.559470.122480@x40g2000prg.googlegroups.com> Message-ID: <1185473668.099991.240670@19g2000hsx.googlegroups.com> PHP is just a more inclusive community. The PHP community is more concerned with the casual user and the end user. This is PHP's core strength, and one of Python's core weaknesses. The Python community would be wise to adopt PHP's concern for the end user. That being said, I don't think you will find PHP easier than Python. I think the reverse is true, except in the simplest cases. Also, Python is economical and easy to use if you go with a Python centric web host, such as Web Faction. From denishajoely1 at gmail.com Fri Jul 27 07:42:45 2007 From: denishajoely1 at gmail.com (denishajoely1 at gmail.com) Date: Fri, 27 Jul 2007 11:42:45 -0000 Subject: Internet surveying with EZquestionnaire Message-ID: <1185536565.505178.157280@e16g2000pri.googlegroups.com> Hi , Hope you are doing great. Recently I needed to conduct a survey on Employee Satisfaction at the work place to design an employee retention program. I was searching on the net for help on conducting surveys and I came across www.ezqustionnaire.com They had a survey template on employee satisfaction (with questions), thereby making my work a lot easier. They have a basic package for free to conduct simple surveys with the option to be upgraded any time. EZquestionnaire team provides a powerful web survey management system. You can create multi-page surveys with branches and your own graphics. They have some real-time online reports which helped me analyze my survey results very swiftly >From signing up to taking a quick tour to compiling and publishing the survey took less than 30 Minutes. We need more tools like these to make our work easier and save time. Check them out at www.ezquestionnaire.com View Demo: http://216.97.88.253/marketing/ezqdemo/ezqsurvey.htm Regards Denisha Joely From stefan.behnel-n05pAM at web.de Thu Jul 5 04:28:09 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 05 Jul 2007 10:28:09 +0200 Subject: Problem with building extension in Python In-Reply-To: <1183622938.086813.18950@k79g2000hse.googlegroups.com> References: <1183622938.086813.18950@k79g2000hse.googlegroups.com> Message-ID: <468CAB99.2080907@web.de> vedrandekovic at v-programs.com wrote: > I have already install Microsoft visual studio .NET 2003 and MinGw, > when I try to build a extension: > > python my_extension_setup.py build ( or install ) , I get an error: > > LINK : fatal error LNK1141: failure during build of exports file > error: command '"C:\Program Files\Microsoft Visual Studio .NET > 2003\Vc7\bin\link.exe"' failed with exit status 1141. > > What shoud I do??? Tell us what the actual error message is? What you provide here is only the last line, the real error is most likely before that. Please provide a bit more of the output, anything that might be helpful to understand the problem. Stefan From bblais at bryant.edu Tue Jul 24 13:16:27 2007 From: bblais at bryant.edu (Brian Blais) Date: Tue, 24 Jul 2007 13:16:27 -0400 Subject: Tix not properly installed on OS X? In-Reply-To: <46A60C80.60502@codebykevin.com> References: <48B39FEC-D3B9-4FAF-AD45-0DD744D8D289@bryant.edu> <46A60C80.60502@codebykevin.com> Message-ID: <98214A15-2E34-4C0E-BB34-2FD8A92A2ACC@bryant.edu> On Jul 24, 2007, at Jul 24:10:28 AM, Kevin Walzer wrote: > You need an up-to-date installation of the base Tix package on your > system, in the same path as your Tcl/Tk libraries. I downloaded and > built the most recent version of Tix from http://tix.sf.net (dated > November 2006) and the Python samples run fine. So I tried to build Tix, and it complains about a tcl header file (tclPort.h). My Tcl stuff is in /System/Library/Frameworks/ Tcl.framework/Versions/8.4/, but the header file doesn't exist. I assume I need to download the source for Tcl and build that, or is it enough to have the headers from the source of tcl? I just don't want to break something that is already there. thanks! bb -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Mon Jul 30 02:15:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 30 Jul 2007 03:15:48 -0300 Subject: making a variable available in a function from decorator References: Message-ID: En Sun, 29 Jul 2007 19:22:47 -0300, rkmr.em at gmail.com escribi?: > I create a variable in a decorator. i want to be able to access that > variable in the function to be decorated. How to do this? Combining `wraps` and `partial` from the functools standard module : import functools def my_decorator(f): newvar = 1234 # compute your desired variable @functools.wraps(f) def wrapper(*args, **kwds): print "Calling", f.func_name return f(*args, **kwds) return functools.partial(wrapper, newvar=newvar) @my_decorator def foo(x,y,**kw): print "x=",x,"y=",y # access the variable as a keyword argument if "newvar" in kw: print "newvar",kw["newvar"] py> foo(1,2) Calling foo x= 1 y= 2 newvar 1234 -- Gabriel Genellina From martin.clausen at gmail.com Wed Jul 4 16:37:24 2007 From: martin.clausen at gmail.com (Martin) Date: Wed, 04 Jul 2007 20:37:24 -0000 Subject: 15 Exercises to Know A Programming Language In-Reply-To: <1183463230.092640.102720@j4g2000prf.googlegroups.com> References: <1183456696.168214.114900@o61g2000hsh.googlegroups.com> <1183463230.092640.102720@j4g2000prf.googlegroups.com> Message-ID: <1183581444.751837.191220@k79g2000hse.googlegroups.com> On Jul 3, 1:47 pm, John Machin wrote: > On Jul 3, 7:58 pm, Martin wrote: > > > > > I am trying to improve my Python skills through some exercises. > > Currently I am working on Larry's "15 exercises to know a programming > > language " (http://www.knowing.net/ > > PermaLink,guid,f3b9ba36-848e-43f8-9caa-232ec216192d.aspx). The first > > exercise is this: > > > "Write a program that takes as its first argument one of the words > > 'sum,' 'product,' 'mean,' or 'sqrt' and for further arguments a > > series of numbers. The program applies the appropriate function to > > the series." > > > My solution so far is this: > > >http://dpaste.com/13469/ > > > I would really like some feedback. Is this a good solution? is it > > efficient? robust? what could be improved? any not looking for a > > revised solution, hints on what to improve are also very welcome. > > > Martin > > sum is a builtin function in Python 2.3 and later. You could do > something like this: > > try: > sum > except NameError: > def sum(args): > return reduce(operator.add, args) > > Tested with 2.5 back to 2.1, and 1.5.2 :-) Thanks John and Daniel. My revised version now uses sum(). I have started to implement some basic error checking and validation. Martin From owntheweb at gmail.com Mon Jul 9 16:33:05 2007 From: owntheweb at gmail.com (Ultrus) Date: Mon, 09 Jul 2007 20:33:05 -0000 Subject: dealing with nested xml within nested xml within...... In-Reply-To: <1184012322.363949.306330@n60g2000hse.googlegroups.com> References: <1184011424.662766.176530@k79g2000hse.googlegroups.com> <1184012322.363949.306330@n60g2000hse.googlegroups.com> Message-ID: <1184013185.378594.155080@w3g2000hsg.googlegroups.com> > You'd probably write a function that called itself to parse something > like this. Unfortunately, I am not a recursion expert. You can read up > on it though: > > http://www.freenetpages.co.uk/hp/alan.gauld/tutrecur.htmhttp://pythonjournal.cognizor.com/pyj2.2/RecursionByAJChung.html Ah! That's the termage I was looking for. Thanks much for the link. I will research recursion. From rcdailey at gmail.com Tue Jul 31 13:55:44 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 31 Jul 2007 12:55:44 -0500 Subject: Iteration over strings Message-ID: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> Hi, 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. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Jul 10 12:18:23 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 10 Jul 2007 18:18:23 +0200 Subject: bool behavior in Python 3000? References: Message-ID: Alan Isaac wrote: > Is there any discussion of having real booleans > in Python 3000? The last I have seen is http://mail.python.org/pipermail/python-3000/2007-January/005284.html > Hoping the bool type will be fixed will be fixed, Do you care to explain what is broken? Peter From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jul 16 10:29:16 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 16 Jul 2007 16:29:16 +0200 Subject: Dynamic method In-Reply-To: <1i1clx6.1qpf4ykihdj1oN%raims@dot.com> References: <46939ba9$0$32159$426a74cc@news.free.fr> <46949c19$0$23164$426a34cc@news.free.fr> <1i1clx6.1qpf4ykihdj1oN%raims@dot.com> Message-ID: <469b80bb$0$23769$426a34cc@news.free.fr> Lawrence Oluyede a ?crit : > Bruno Desthuilliers > wrote: >>> I agree that in general the solution explained by Alex and you is better. >> They are not "better" - they are correct. > > Another way is to use the 'types' module: True - and that's somewhat cleaner since it doesn't expose the internals of the descriptor protocol. OTHO, it can lead to strange results with callables not implementing the descriptor protocol: class MyCallable(object): def __init__(self, name): self.name = name def __call__(self): print self.name fun = MyCallable('gizmo') class Foo(object): pass f = Foo() f.fun = types.MethodType(fun, f, Foo) f.fun() => Traceback (most recent call last): File "", line 1, in File "/tmp/python-17437zds.py", line 16, in f.fun() TypeError: __call__() takes exactly 1 argument (2 given) From steve at REMOVE.THIS.cybersource.com.au Wed Jul 25 21:27:22 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 26 Jul 2007 11:27:22 +1000 Subject: Flatten a list/tuple and Call a function with tuples References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <7xzm1kqw89.fsf@ruckus.brouhaha.com> Message-ID: On Wed, 25 Jul 2007 09:33:26 -0700, Paul Rubin wrote: > Things > are logically single values or they are logically lists of values Except for strings, and string-like objects. And files. And records/structs, and tuples. And lists. And sets. And bit strings. And tree-like structures. And, well, just about everything really. But apart from those minor exceptions, I agree completely with your recommendation. (Ha ha only serious.) -- Steven. From ptmcg at austin.rr.com Tue Jul 3 09:38:29 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 03 Jul 2007 06:38:29 -0700 Subject: Pretty Scheme, ??? Python In-Reply-To: References: <46895e12$0$5078$ba4acef3@news.orange.fr> <_Ddii.36114$G23.10348@newsreading01.news.tds.net> <1183418938.911025.55340@w5g2000hsg.googlegroups.com> Message-ID: <1183469909.444902.147310@57g2000hsv.googlegroups.com> Neil - >> The above shadows 'id'; I suppose 'ident' would be better. Doh! I found the id() shadowing later, changed my var to id_ so as not to stray from your BNF too much. >> How can I make it barf for testcases like '(+ 2 3))'? It doesn't >> seem to expect an Eof. To force parsing to the end of string, add a StringEnd instance where you expect there to be the end of the input string. Change: waeTree = wae.parseString(t) to: waeTree = (wae + StringEnd()).parseString(t) >> The muss is that, >> since all the __init__ functions now expect a token list instead >> of named arguments, they are now cryptic, and creating AST's >> manually became annoying. The fuss is that I do have to create >> one in With's calc function. It should be unnecessary for the >> AST objects to be so dependent upon the grammar to work >> correctly. I agree 1000%. The pyparsing method for this is to use setResultsName. Here is the grammar, with results names defined to match those in your original. And you are absolutely correct, using named fields like this makes your code MUCH more robust, and less dependent on the grammar. num = Combine( Optional("-") + Word(nums) ).setResultsName("n") id_ = oneOf( list(alphas) ).setResultsName("v") addwae = Group( LPAR + "+" + wae.setResultsName("lhs") + wae.setResultsName("rhs") + RPAR ) subwae = Group( LPAR + "-" + wae.setResultsName("lhs") + wae.setResultsName("rhs") + RPAR ) withwae = Group( LPAR + "with" + LPAR + id_.setResultsName("bound_id") + wae.setResultsName("named_expr") + RPAR + wae.setResultsName("bound_body") + RPAR ) Now your calc methods can refer to them using: self.tokens.lhs self.tokens.bound_id etc. Here is my alternative solution (not using results names). I used the base WAE class to accept the tokens as the initialization var, then unpack the list into variables in each respective calc() method. I did not see the need for a subst() method. There is a complete s-exp parser at the pyparsing wiki examples page: http://pyparsing.wikispaces.com/space/showimage/sexpParser.py -- Paul class WAE(object): ids = {} def __init__(self,tokens): # need to deref element 0 because of Groups self.tokens = tokens[0] class NumWAE(WAE): def calc(self): return int(self.tokens) class IdWAE(WAE): def getId(self): return self.tokens def calc(self): return WAE.ids[self.getId()][-1] class BinOpWAE(WAE): def calc(self): op,a,b = self.tokens return self.opfn(a.calc(), b.calc()) class AddWAE(BinOpWAE): opfn = staticmethod(lambda a,b:a+b) class SubWAE(BinOpWAE): opfn = staticmethod(lambda a,b:a-b) class WithWAE(WAE): def calc(self): op,varid,varexpr,withexpr = self.tokens varname = varid.getId() if varname not in WAE.ids: WAE.ids[varname] = [] WAE.ids[varname].append( varexpr.calc() ) ret = withexpr.calc() WAE.ids[varname].pop() return ret for expr,cls in zip((num,id_,addwae,subwae,withwae), (NumWAE,IdWAE,AddWAE,SubWAE,WithWAE)): expr.setParseAction(cls) for t in tests: print t waeTree = wae.parseString(t)[0] print waeTree.calc() print From robert.kern at gmail.com Thu Jul 26 21:16:27 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Jul 2007 20:16:27 -0500 Subject: Another C API Question In-Reply-To: <1185498383.333248.225360@19g2000hsx.googlegroups.com> References: <1185498383.333248.225360@19g2000hsx.googlegroups.com> Message-ID: beginner wrote: > Hi, > > I run into another C API question. What is the simplest way to convert > an PyObject into a double? > > For example, I have > > PyObject *obj; > > I know obj is a number, but I do not know the exact type. How can I > convert it to double without writing a giant switch() that exhausts > every single type of number? Convert it to a Python float using PyNumber_Float(), then use PyFloat_AsDouble() to get the C double value from it. -- 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 nagle at animats.com Wed Jul 11 18:23:59 2007 From: nagle at animats.com (John Nagle) Date: Wed, 11 Jul 2007 15:23:59 -0700 Subject: Problem with Python's "robots.txt" file parser in module robotparser In-Reply-To: References: <0T7li.5316$rL1.2716@newssvr19.news.prodigy.net> Message-ID: Nikita the Spider wrote: > > Hi John, > Are you sure you're not confusing your sites? The robots.txt file at > www.ibm.com contains the double slashed path. The robots.txt file at > ibm.com is different and contains this which would explain why you > think all URLs are denied: > User-agent: * > Disallow: / > Ah, that's it. The problem is that "ibm.com" redirects to "http://www.ibm.com", but but "ibm.com/robots.txt" does not redirect. For comparison, try "microsoft.com/robots.txt", which does redirect. John Nagle From horpner at yahoo.com Thu Jul 5 15:31:33 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 05 Jul 2007 19:31:33 GMT Subject: Where is the syntax for the dict() constructor ?! References: <468D1D9D.6060002@gmail.com> <468D3445.2060408@gmail.com> Message-ID: On 2007-07-05, Captain Poutine wrote: > "Reader objects (DictReader instances and objects returned by > the reader() function) have the following public methods: Lucky for you and me, Peter Otten corrected my mistaken advice. > next( ) > Return the next row of the reader's iterable object as a list, > parsed according to the current dialect." > > But that's not enough information for me to use. Also, the doc > says basically "csv has dialects," but doesn't even enumerate > them. Where is the real documentation? It's referring to the fact that csv has no standard to adhere to, so sometimes slightly different ways of quoting and escaping appear in csv files. Apart from that, through configuring a new dialect you can use csv to parse many kinds of delimited data files, not just csv as written by MS apps. Mostly you can use the default 'excel' dialect and be quite happy, since Excel is the main reason anybody still cares about this unecessarily hard to parse (it requires more than one character of lookahead for no reason except bad design) data format. See Library Reference 9.1.2 Dialects and Formatting Paremeters for an explanation of what can be configured. > Also, when I do a print of row, it comes out as: > ['12345', 'ET'] > > But there are no quotes around the number in the file. Why is > Python making it a string? It's a string to start with, since it comes from a text file. Besides, a string is an excellent epresentation for a zip code, since arithmetic upon them is unthinkable. I shared your frustration with the csv module docs when I first read them. But happily you can skip them and just read the easily adapted examples (9.1.5 Examples). -- Neil Cerutti From gentoodev at gmail.com Mon Jul 9 11:42:47 2007 From: gentoodev at gmail.com (Rob Cakebread) Date: Mon, 09 Jul 2007 15:42:47 -0000 Subject: Tool for finding external dependencies In-Reply-To: <1183992896.381070.62280@n60g2000hse.googlegroups.com> References: <1183945183.147231.120180@z28g2000prd.googlegroups.com> <1183990671.337753.106370@k79g2000hse.googlegroups.com> <1183991251.354349.326520@e16g2000pri.googlegroups.com> <1183992896.381070.62280@n60g2000hse.googlegroups.com> Message-ID: <1183995767.335243.197190@i38g2000prf.googlegroups.com> On Jul 9, 7:54 am, kyoso... at gmail.com wrote: > > > mod = modulefinder.ModuleFinder() > mod.run_script(path/to/python_script.py) > mod.report() > > > > Mike Nope. All of those tools and the code above show *all* imports/ dependencies, which is way too much information. I just need the 'external' dependencies, like in the example from pylint I pasted above. If nothing exists I'll just have to figure out how pylint does it. I'm working on g-pypi which creates ebuilds for Gentoo Linux. For packages that use setuptools I can get the dependencies easily enough because of 'install_requires', but for packages that don't, I need another way to find them. Thanks, Rob From ptmcg at austin.rr.com Mon Jul 23 17:04:50 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 23 Jul 2007 14:04:50 -0700 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: <7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com> <1185204512.255392.105820@r34g2000hsd.googlegroups.com> Message-ID: <1185224690.523486.108680@g4g2000hsf.googlegroups.com> On Jul 23, 12:43 pm, ed... at holyrood.ed.ac.uk (Eddie Corns) wrote: > Paul McGuire writes: > >On Jul 23, 5:53 am, ed... at holyrood.ed.ac.uk (Eddie Corns) wrote: > >> Wolfgang Strobl writes: > >> >few of James Gimple's snippets from "Algorithms in SNOBOL4" > >> >(->http://www.snobol4.org/) as an exercise using that library might help > >> >to get a better appreciation. Perhaps I'll try, eventually ... > > >> I never noticed them or the PDF of the book there before. Some Friday > >> afternoon reading for sure. > > >> Personally I hope to get more to time to look at a combination of Lua and > >> PEGs (http://en.wikipedia.org/wiki/Parsing_expression_grammar) for my parsing > >> needs. > > >> Eddie > >If you get a chance to look at pyparsing, I'd be interested in your > >comments. The PEG page and the SNOBOL implementation have many > >similar concepts with pyparsing (or is it the other way around?). > > It's on my list of things to get round to. > > I think what I'm really after though is a parsing DSL. I only did only one > fairly small project in SNOBOL but I was impressed at the ease with which I > could express the problem (some googling suggested that many end users found > the same). I guess I want SNOBOL embedded in a modern language with scoping > etc. Python is antithetical to (this class of) DSLs (IMHO) :( > > Probably what I really need is parser combinators in Haskell or maybe camlp4 > or some such exotica but unfortunately I've never heard of them. > > Eddie- Hide quoted text - > > - Show quoted text - I have had pyparsing users refer to pyparsing as an in-Python DSL, and others make comparisons between pyparsing and Parsec (monadic combinator in Haskell). I'm not sure why you would say this approach is antithetical to Python - the builtin support for operator overloading, __call__, __len__, __nonzero__(soon to be __bool__), __set/getattr__, etc. permit you to impart quite a bit of expressive behavior to your parsing classes. What I tried to do with pyparsing was to emulate Python's builtin container classes and object instances with the results that get returned from invoking a parser, so that the after-parsing work would feel natural to established Python users. If you want to just see some existing BNF's implemented in pyparsing, you can view them online at the pyparsing wiki. Here are some representative examples: http://pyparsing.wikispaces.com/space/showimage/simpleSQL.py http://pyparsing.wikispaces.com/space/showimage/fourFn.py http://pyparsing.wikispaces.com/space/showimage/jsonParser.py -- Paul From the.mindstorm.mailinglist at gmail.com Fri Jul 6 04:56:33 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Fri, 06 Jul 2007 01:56:33 -0700 Subject: MethodType/FunctionType and decorators In-Reply-To: <1i0snfy.9sv6evjonlj6N%aleax@mac.com> References: <1183589529.198694.109440@m36g2000hse.googlegroups.com> <1183591053.434640.119550@o61g2000hsh.googlegroups.com> <1i0qoq9.u1fu2g63fkmxN%aleax@mac.com> <1183623479.913816.301230@g4g2000hsf.googlegroups.com> <1183626989.983470.94950@o61g2000hsh.googlegroups.com> <1183641471.753457.269030@m36g2000hse.googlegroups.com> <1183644112.049339.159460@c77g2000hse.googlegroups.com> <1183673911.790367.73090@n2g2000hse.googlegroups.com> <1i0snfy.9sv6evjonlj6N%aleax@mac.com> Message-ID: <1183712193.953105.277460@c77g2000hse.googlegroups.com> On Jul 6, 6:19 am, a... at mac.com (Alex Martelli) wrote: > Alex Popescu wrote: > > ... > > > frameworks (TestNG is not a unit testing framework, > > but a full flavored testing framework that fits perfectly functional > > testing, integration testing, and with some of the > > very advanced features even performance and load testing). > > Nice! Does it have any integration/interoperability with FIT/Fitnesse, > btw? For certain kinds of "functional testing" (where the specs are to > be mostly written by people with no programming skills but strong > business, accounting, &c, i.e., people _used_ to thinking in terms of > tables and spreadsheets) I find that approach very interesting... > > Alex That's an interesting idea! We never tried that before but I will definitely look into it. Thanks for the suggestion Alex. ./alex -- .w( the_mindstorm )p. From the.mindstorm.mailinglist at gmail.com Wed Jul 18 06:50:20 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Wed, 18 Jul 2007 10:50:20 +0000 (UTC) Subject: Posted messages not appearing in this group References: <1184742315.618696.202600@z24g2000prh.googlegroups.com> Message-ID: Sanjay gmail.com> writes: > > Hi All, > > I tried posting in this group twice since last week, but the messages > did not appear in the forum. Don't know why. Trying this message > again... > > Sanjay > Something similar seemed to happen to me too, but when checking with gmane I've noticed that all my posts got in (and now I am trying to figure out how can I apologize for multiple posts :-) ). bests, ./alex -- .w( the_mindstorm )p. From david.hirschfeld at centrica.co.uk Tue Jul 3 05:46:22 2007 From: david.hirschfeld at centrica.co.uk (Dave) Date: Tue, 3 Jul 2007 09:46:22 +0000 (UTC) Subject: DatePart From String References: <43232.8877890997$1183453330@news.gmane.org> Message-ID: Robert Rawlins - Think Blue thinkbluemedia.co.uk> writes: > I?ve tried using the time.strptime() function without much success so > thought I?d come and ask your advice. > How exactly does it not work?? This works for me: from time import mktime, strptime from datetime import datetime datetime_string = '2007-02-01 00:00:00' datetime_object = datetime.fromtimestamp( mktime(strptime(datetime_string,'%Y-%m-%d %H:%M:%S'))) print datetime_object.year print datetime_object.month print datetime_object.day print datetime_object.hour print datetime_object.minute print datetime_object.second HTH, Dave From apetresc at uwaterloo.ca Wed Jul 18 20:55:59 2007 From: apetresc at uwaterloo.ca (Adrian Petrescu) Date: Wed, 18 Jul 2007 17:55:59 -0700 Subject: Interpreting os.lstat() Message-ID: <1184806559.224636.266500@e9g2000prf.googlegroups.com> I'm playing with FUSE's python bindings, and I'm expected to return a list that matches the structure of a python os.lstat() call. So, for example: >>> import os >>> os.lstat("/home/adrian/fuse_test") (16877, 10666636L, 2050L, 4, 1000, 1000, 4096L, 1184803155, 1184170289, 1184170289) The problem is, I'm not sure how to recreate this kind of structure because I have no idea about the significance of the entries. The docstring wasn't much help: >>> print os.lstat.__doc__ lstat(path) -> stat result Like stat(path), but do not follow symbolic links. >>> print os.stat.__doc__ stat(path) -> stat result Perform a stat system call on the given path. I checked the online Python documentation at http://python.org/doc/1.5.2/lib/module-stat.html but it just says to "consult the documentation for your system.". At this point I'm guessing that os.lstat is nothing more than a wrapper for some Linux system call, so I looked up the results of running 'stat' on the same file, and I get: adrian at adrian-desktop:~$ stat fuse_test/ File: `fuse_test/' Size: 4096 Blocks: 8 IO Block: 4096 directory Device: 802h/2050d Inode: 10666636 Links: 4 Access: (0755/drwxr-xr-x) Uid: ( 1000/ adrian) Gid: ( 1000/ adrian) Access: 2007-07-18 19:59:15.000000000 -0400 Modify: 2007-07-11 12:11:29.000000000 -0400 Change: 2007-07-11 12:11:29.000000000 -0400 I can see some correspondence between the "stat" call and os.lstat (for example, I'm guessing os.lstat(path)[6] represents the filesize), but I can't see the correspondence between some of the other fields. What does os.lstat(path)[0] represent? Are those last three the created/modified/accessed times in unix time or what? Basically, what does each field of os.lstat(path) represent? My system is Linux 2.6.20 and I'm using Python 2.5.1 Thanks in advance, guys! =) From http Thu Jul 12 21:05:54 2007 From: http (Paul Rubin) Date: 12 Jul 2007 18:05:54 -0700 Subject: Fastest way to convert a byte of integer into a list References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> <1184284461.506663.75500@g12g2000prg.googlegroups.com> <1184284861.695430.99300@e9g2000prf.googlegroups.com> <7xr6ndtae7.fsf@ruckus.brouhaha.com> <1184287796.252097.46660@x35g2000prf.googlegroups.com> Message-ID: <7xfy3taz9p.fsf@ruckus.brouhaha.com> John Machin writes: > > numlist = lookup_table[num] > > where lookup_table is a precomputed list of lists. > Ummm ... didn't the OP say he had 32-bit numbers??? He asked about 8 bit numbers. I saw something about 32-bit numbers but figured those would be split into bytes or something: (untested and I don't remember if this is the byte order wanted): from itertools import chain numlist = list(chain(lookup_table[(num>>i)&0xff] for i in xrange(0,32,8))) From stefan.behnel-n05pAM at web.de Thu Jul 26 10:34:25 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 26 Jul 2007 16:34:25 +0200 Subject: Parsing XML with ElementTree (unicode problem?) In-Reply-To: <1185459815.871401.35320@b79g2000hse.googlegroups.com> References: <1185200976.082516.105420@57g2000hsv.googlegroups.com> <1185279975.254458.7510@57g2000hsv.googlegroups.com> <1185287404.060182.314750@57g2000hsv.googlegroups.com> <46A618E9.6010304@web.de> <1185449094.998635.67870@w3g2000hsg.googlegroups.com> <1185455621.498620.51650@i13g2000prf.googlegroups.com> <1185459815.871401.35320@b79g2000hse.googlegroups.com> Message-ID: <46A8B0F1.1010405@web.de> oren.tsur at gmail.com wrote: > On Jul 26, 3:13 pm, John Machin wrote: >> On Jul 26, 9:24 pm, oren.t... at gmail.com wrote: >> >>> OK, I solved the problem but I still don't get what went wrong. >>> Solution - use tree builder in order to create the new xml file >>> (previously I was "manually" creating it). >>> I'm still curious so I'm adding a link to a short and very simple >>> script that gets an xml (containing non ascii chars) from the web and >>> saves some of the elements to 2 different local xml files - one is >>> created by XMLWriter and the other is created manually. you could see >>> that parsing of the first local file is OK while parsing of the >>> "manually" created xml file fails. obviously I'm doing something wrong >>> and I'd love to learn what. >>> the toy script:http://staff.science.uva.nl/~otsur/code/xmlConversions.py >> Simple file comparison: >> >> File 1: ... Modern Church. <p>The book ... >> File 2: ... Modern Church.

The book ... >> >> Firefox: >> >> XML Parsing Error: mismatched tag. Expected:

. >> Location: file:///C:/junk/myDeVinciCode166_2.xml >> Line Number 3, Column 1153: >> >> The...Church.

The...thrill. >> ------------------------------------------^ > > yup, but why does this happen - on the script side - I write the exact > same strings, of content with supposedly, same encoding, so why the > encoding is different? Read the mail. It's not the encoding, it's the "

" which does not get through as a tag in the first file. Stefan From infocat at earthlink.net Sun Jul 8 02:59:55 2007 From: infocat at earthlink.net (Frank Swarbrick) Date: Sun, 08 Jul 2007 00:59:55 -0600 Subject: socket: connection reset by server before client gets response In-Reply-To: <1183870439.595652.305590@z28g2000prd.googlegroups.com> References: <1183819907.249945.239700@o11g2000prd.googlegroups.com> <1183827514.109496.252870@d30g2000prg.googlegroups.com> <46902a45$0$331$e4fe514c@news.xs4all.nl> <1183870439.595652.305590@z28g2000prd.googlegroups.com> Message-ID: <5fbgbdF3b4vgcU1@mid.individual.net> ahlongxp wrote: >> Post the code. > ok. > here is the code: > > # Echo server program > import socket > > HOST = '' # Symbolic name meaning the local host > PORT = 50007 # Arbitrary non-privileged port > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > s.bind((HOST, PORT)) > s.listen(1) > conn, addr = s.accept() > print 'Connected by', addr > conn.settimeout(1) > toread = 99 > retrytime = 0 > reads = 0 > while reads < toread and retrytime < 10: > try: > data = conn.recv(min(32,toread-reads)) > if not data: continue > print data > reads += len(data) > except: > retrytime += 1 > print "timeout %d" % retrytime > continue > if reads == toread: > conn.send("OK") > else: > conn.send("NOT OK") > conn.close() > > ****************I'm the separate > line********************************************* > > # Echo client program > import socket > > HOST = 'localhost' # The remote host > PORT = 50007 # The same port as used by the server > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s.connect((HOST, PORT)) > for i in range(12): > print "time %d" % i > s.send('0123456789') > #data = s.recv(1024) > #print "data %d" %i, data > #s.shutdown(socket.SHUT_WR)#no more write > data=s.recv(1024) > s.close() > print 'Received', repr(data) > > client is supposed to get the response, either "OK" or "NOT OK". > but the fact is, client gets "Connection reset by peer" (as shown > below) about one in fifth. > ---------------------------------- > Traceback (most recent call last): > File "c.py", line 10, in > s.send('0123456789') > socket.error: (104, 'Connection reset by peer') > ---------------------------------- > > anyway, server is doing well all the time. > > any comments on the design or implementation will be greatly > appreciated. So, umm, what exactly are you trying to accomplish? Here are the results I'm getting: Server: Connected by ('127.0.0.1', 53536) 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 0123456789 012345678 Client: time 0 time 1 time 2 time 3 time 4 time 5 time 6 time 7 time 8 time 9 time 10 time 11 Traceback (most recent call last): File "echo_c.py", line 10, in s.send('0123456789') socket.error: (32, 'Broken pipe') It looks like what is happening is the server only accepts 99 bytes. It then does the send and the close. The client wants to send 120 bytes, 10 bytes at a time. By the time is does the 12th send the server has already finished, closing its socket and exiting. So when the client attempts send #12 the socket is already closed. Thus the error. I'm not sure why you are getting the 'connection reset' instead of 'broken pipe'. Probably different OS. (I'm using Mac OS X 10.4.10.) Anyway, I changed your code slightly, wrapping the send in a try/except block like this: try: s.send('0123456789') except socket.error ,e: print "Socket Error:", e break Now here are my results for the client: time 0 time 1 time 2 time 3 time 4 time 5 time 6 time 7 time 8 time 9 time 10 time 11 error: (32, 'Broken pipe') Received 'OK' The way you had it the program crashed before it could do the receive. Frank From Nomad.C at gmail.com Tue Jul 3 11:13:46 2007 From: Nomad.C at gmail.com (Nomad.C at gmail.com) Date: Tue, 03 Jul 2007 15:13:46 -0000 Subject: python 3.0 or 3000 ....is it worth waiting??? Newbie Question Message-ID: <1183475626.705580.214870@n2g2000hse.googlegroups.com> Hi I'm considering learning Python...but with the python 3000 comming very soon, is it worth waiting for?? I know that the old style of coding python will run parallel with the new, but I mean, its going to come to an end eventually. What do you think?? Chris From kyosohma at gmail.com Mon Jul 16 14:51:16 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 16 Jul 2007 18:51:16 -0000 Subject: Technology solutions for Ruby? In-Reply-To: <1184611602.414529.41090@i38g2000prf.googlegroups.com> References: <469B059C.2050802@cesmail.net> <1184606739.054580.197740@g37g2000prf.googlegroups.com> <1184611602.414529.41090@i38g2000prf.googlegroups.com> Message-ID: <1184611876.692894.17140@g4g2000hsf.googlegroups.com> On Jul 16, 1:46 pm, vasudevram wrote: > On Jul 16, 10:25 pm, vasudevram wrote: > > > > > [ Though the OP posted his message to comp.lang.ruby, I'm cross- > > posting it to comp.lang.python, since he mentions Python as a possible > > alternative he's looking at, and also because I've recommended Python > > for his stated needs. Also, interested to see what other Pythonistas > > have to say in response to my reply. > > - Vasudev] > > > > On Jul 16, 2007, at 2:21 AM, Michael Reiland wrote: > > > At the heart of the issue is the fact that I refuse to use Java for this > > > project, I prefer not to use .Net because of the portability issues, > > and > > I'd like to get away from C++ for obvious reasons. > > > > To me this means Ruby, Python, or, as mentioned above, Perl. If anyone > > > can tell me of a way to meet the above requirements in either Python > > or > > Perl, I'm all ears (I just prefer Ruby). > > > Yes, I think it would be really great for the Ruby community and for > > the growth of the language if wxRuby was more mature as a GUI toolkit. > > (Not knocking the wxRuby developers at all, its great that they've > > even done what they have - I know that creating other language (like > > Ruby) bindings to a C++ lib is a non-trivial task). > > > My suggestion: Python + wxPython + Python DBI + (Py2Exe + InnoSetup) > > *might* meet all your needs. (As with any decision about what software > > technologies to use, you'll have to evaluate the suggested options to > > see if they fit your needs.) > > > Note: I've used and like both Ruby and Python (saying this after using > > many, though not all, language features and libraries of both > > languages), and am not trying to discourage you from using Ruby for > > your needs; its just that, based on your needs as described, it looks > > to me as if Python meets them better than Ruby at present: > > > > 1. GUI - Native Look and Feel. According to wxRuby the bindings aren't > > > mature enough for production use. Does anyone have any experience > > with > > this and/or can you offer alternatives that provide a native look and > > feel (I > > > I don't know enough about wxRuby to comment. > > > wxPython has this (Native Look and Feel), I think (used it some, a > > while ago), not 100% sure, you can check on the site - http:/www.wxpython.org > > - to make sure. The site does say that it is cross-platform: > > > "wxPython is a cross-platform toolkit. This means that the same > > program will run on multiple platforms without modification. Currently > > supported platforms are 32-bit Microsoft Windows, most Unix or unix- > > like systems, and Macintosh OS X. > > " > > > but that doesn't necessarily mean that it will have native look and > > feel on all supported platforms. (The two are not the same thing.) > > That's why you will need to check. > > > wxPython pros: Its fairly easy to learn, at least for simple GUI apps > > (e.g. a few widgets / controls and a file dialog or two). I was able > > to build these simple ones - see the code, article and screenshots > > available here (or from links from here): > > >http://www.packtpub.com/article/Using_xtopdf > > > - in quite a short time, starting from zero knowledge of wxPython (I > > did know some Python from before), just by looking at the sample apps, > > and some reading of the docs. > > > See the quotes about wxPython:http://www.wxpython.org/quotes.php > > > >2. Databases - contemplating using ActiveRecord, but I would like to use > > > ODBC to support multiple types of DB's in a uniform way (if you know > > of > > alternatives to ODBC or ActiveRecord, please let me know). > > > I think, but again, not sure, that Python DBI + appropriate database > > drivers, may meet this need. Basically Python DBI is similar to ODBC > > (roughly), and to Perl DBI + DBD, as I understand. There's also ODBC > > support in the Win32 extensions package for Python - IIRC, Google for > > 'win32all' to get it. Its also available as a link from the Python for > > Win32 MSI installer on python.org. > > I've used Python ODBC some, it works and is easy to use. > > See this for a simple example: > > >http://jugad.livejournal.com/2006/07/07/ > > > (See the second post at that page, titled "Publishing ODBC database > > content as PDF > > ". The code shown in the post is not indented as per proper the Python > > syntax (LiveJournal messed up the indentation), sorry about that, but > > its trivial to correct if you know Python indenting rules). Also read > > the Python ODBC docs and examples, of course. > > > >3. Binary - Are there any utilities for compiling Ruby into a binary > > > executable? The issue is twofold, speed, and not handing the > > customer > > the source :) > > > For Python, there is py2exe (for Windows only). I used py2exe recently > > and it works well enough for the simple cases that I tried. (I tried > > building EXEs for a simple Python hello-world program, and for a > > simple wxPython GUI app based on my xtopdf toolkit. Both worked ok.) > > For cross-platform (Windows and Linux, IIRC), there is PyInstaller > > (Google for it), haven't tried it out yet, just downloaded it > > recently. > > > I don't think you'll gain much speed by this compiling step, though > > (over and above what Python gives you itself, when it compiles > > your .py files to .pyc files). The purpose of py2exe is more to hide > > the source code than to speed it up, as I understand (could be wrong). > > > Note: py2exe only creates an EXE and DLLs needed, from your source and > > its required Python modules. To create an installer, try InnoSetup > > (for Windows only). I recently tried it out, version 5, again, it > > worked well. Could create Windows SETUP.EXE-type installers for the > > two EXEs described above. Worked ok. > > > I first learned Python, have been using it for some time for various > > projects, and then learned Ruby, and have done some projects with Ruby > > too. > > > I've been reading both the Ruby Cookbook and the Python Cookbook > > rather thoroughly in the last few weeks (and trying out and modifying > > many of the recipes), and what I've observed is that the two languages > > are roughly similar in features. For basic features common to most > > languages (constants, variables, arrays, hashes/dictionaries, file I/ > > O, classes, objects, modules/libraries, etc. - they work roughly in > > the same fashion - though syntax obviously differs, you can mostly do > > what you can in one of them, in the other as well. (Note that I'm not > > talking about libraries here - this will obviously differ as each > > language will have its own set of libraries for doing various tasks, > > like networking and other areas - though even here there is a good > > amount of overlap/similarity.) > > > For more advanced language features related to object-orientation, > > metaclasses / metaprogramming, both have some support, but you might > > or might not be able to do in one, what you can do in the other. > > > HTH > > Vasudev Ram > > Site:http://www.dancingbison.com > > PDF toolkit (in Python):http://sourceforge.net/projects/xtopdf > > Blog:http://jugad.livejournal.com > > P.S.: Some more thoughts: > > If you'd really prefer to work in Ruby, but find after investigation, > that the wxPython recommendation I've made is worth pursuing, you > could check out this other approach: > > - Write the GUI in Python + wxPython > - Write the rest of the app - the back end - in Ruby. > - Connect the two via any one of the following distributed computing > technology options: > > - sockets (lowest level, more coding needed, need to create your > own proprietary, application-specific (though not necessarily very > difficult) "protocol" on top of the sockets layer > > - XML-RPC (less coding than sockets, fairly easy to code with, > supports most/all basic scalar data types (string, int) of Python/ > Ruby, also supports 'structs' and arrays. XML-RPC structs are not > really structs in the C sense, they more or less map to hashes/ > dictionaries of Ruby/Python respectively. A Binary XML-RPC data type > is also available, it works by Base-64 encoding your binary data. Have > tried out this type as well as the simple scalar types, they work. > (E.g. I could generate a PDF file on the server in response to a > client method call, and send the PDF back to the client as the method > response, using the Binary data type.) In XML-RPC you can either use > the register_instance or register_function functions to register your > class's callable methods or your standalone callable functions so the > client can call them. > Each of these approaches (register_function vs. register_instance) has > its pros and cons - e.g. IIRC, you can register any number of > functions, but you can only register one instance of an object - so if > using this approach, you'd need to either a) have all your callable > code in one class, or make that one class a manager/controler class > that delegates to other classes to do the needed work. > > - SOAP. Ruby's stdlib has SOAP support. Python has SOAPpy and a > few others, not sure whether those projects are active and supported > currently. You will need to check this out. Comments similar to those > for XML-RPC above. > > - ICE from ZeroC -www.zeroc.com. This is like a lighter CORBA. > Some of the key developers are prior CORBA experts, like Michi Henning > who wrote a well-known C++/CORBA book. But check out the licenses for > ICE; IIRC, the open source version is under the GPL. You have to pay > for a commercial license. > > ICE supports Python for both client and server, has Ruby support > (need to check if both client and server, or client only). > > - HTTP calls. Use Webrick or Mongrel HTTP server libraries - you > can "mount" instances of classes into the HTTP servers that these > libraries allow you to create and run. (This is similar to Java > servlets running inside a Java servlet container.) "Call" the methods > of these instances from the Python + wxPython GUI front end via the > appropriate HTTP client library (urllib or urllib2 or httplib2) for > Python, open-uri for Ruby. I've checked this out (briefly), it works, > and is a neat and somewhat powerful technique, IMO. (What this implies > is that the client for your HTTP server, need not be a browser - it > can be a... > > read more ? wxPython uses the native widgets of the platform it is running on in most (if not all) cases, so if you want the "native look & feel", than that is the way I would go. They have the best user's group I've seen so far as well. Mike From nagle at animats.com Thu Jul 12 23:43:19 2007 From: nagle at animats.com (John Nagle) Date: Fri, 13 Jul 2007 03:43:19 GMT Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <5dveb4F360un0U1@mid.individual.net> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: Donn Cave wrote: > In its day, goto was of course very well loved. No, it wasn't. By 1966 or so, "GOTO" was starting to look like a bad idea. It was a huge hassle for debugging. It took another decade to get the iteration constructs approximately right (FORTRAN was too restrictive, ALGOL was too general), and to deal with problems like the "dangling ELSE", but it was clear quite early that GOTO was on the way out. There was a detour through BASIC and its obsession with line numbers ("GOSUB 14000" - bad subroutine call construct) that took a while to overcome. Much of that was from trying to cram interactive systems into computers with very modest capacity per user. John Nagle From hari.siri74 at gmail.com Wed Jul 11 20:32:42 2007 From: hari.siri74 at gmail.com (hari.siri74 at gmail.com) Date: Thu, 12 Jul 2007 00:32:42 -0000 Subject: socket programming related. Message-ID: <1184200362.261465.125810@w3g2000hsg.googlegroups.com> I have just started working in network programming using python. written code for socket connection between client and server. Client sent data to server for server processing (also server echoing back rcvd data to client). When there is ("if no data": break ) no data from client then the while loops break in server. The server program process recvd data and my requirement is to send back the *results* to client program for user sake. I did many trials but no use, as these socket calls are blocking, i could not make my req. From kyosohma at gmail.com Tue Jul 3 09:37:11 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 03 Jul 2007 06:37:11 -0700 Subject: what is wrong with that r"\" In-Reply-To: References: <1183468603.714314.241430@n60g2000hse.googlegroups.com> Message-ID: <1183469831.914087.66580@k29g2000hsd.googlegroups.com> On Jul 3, 8:25 am, Jean-Paul Calderone wrote: > On Tue, 03 Jul 2007 06:16:43 -0700, kyoso... at gmail.com wrote: > >On Jul 3, 7:15 am, alf wrote: > >> question without words: > > >> >>> r"\" > >> File "", line 1 > >> r"\" > >> ^ > >> SyntaxError: EOL while scanning single-quoted string > >> >>> r"\ " > >> '\\ ' > > >One slash escapes the following character, so the proper way of > >writing it is either > > >r"\\" or r"\"" > > >Seehttp://docs.python.org/ref/strings.htmlfor more information. > > I wonder if the OP was asking how to spell the one-length string \? > In that case, the answer is that it can't be done using raw strings, > but "\\" does it. Backslash escapes aren't interpreted in raw strings, > but you still can't end a raw string with a backslash. > > Jean-Paul Very true...sometimes I need to read these weird posts 2 or 3 times. Mike From brickenstein at googlemail.com Thu Jul 12 06:34:44 2007 From: brickenstein at googlemail.com (brickenstein at googlemail.com) Date: Thu, 12 Jul 2007 03:34:44 -0700 Subject: profiling a C++ python extension In-Reply-To: <1184113272.962640.41240@22g2000hsm.googlegroups.com> References: <1184113272.962640.41240@22g2000hsm.googlegroups.com> Message-ID: <1184236484.270723.27570@g4g2000hsf.googlegroups.com> Hi! It doesn't suffice to compile the python interpreter with -pg, as the module is loaded via dlopen. I solved the problem for my case compiling an executable with embedded python and the module itself. I would wish, that there would be an easier way. Best regards, Michael From martin at v.loewis.de Mon Jul 2 01:22:44 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 02 Jul 2007 07:22:44 +0200 Subject: unicode In-Reply-To: <1183348831.983714.292640@k29g2000hsd.googlegroups.com> References: <1183267580.178435.265640@o61g2000hsh.googlegroups.com> <1183318859.305908.218960@w5g2000hsg.googlegroups.com> <46880b1a$0$22417$9b622d9e@news.freenet.de> <1183348316.943369.230970@q75g2000hsh.googlegroups.com> <1183348831.983714.292640@k29g2000hsd.googlegroups.com> Message-ID: <46888BA4.1010205@v.loewis.de> > ooops. I mean is that the same as print calling > u_str.encode(sys.stdout.encoding)? Almost. It's rather u_str.encode(sys.stdout.encoding or sys.getdefaultencoding()) (in case sys.stdout.encoding isn't set) Regards, Martin From Arash at ece.ucsb.edu Fri Jul 13 00:33:11 2007 From: Arash at ece.ucsb.edu (Arash Arfaee) Date: Thu, 12 Jul 2007 21:33:11 -0700 Subject: Fast powerset function Message-ID: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> I need a powerset generator function. It's really slow with recursion. Does anybody have any idea or code(!!) to do it in an acceptable time? Thanks -Arash -------------- next part -------------- An HTML attachment was scrubbed... URL: From sander at steffann.nl Sun Jul 1 06:47:17 2007 From: sander at steffann.nl (Sander Steffann) Date: Sun, 1 Jul 2007 12:47:17 +0200 Subject: unicode References: <1183267580.178435.265640@o61g2000hsh.googlegroups.com> Message-ID: Hi, "Erik Max Francis" wrote in message news:Qp6dndf6_Mcn3BrbnZ2dnUVZ_hynnZ2d at speakeasy.net... > 7stud wrote: > >> Based on this example and the error: >> >> ----- >> u_str = u"abc\u9999" >> print u_str >> >> UnicodeEncodeError: 'ascii' codec can't encode character u'\u9999' in >> position 3: ordinal not in range(128) >> ------ >> >> it looks like when I try to display the string, the ascii decoder >> parses each character in the string and fails when it can't convert a >> numerical code that is higher than 127 to a character, i.e. the >> character \u9999. > > If you try to print a Unicode string, then Python will attempt to first > encode it using the default encoding for that file. Here, it's apparent > the default encoding is 'ascii', so it attempts to encode it into ASCII, > which it can't do, hence the exception. If you want to change the default encoding of your stdout and stderr, you can do something like this: import codecs, sys sys.stdout = codecs.getwriter('utf-8')(sys.stdout) sys.stderr = codecs.getwriter('utf-8')(sys.stderr) After doing this, print u_str will work as expected (when using an utf-8 terminal) - Sander From aahz at pythoncraft.com Sun Jul 15 19:00:58 2007 From: aahz at pythoncraft.com (Aahz) Date: 15 Jul 2007 16:00:58 -0700 Subject: Can a low-level programmer learn OOP? References: Message-ID: In article , James Stroud wrote: > >If you just want to enter some values and set some flags and then hit >"go", you could always program the GUI in HTML and have a cgi script >process the result. This has a lot of benefits that are frequently >overlooked but tend to be less fun than using a bona-fide toolkit like >WX or QT. This is excellent advice worth emphasizing -- but then, I make my living working on a web app. ;-) -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I support the RKAB From claird at lairds.us Fri Jul 6 13:10:41 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 6 Jul 2007 17:10:41 +0000 Subject: connecting to serial port + python References: <1183467711.963266.137590@m37g2000prh.googlegroups.com> Message-ID: In article <1183467711.963266.137590 at m37g2000prh.googlegroups.com>, Japan Shah wrote: >Hello, > >I am trying to connect my Nokia 6610 using usb cable, >I have installed usb-serial driver of it. > > >I hv tested it with Hyperterminal and it works fine. > >but when I wrote a python script I am not able to receive the responce >from the device. . . . It's quite likely that you do NOT want to regard this as a "serial port" device as commonly understood. It's even more likely that you're going to be very happy once you start reading about gammu , an open-source project (or collection of open-source pro- jects) focussed on mobile telephony handset devices, especially those from Nokia. Gammu works particularly well with the 6610 and closely- related handsets, in my experience; I've been using it so for a couple of years. What's your preferred (desktop) operating system? Which cable did you buy? Is it compatible with one made at the Nokia factories? Not all USB cables are alike ... From gabe at dragffy.com Thu Jul 26 05:50:45 2007 From: gabe at dragffy.com (Gabriel Dragffy) Date: Thu, 26 Jul 2007 10:50:45 +0100 Subject: Reading data from an ISA port In-Reply-To: <5gkn9lF3g5b6vU1@mid.uni-berlin.de> References: <5gkn9lF3g5b6vU1@mid.uni-berlin.de> Message-ID: On 23 Jul 2007, at 23:09, Diez B. Roggisch wrote: > Gabriel Dragffy schrieb: >> Dear list members >> >> I must admit I am a new user of Python, but it is a language that I >> enjoy using. >> >> For one of my university projects I need to write a program that can >> read several bytes from an ISA port. It has been suggested to me >> that I >> look at using C or Pyinline. If I can I would prefer to continue >> to use >> Python, and Pyinline won't play ball. >> >> I am sure Python can do this for me, but the question is how? What >> modules and code do I need to look? I'd be very grateful for any >> suggestions and advice. > > Python as-is won't help. It has no concept of memory addresses and > direct access to them. However, a trivial C-extension together with > the > struct and/or ctypes module will help. > > What you essentially need to code is a C-extension that will allow you > to directly access memory. Wrap that either in an extension or > using ctypes. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list Thanks for your information. Are you able to tell me where or how to get or make this trivial C extension, please? Regards Gabriel From pict100 at gmail.com Fri Jul 20 11:31:19 2007 From: pict100 at gmail.com (DarkBlue) Date: Fri, 20 Jul 2007 08:31:19 -0700 Subject: Document creation with odfpy Message-ID: <1184945479.800061.108100@e16g2000pri.googlegroups.com> Hello I hope here is the right place to ask this: I use the python odfpy library to create and load an odt file , however, spaces in the passed in text are removed. http://opendocumentfellowship.org/development/projects/odfpy python2.4 from odf.opendocument import OpenDocumentText from odf.style import Style, TextProperties from odf.text import H, P, Span def SaveIt(MYTEXT) : doc = OpenDocumentText() for line in MYTEXT: p = P(text=line) doc.text.addElement(p) doc.save('mynewfile.odt') MYTEXT is a list containing lines from a wx.TextCtrl if a line is: abcabc abcabc abcabc the result in the odt file looks like: abcabc abcabc abcabc Is there anything I am doing wrong ? Thanks Db From jitudon at hotmail.com Fri Jul 6 01:14:45 2007 From: jitudon at hotmail.com (jitudon at hotmail.com) Date: Thu, 05 Jul 2007 22:14:45 -0700 Subject: How to close a program I execute with subprocess.Popen? In-Reply-To: <1183124181.318726.200620@m36g2000hse.googlegroups.com> References: <1183124181.318726.200620@m36g2000hse.googlegroups.com> Message-ID: <1183698885.626159.276070@e9g2000prf.googlegroups.com> On Jun 29, 6:36 pm, revenan... at hotmail.com wrote: > I'm writing a program which has to execute a command, get its output > and show it on a treeview. > This command runs for a very long time. > I want to end the execution of the command when the user closes my > application. > > Right now I'm using an object my_child of type subprocess.Popen to > execute the command, inside a thread with an infinite loop where we > constantly ask for its output. > > To end the program when the user closes the application, I send a > SIGTERM to the process with pid my_child.pid using os.kill. But I also > have to send a SIGTERM to my_child.pid + 1 because my_child.pid is the > pid of /bin/sh -c which is the one which calls the command, because > when I try to run Popen with shell=False, it sends an exception and > says the file or directory doesn't exist. > > Anyone knows of a better way to close the command than using a > SIGTERM? I just can't help myself thinking this is an ugly dirty hack. As nick pointed out use process group's . I use the "preexec_fn" keyword argument to Popen and "os.setsid()" call's side effect to make process groups and then os.killpg() to send the signal to process groups. child = Popen( cmd , preexec_fn = os.setsid ) os.killpg( child.pid,signal.SIGINT) Regards jitu From stefan.behnel-n05pAM at web.de Thu Jul 12 14:19:55 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 12 Jul 2007 20:19:55 +0200 Subject: web page text extractor In-Reply-To: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> References: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> Message-ID: <469670CB.4020603@web.de> kublai wrote: > For a project, I need to develop a corpus of online news stories. I'm > looking for an application that, given the url of a web page, "copies" > the rendered text of the web page (not the source HTNL text), opens a > text editor (Notepad), and displays the copied text for the user to > examine and save into a text file. Graphics and sidebars to be > ignored. The examples I have come across are much too complex for me > to customize for this simple job. Can anyone lead me to the right > direction? Super-simplistic: >>> import lxml.etree as et >>> parser = et.HTMLParser() >>> tree = et.parse("http://the/page.html", parser) >>> print tree.xpath("string(/html/body)") http://codespeak.net/lxml/ You may want to use the incredibly versatile "lxml.html.clean" module first to remove any annoying content. It's not released yet but available in a branch: http://codespeak.net/svn/lxml/branch/html/ Stefan From siona at chiark.greenend.org.uk Sat Jul 21 14:32:38 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 21 Jul 2007 19:32:38 +0100 (BST) Subject: Interpreting os.lstat() References: <1184806559.224636.266500@e9g2000prf.googlegroups.com> <46a057e8$0$19051$9b622d9e@news.freenet.de> <46A12C88.7070403@v.loewis.de> Message-ID: <+FB*rrjQr@news.chiark.greenend.org.uk> =?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?= wrote: >> But it obviously does a lot of other stuff, including formatting >> the results of the system call for display. >It most decisively does *not* format the results of the system call >"for display". "It" here refers to the program stat, which on most systems I use is in /usr/bin/stat and most assuredly *does* format the results of the system call for display. > I think it is important >to understand that Python does *not* do any significant code >to os.stat and os.lstat; Absolutely, which is why I consider it foolish for the OP to be trying to deduce the meaning of os.stat by looking at the output of the stat program, rather than studying the man page for the stat system call. -- \S -- siona at chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/ "Frankly I have no feelings towards penguins one way or the other" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From dtbrown at ag.com Tue Jul 24 09:07:49 2007 From: dtbrown at ag.com (DB Daniel Brown) Date: Tue, 24 Jul 2007 09:07:49 -0400 Subject: How do I 'stat' online files? Message-ID: I am working on a program that needs to stat files (gif, swf, xml, dirs, etc) from the web. I know how to stat a local file... import os tplStat = os.stat(path) but I can't figure out how to stat a file that resides on a web server. I am not sure if it makes a difference, but most (maybe all) of the files that I need to stat reside within the same domain that will generate the request. I am able to open the file by using import urllib f = urllib.urlopen(url) but for some reason I cannot stat the files. Any help will greatly be appreciated. Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From nicola.musatti at gmail.com Thu Jul 5 11:27:53 2007 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Thu, 05 Jul 2007 15:27:53 -0000 Subject: The best platform and editor for Python In-Reply-To: References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183644537.859604.27790@w5g2000hsg.googlegroups.com> Message-ID: <1183649273.284539.197860@n2g2000hse.googlegroups.com> On Jul 5, 4:21 pm, Roy Smith wrote: > In article <1183644537.859604.27... at w5g2000hsg.googlegroups.com>, > Nicola Musatti wrote: > > > On Jul 5, 1:23 pm, Gregor Horvath wrote: > > [...] > > > That's a property of open source projects. > > > Features nobody really needs are not implemented. > > > No, no, you got it all wrong. It's in *commercial* projects that > > features nobody really needs are not implemented. > > No, no, squared. In a commercial project, the only features that get > implemented are the ones somebody is willing to pay for. Whether there is > any correlation between need and willingness to pay is an open question. Ah, but you snipped the most important part of my post: > Profit is fundamental in convincing you that you really > need the features. I mean, marketing is all about creating the willingness by stimulating the perception of the need. Cheers, Nicola Musatti From george.sakkis at gmail.com Wed Jul 18 20:35:46 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 19 Jul 2007 00:35:46 -0000 Subject: Break up list into groups In-Reply-To: <1184694533.380918.169640@m37g2000prh.googlegroups.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> <1184694533.380918.169640@m37g2000prh.googlegroups.com> Message-ID: <1184805346.034493.217840@g12g2000prg.googlegroups.com> On Jul 17, 1:48 pm, Matimus wrote: > I did some more experimenting and came up with the code below. It > shows several methods. When run, the script tests the robustness of > each method (roughly), and profiles it using timeit. The results from > running on my laptop are shown below the code. > > > seqs = [# Original: > [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, > 12, 13, > 0xF0, 14, 0xF1, 15], > # Single entry: > [0xF0, 1, 2, 3], > # empty > [], > # No values with 0x80 set > [1, 2, 3, 14, 15], > # Does not start with a value that has 0x80 set > [1, 2, 3, 14, 15, 0xF0, 1, 2, 3]] > > expected = [# Original: > [[0xF0, 1, 2, 3], [0xF0, 4, 5, 6], [0xF1, 7, 8], [0xF2, 9, > 10, 11, 12, 13], > [0xF0, 14], [0xF1, 15]], > # Single entry: > [[0xF0, 1, 2, 3]], > # empty > [], > # No values with 0x80 set > [], > # Does not start with a value that has 0x80 set > [[0xF0, 1, 2, 3]]] > > def gengroups0(seq): > group = None > for val in seq: > if val & 0x80: > if group: yield group > group = [] > try: > group.append(val) > except AttributeError: > pass > if group: yield group > > def getgroups0(seq): > groups = [] > group = None > for val in seq: > if val & 0x80: > if group: > groups.append(group) > group = [] > try: > group.append(val) > except AttributeError: > pass > if group: > groups.append(group) > return groups > > def gengroups1(seq): > idxs = [i for i,v in enumerate(seq) if v&0x80] > for i,j in zip(idxs,idxs[1:]+[None]): > yield seq[i:j] > > def getgroups1(seq): > idxs = [i for i,v in enumerate(seq) if v&0x80] > return [seq[i:j] for i,j in zip(idxs,idxs[1:]+[None])] > > # Similar to the partition method on strings > def partition(seq,f=None): > if f is None: > f = lambda x:x > for i,v in enumerate(seq): > if f(v): > return seq[:i],[seq[i]],seq[i+1:] > return seq,[],[] > > def rpartition(seq, f=None): > if f is None: > f = lambda x:x > for i,v in zip(range(len(seq)-1,-1,-1),seq[::-1]): > if f(v): > return seq[:i],[seq[i]],seq[i+1:] > return ([],[],seq) > > def gengroups2(seq): > while seq: > seq, key, val = rpartition(seq, lambda x: x&0x80) > if key and val: yield key+val > > def getgroups2(seq): > groups = [] > while seq: > seq, key, val = rpartition(seq, lambda x: x&0x80) > if key and val: > groups.append(key+val) > return groups > > def getgroups3(seq): > groups = [] > for i in seq: > if 0x80 & i: > groups.append([i]) > else: > groups[-1].append(i) > return [x for x in groups if x] > > seq = seqs[0] > if __name__ == "__main__": > from timeit import Timer > import __main__ > for i in range(4): > fname = "getgroups"+str(i) > f = getattr(__main__,fname) > print fname > for i,(s,e) in enumerate(zip(seqs,expected)): > print "test %d:"%i, > try: > if f(s) == e: > print "pass" > else: > print "fail" > except: > print "error" > > t = Timer(fname+'(seq)', > 'from __main__ import seq,'+fname) > print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/ > 100000) > print > > > Output from running the above: > getgroups0 > test 0: pass > test 1: pass > test 2: pass > test 3: pass > test 4: pass > 14.85 usec/pass > > getgroups1 > test 0: pass > test 1: pass > test 2: pass > test 3: pass > test 4: pass > 13.81 usec/pass > > getgroups2 > test 0: fail > test 1: pass > test 2: pass > test 3: pass > test 4: pass > 56.38 usec/pass > > getgroups3 > test 0: pass > test 1: pass > test 2: pass > test 3: error > test 4: error > 16.23 usec/pass > > `getgropus2' fails test 0 because it produces a reversed list. That > can easily be fixed by re-reversing the output before returning. But, > since it is by far the slowest method, I didn't bother. > > `getgroups3' is a method I got from another post in this thread, just > for comparison. > > >From my benchmarks it looks like getgroups1 is the winner. I didn't > > scour the thread to test all the methods however. Here's a small improvement of getgroups1, both in time and memory: from itertools import islice def getgroups4(seq): idxs = [i for i,v in enumerate(seq) if v&0x80] idxs.append(None) return [seq[i:j] for i,j in izip(idxs, islice(idxs,1,None))] George From robert.rawlins at thinkbluemedia.co.uk Tue Jul 3 10:49:39 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Tue, 3 Jul 2007 15:49:39 +0100 Subject: POpen - Wait For Process To Complete Message-ID: <001801c7bd81$6272ccb0$27586610$@rawlins@thinkbluemedia.co.uk> Hello guys, Quite a simple one I'm hoping. I've got a process that I run using popen which writes to a file, I'm then going to read the file and parse its contents. However, getting the application to wait until the process is complete and finished writing before it reads and parses the file is becoming complicated. Popen is meant to have a wait() function along with a poll() function (according to the docs), both of which can be used to make the app wait for the process to finished, but for some reason I can't get them working, when I try this: Import popen2 Process = popen2.popen4('This is my command to run from cmd') Process.wait() f = open('path/to/output/file.txt') new = f.read() f.close() It throws back the following error to me: push.wait() AttributeError: 'tuple' object has no attribute 'wait' Which is fair enough as popen4 returns a tuple containing the output streams from the cmd command, but how the hell can I have it wait so I can read the physical files? I'll be interested to hear your thoughts guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Fri Jul 20 15:28:21 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 20 Jul 2007 12:28:21 -0700 Subject: Python MAPI In-Reply-To: <1184957337.367674.104760@i13g2000prf.googlegroups.com> References: <1184954229.222401.213380@k79g2000hse.googlegroups.com> <1184957337.367674.104760@i13g2000prf.googlegroups.com> Message-ID: <1184959701.447824.70890@q75g2000hsh.googlegroups.com> On Jul 20, 1:48 pm, vasudevram wrote: > On Jul 20, 10:57 pm, kyoso... at gmail.com wrote: > > > > > Hi, > > > I've been googling all over and can't find any good answers about this > > problem. I would like to create some kind of MAPI interface with > > Python such that when I open Microsoft Word (or another Office > > program) and click File, Send To, Mail Recipient it opens a program I > > wrote in Python and uses it to send the email rather than Outlook. > > > The closest I've come is finding the registry key HKLM\Software\Clients > > \Mail which seems to control the default email client. I did figure > > out how to redirect mailto directives on websites to my program > > successfully, but this is a whole 'nother ballgame. > > > Any suggestions are welcome. I am considering writing some VBA hooks > > in Office Apps in question, but would prefer to avoid that. > > > Thanks! > > > Mike > > > P.S. Currently using Python 2.4, wxPython 2.8.3 (for GUI) on Windows > > XP Pro. > > Hi, > > 1: I don't know much about Windows APIs, but am currently reading the > "Windows Internals" book. Got this idea from it: > > Go tohttp://www.microsoft.com/technet/sysinternals/default.mspx > and check out the SysInternals utilities there. The book says that you > can use some of them to "spy" on what an app is doing - what registry > keys it is reading/writing, lots of other OS-level calls it makes as > it runs. Digging around and using some of these utilities to check out > what an Office app does when you use it to send mail, might help you > figure out a way to do what you want. > > 2. Try looking for registry entries specific to Office Apps, and look > under those subtrees for likely email-related entries to modify (if > you haven't tried that already). I guess you already know that > fiddling with the registry can be risky and can crash your system, so > take backups, etc. > > Using COM via Python may also help - again, some digging required. You > probably already have the PyWin32 Python extensions for Windows COM > (earlier called win32all - seehttp://wiki.python.org/moin/Win32All) - > if not, its available here: > > http://www.python.org/download/releases/2.4.4/ > (scroll down the page for the link) > > Vasudev Ramwww.dancingbison.com > jugad.livejournal.com > sourceforge.net/projects/xtopdf Thanks for the ideas...I am already monitoring the registry to see what happens when I switch between two email clients. In this case, I am switching between Outlook 2003 and Thunderbird 2. The pertinent registry files are as follows: # changes which email client to use [HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail] # obviously changes the .eml file association [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.eml] # haven't the fogiest idea what this does, if anything [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{29F458BE-8866-11D5- A3DD-00B0D0F3BAA7}] # change mailto functionality [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\mailto\DefaultIcon] @="C:\\Program Files\\Mozilla Thunderbird\\thunderbird.exe,0" [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\mailto\shell\open\command] @="\"C:\\Program Files\\Mozilla Thunderbird\\thunderbird.exe\" -osint - compose \"%1\"" I assume you're referring to "Process Monitor", which is a really cool tool. Maybe it'll help, but I usually can't get it to filter out enough of the noise to make the output useful. I'll give it a go nonethless. I am running all my tests in a VM, so I really don't care if the registry gets hosed at this point. Thanks again, Mike From http Sun Jul 8 18:52:29 2007 From: http (Paul Rubin) Date: 08 Jul 2007 15:52:29 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <46824d8d$0$2324$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> Message-ID: <7xvecumrte.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > As far as I can see, the only difference is that the list comp variable > isn't explicitly created with a statement of the form "name = value". Why > is that a problem? I don't know that listcomp vars are worse problem than other vars; however there is an easy workaround for the listcomp vars so I use it. If there was a way to restrict the scope of other local vars (I gave examples from other languages of how this can be done), I'd use that too. From grante at visi.com Mon Jul 16 14:05:26 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 16 Jul 2007 18:05:26 -0000 Subject: Best method for inter process communications References: <1184606522.541918.18870@22g2000hsm.googlegroups.com> Message-ID: <139ncr6nr6b6j06@corp.supernews.com> On 2007-07-16, JamesHoward wrote: > I am looking for a way of performing inter process communication over > XML between a python program and something else creating XML data. > > What is the best way of performing this communication? I could bind a > socket to localhost and perform the data transfer that way, but that > seems inefficient due to the addition of TCP/IP or UDP/IP overhead. > Is there a way to stream data via a custom datastream (I.E. not STDIO, > STDERR, etc)? You could use a named pipe or a Unix domain socket. The nice thing about an IP socket is that you get network transparancy: the two programs can be moved to two different machines. -- Grant Edwards grante Yow! It's the RINSE CYCLE!! at They've ALL IGNORED the visi.com RINSE CYCLE!! From gagsl-py2 at yahoo.com.ar Thu Jul 5 04:33:07 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Jul 2007 05:33:07 -0300 Subject: Problem with building extension in Python References: <1183622938.086813.18950@k79g2000hse.googlegroups.com> Message-ID: En Thu, 05 Jul 2007 05:08:58 -0300, escribi?: > I have already install Microsoft visual studio .NET 2003 and MinGw, > when I try to build a extension: Is this for Python 2.4? I think you can't compile Python 2.5 with VS2003. > python my_extension_setup.py build ( or install ) , I get an error: > > LINK : fatal error LNK1141: failure during build of exports file > error: command '"C:\Program Files\Microsoft Visual Studio .NET > 2003\Vc7\bin\link.exe"' failed with exit status 1141.What shoud I > do??? Almost surely you got a previous error, making link to fail. Try to correct *that* error. -- Gabriel Genellina From wojciech_mula at poczta.null.onet.pl.invalid Tue Jul 31 16:57:46 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?iso-8859-2?Q?Mu=B3a?=) Date: Tue, 31 Jul 2007 20:57:46 +0000 (UTC) Subject: split a string of space separated substrings - elegant solution? References: <46af9beb$0$14242$ba620e4c@news.skynet.be> Message-ID: Helmut Jarausch wrote: > Hi, > > 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') import csv s = 'abc "xy z" "1 2 3" "a \\" x"' r = iter(csv.reader([s], delimiter=" ", escapechar="\\")) print r.next() w. From robert.rawlins at thinkbluemedia.co.uk Mon Jul 16 05:04:07 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 16 Jul 2007 10:04:07 +0100 Subject: Access Object From 2 Applications or Fix Scheduler In-Reply-To: <00a501c7c776$900ba8a0$03000080@hendrik> References: <015201c7c71a$2be05df0$83a119d0$@rawlins@thinkbluemedia.co.uk> <00a501c7c776$900ba8a0$03000080@hendrik> Message-ID: <018b01c7c788$47ea3700$d7bea500$@rawlins@thinkbluemedia.co.uk> Also Hendrik, I should probably mention that the second application is a constant running application, it's nothing something that can just be 'started' by the first one, its running non-stop and just needs data passed into it regularly when the first application finds it. Application 1 Application 2 Work with dict Work with dict Work with dict Work with dict New XML Found, Parse Into Dict --------------> Work with new dict Work with new dict Work with new dict Work with new dict You see how that works? Application 1 has a function that runs every minute and _may_ find a new xml file, if it does then I need it to parse that file into a list of dictionary and then pass that into application 2, which then starts using it :-) Now we may be able to avoid this if there is some type of file watcher function available in python, my second application could then just watch the XML file and as soon as a new one is available parse it itself. Is that something you've heard of? Thanks, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Hendrik van Rooyen Sent: 16 July 2007 07:29 To: python-list at python.org Subject: Re: Access Object From 2 Applications or Fix Scheduler Robert Rawlins - Think Blue wrote: >Hello Guys, > >I have two applications which I need to get talking and sharing an >object, what s the best way to do this? Basically my >first application parses an XML document into a bunch of lists and tuples etc, and I need to access the data in these lists >and tuples from my second application. Is this possible? And whats the simplest method? > >This problem all evolves from a hack/work around Ive had to place >together as I have been having problems with >sched, these two applications used to be a single one to start with but for some reason when scheduling tasks using the >sched module they wouldnt ever run when supposed too, so Id schedule >it to run every 2 minutes and it would run >between 3 and 15 minutes :-s so I ripped it out into its own application and it now runs every 2 minutes exactly. > >I either need to fix my sched issues or the memory share, either way >Im quite happy, just need to get it working >smoothly. > >Any ideas? > You have already split the thing, so I would: schedule the XML parser and make it do its stuff. then pickle the results using cPickle then from this first thing, either: write the pickles to temp files and start the second thing using eg os.system() or start the second thing and use a named pipe to pass the pickles over for unpickling and processing, or use one of the popens, or have a look at Pyro, or start the second thing as a thread and use a Queue.. of course this whole scheme will fall apart if the combined processing takes longer than the scheduling interval. HTH - Hendrik From alanwilter at gmail.com Tue Jul 17 12:50:24 2007 From: alanwilter at gmail.com (Alan) Date: Tue, 17 Jul 2007 17:50:24 +0100 Subject: building static python with Numeric In-Reply-To: References: Message-ID: Dears, It's about Pyhton for Linux X86. First, I would like to know if it's possible to build a fully static python binary, something that does not depends on others libraries when using 'ldd python', e.g. If so, how? Second, I would like to build a python for distribution that would include (statically if possible) the package Numeric-24.2. Is it possible? How? Summarising, I would like to build a python binary independent of others libraries where I could 'import Numeric'. I would appreciate very much any help here. Many thanks in advance. Cheers, Alan From stargaming at gmail.com Wed Jul 11 10:05:00 2007 From: stargaming at gmail.com (Stargaming) Date: Wed, 11 Jul 2007 16:05:00 +0200 Subject: bool behavior in Python 3000? In-Reply-To: <9v4li.8359$MV6.308@trnddc01> References: <5ficp9F3cram2U2@mid.individual.net> <469472f4$0$1293$9b622d9e@news.freenet.de> <1184140795.974059.302830@22g2000hsm.googlegroups.com> <9v4li.8359$MV6.308@trnddc01> Message-ID: <4694e38f$0$11913$9b622d9e@news.freenet.de> Alan Isaac schrieb: > Miles wrote: > >> What boolean operation does '-' represent? > > > Complementation. > And as usual, a-b is to be interpreted as a+(-b). > In which case the desired behavior is > False-True = False+(-True)=False+False = False I always thought, at least in a Python context, A-B would trigger A.__sub__(B), while A+(-B) triggers A.__add__(B.__neg__()). A better choice could be A+~B (A.__add__(B.__invert__())) because it's always unary (and IMO slightly more visible). > In response to Stargaming, Steve is making > a point about the incoherence of certain arguments, > not proposing an implementation. Why should it be incoherent? Bjoern is pointing out an important aspect of how Python handles binary algebra (correctly). In contrast, Steven tries to invert his argument. Following, I showed why Steven's proof is wrong because his implementation fails at some aspects where the current one works. So I cannot see how Bjoern's argument is either wrong or not relevant. From python at jayloden.com Wed Jul 11 17:12:51 2007 From: python at jayloden.com (Jay Loden) Date: Wed, 11 Jul 2007 17:12:51 -0400 Subject: pattern match ! In-Reply-To: <4694BF24.1050706@igpm.rwth-aachen.de> References: <1184125206.034047.175340@n60g2000hse.googlegroups.com> <4694BF24.1050706@igpm.rwth-aachen.de> Message-ID: <469547D3.6010209@jayloden.com> Helmut Jarausch wrote: > hari.siri74 at gmail.com wrote: >> Extract the application name with version from an RPM string like >> hpsmh-1.1.1.2-0-RHEL3-Linux.RPM, i require to extract hpsmh-1.1.1.2-0 >> from above string. Sometimes the RPM string may be hpsmh-1.1.1.2-RHEL3- >> Linux.RPM. >> > > Have a try with > > import re > P=re.compile(r'(\w+(?:[-.]\d+)+)-RHEL3-Linux\.RPM') > S="hpsmh-1.1.1.2-0-RHEL3-Linux.RPM" > PO= P.match(S) > if PO : > print PO.group(1) A slightly more generic match in case your package names turn out to be less consistent than given in the test cases: #!/usr/bin/python import re pattern = re.compile(r'(\w+?-(\d+[\.-])+\d+?)-\D+.*RPM') pkgnames = ["hpsmh-1.1.1.2-0-RHEL3-Linux.RPM", "hpsmh-1.1.1.2-RHEL3-Linux.RPM"] for pkg in pkgnames: matchObj = pattern.search(pkg) if matchObj: print matchObj.group(1) Still assumes it will end in RPM (all caps), but if you add the flag "re.I" to the re.compile() call, it will match case-insensitive. Hope that helps, -Jay From ptmcg at austin.rr.com Sat Jul 7 14:59:43 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 07 Jul 2007 11:59:43 -0700 Subject: Creating logged functions using decorators In-Reply-To: References: Message-ID: <1183834783.235867.146840@n2g2000hse.googlegroups.com> On Jul 7, 1:47 pm, "Nathan Harmston" wrote: > Hi, > > I m thinking about writing some code which logs the input and output > of a function/script and stores it in a database using sqlalchemy > (although I havent started on this yet). I want to do this via a > decorator ( I think this is the best way ). > > def log(fn): > def newfn(*args): > print datetime.date.today() > print __file__ > print fn.__name__ > print args > return fn(*args) > return newfn > > @log > def doAnalysis(a, b): > print a, b > return a + b > > doAnalysis(3, 7) > > I can access the arguments passed to the "logged" function, but is > there anyway I can capture the output of the function i.e. 10. > > Many Thanks in advance, > > Nathan Yes. Capture the output of the function to a variable and log it before you return it. def log(fn): def newfn(*args): print datetime.date.today() print __file__ print fn.__name__ print args returnValue = fn(*args) print returnValue return return newfn Here's another idea: wrap the call to fn inside a try/except block, so that if the function raises an exception, you can log it and then reraise it. -- Paul From pruebauno at latinmail.com Tue Jul 17 13:56:23 2007 From: pruebauno at latinmail.com (pruebauno at latinmail.com) Date: Tue, 17 Jul 2007 10:56:23 -0700 Subject: Compiling python2.5 on IBM AIX In-Reply-To: <1184659090.881833.124240@x35g2000prf.googlegroups.com> References: <1184581796.377610.98230@o61g2000hsh.googlegroups.com> <1184600488.343686.263220@d55g2000hsg.googlegroups.com> <1184659090.881833.124240@x35g2000prf.googlegroups.com> Message-ID: <1184694983.780777.304030@g12g2000prg.googlegroups.com> On Jul 17, 3:58 am, bravo.l... at gmail.com wrote: > > I haven't compiled it myself, but I'm told that the installation I > > work with was compiled with: > > > export PATH=$PATH:/usr/vacpp/bin:/usr/vacpp/lib > > ./configure --with-gcc="xlc_r -q64" --with-cxx="xlC_r -q64" --disable- > > ipv6 AR="ar -X64" > > make > > make install > > I've tried with the followong configuration : > ---------- > export PATH=$PATH:/usr/vacpp/bin:/usr/vacpp/lib > ./configure --prefix=${BASE} --with-gcc="xlc_r -q64" --with-cxx="xlC_r > -q64" --disable-ipv6 AR="ar -X64" LDFLAGS="-L\${BASE}/lib/" PPFLAGS="-I > \${BASE}/include/" > > make > --------- > > but it doesn't compile either : > > make > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Modules/python.o ./Modules/python.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Modules/_typesmodule.o Modules/_typesmodule.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/acceler.o Parser/acceler.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/grammar1.o Parser/grammar1.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/listnode.o Parser/listnode.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/node.o Parser/node.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/parser.o Parser/parser.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/parsetok.o Parser/parsetok.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/bitset.o Parser/bitset.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/metagrammar.o Parser/metagrammar.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/firstsets.o Parser/firstsets.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/grammar.o Parser/grammar.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/pgen.o Parser/pgen.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/myreadline.o Parser/myreadline.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/tokenizer.o Parser/tokenizer.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Objects/abstract.o Objects/abstract.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Objects/boolobject.o Objects/boolobject.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Objects/bufferobject.o Objects/bufferobject.c > "Objects/bufferobject.c", line 22.15: 1506-275 (S) Unexpected text ',' > encountered. > make: 1254-004 The error code from the last command is 1. > > any idea ? > > thanks > > -- > BL Remove the extra comma at the end of line 22 of bufferobject.c That should help you fix it. I sent a bug report for that: http://sourceforge.net/tracker/index.php?func=detail&aid=1557983&group_id=5470&atid=105470 From steve at holdenweb.com Mon Jul 16 13:55:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 16 Jul 2007 13:55:26 -0400 Subject: Pass by reference or by value? In-Reply-To: <1184607606.805940.56980@22g2000hsm.googlegroups.com> References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> <1184385535.558451.306630@22g2000hsm.googlegroups.com> <1184607606.805940.56980@22g2000hsm.googlegroups.com> Message-ID: Beliavsky wrote: > On Jul 13, 11:58 pm, sturlamolden wrote: > > > >> In Fortran you can only pass references. >> >> integer(4) :: a >> a = 1 >> call bar(a) >> >> subroutine bar(a) >> integer(4) :: a >> a = 0 ! side-effect >> end subroutine >> >> That means, when a variable is used to call a function, the function >> receives a pointer to the actual argument, not a local copy. That is >> very different from C's copy-passing behaviour. > > In Fortran, if a procedure argument is modified within the procedure, > that change is propagated to the value of the argument in the caller. > The standard does NOT mandate how this is accomplished, and one could > in theory write a compiler that makes a local copy of all procedure > arguments, as long as the variables passed as arguments were updated > in the caller. Early implementations of Fortran 90 often made copies > of array arguments, hurting performance. Current compilers do this > less often. > > It is common to pass constants and expressions to Fortran procedures, > which does not fit the pass-by-reference paradigm. > You can pass a reference to a constant just as easily as you can pass a reference to a variable. The only think you have to ensure is that when you pass a reference to a constant something stops the procedure from changing it. Some early Fortran compilers omitted this small but important detail, leading to programs with incomprehensible semantics, as the values of numeric literals could no longer be relied upon. > Fortran 2003 has the VALUE attribute to give the C pass-by-value > behavior when desired. > 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 walthervondervogelweide at gmx.de Wed Jul 18 10:43:27 2007 From: walthervondervogelweide at gmx.de (Wolfgang Mederle) Date: Wed, 18 Jul 2007 16:43:27 +0200 Subject: The Modernization of Emacs: exists already References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272678.877166.209640@j4g2000prf.googlegroups.com> <1184764620.778937.264760@m37g2000prh.googlegroups.com> Message-ID: Xah Lee wrote: > In Emacs's documentation, the term Meta key should be replaced with > the Alt key, to reflect current usage, since that is the keyboard 99% > of personal computer users know. The "Meta key" name is a major point > of confusion for getting people to learn Emacs. This is utter bullshit. On my Mac, the Meta key is mapped to the Command key, while the Alt (Option) key is used by the system. Follow-up to comp.emacs. From no at no.no Fri Jul 13 02:43:58 2007 From: no at no.no (Daniel) Date: Fri, 13 Jul 2007 09:43:58 +0300 Subject: Getting values out of a CSV References: <1184295593.638409.22910@22g2000hsm.googlegroups.com> Message-ID: On Fri, 13 Jul 2007 08:51:25 +0300, Gabriel Genellina wrote: >> data = [row for row in csv.reader(open('some.csv', 'rb')) > > Note that every time you see [x for x in ...] with no condition, you can > write list(...) instead - more clear, and faster. > > data = list(csv.reader(open('some.csv', 'rb'))) Clearer? Maybe, but list comprehensions are clearer (at least for me) Faster? No. List Comprehensions are faster. From cai.haibin at gmail.com Tue Jul 24 06:44:50 2007 From: cai.haibin at gmail.com (james_027) Date: Tue, 24 Jul 2007 10:44:50 -0000 Subject: classmethod & staticmethod In-Reply-To: <46a5b2ad$0$18903$426a74cc@news.free.fr> References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> <46a5b2ad$0$18903$426a74cc@news.free.fr> Message-ID: <1185273890.838047.125800@e16g2000pri.googlegroups.com> hi, > The 'real' use is (are) the one(s) you'll find. FWIW, I use > staticmethods for helper functions that don't need access to the class > or instance but are too specific to a class to be of any use as plain > functions. Which is not a very frequent case. Classmethods are more > usefull - mostly as alternate constructors or utility methods for an > alternate constructor, but there are other possible uses (sorry, I have > no concrete example at hand). You mean like the example from Marc Thanks james From arkanes at gmail.com Tue Jul 24 14:52:29 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 24 Jul 2007 13:52:29 -0500 Subject: Technology solutions for Ruby? In-Reply-To: <1184606739.054580.197740@g37g2000prf.googlegroups.com> References: <469B059C.2050802@cesmail.net> <1184606739.054580.197740@g37g2000prf.googlegroups.com> Message-ID: <4866bea60707241152x5c20cd4fw863f37bb96b037e8@mail.gmail.com> On 7/16/07, vasudevram wrote: > > [ Though the OP posted his message to comp.lang.ruby, I'm cross- > posting it to comp.lang.python, since he mentions Python as a possible > alternative he's looking at, and also because I've recommended Python > for his stated needs. Also, interested to see what other Pythonistas > have to say in response to my reply. > - Vasudev] > > > On Jul 16, 2007, at 2:21 AM, Michael Reiland wrote: > > > At the heart of the issue is the fact that I refuse to use Java for this > project, I prefer not to use .Net because of the portability issues, > and > I'd like to get away from C++ for obvious reasons. > > > To me this means Ruby, Python, or, as mentioned above, Perl. If anyone > can tell me of a way to meet the above requirements in either Python > or > Perl, I'm all ears (I just prefer Ruby). > > Yes, I think it would be really great for the Ruby community and for > the growth of the language if wxRuby was more mature as a GUI toolkit. > (Not knocking the wxRuby developers at all, its great that they've > even done what they have - I know that creating other language (like > Ruby) bindings to a C++ lib is a non-trivial task). > > My suggestion: Python + wxPython + Python DBI + (Py2Exe + InnoSetup) > *might* meet all your needs. (As with any decision about what software > technologies to use, you'll have to evaluate the suggested options to > see if they fit your needs.) > > Note: I've used and like both Ruby and Python (saying this after using > many, though not all, language features and libraries of both > languages), and am not trying to discourage you from using Ruby for > your needs; its just that, based on your needs as described, it looks > to me as if Python meets them better than Ruby at present: > > > 1. GUI - Native Look and Feel. According to wxRuby the bindings aren't > mature enough for production use. Does anyone have any experience > with > this and/or can you offer alternatives that provide a native look and > feel (I > > I don't know enough about wxRuby to comment. > > wxPython has this (Native Look and Feel), I think (used it some, a > while ago), not 100% sure, you can check on the site - http:/ > www.wxpython.org > - to make sure. The site does say that it is cross-platform: > > "wxPython is a cross-platform toolkit. This means that the same > program will run on multiple platforms without modification. Currently > supported platforms are 32-bit Microsoft Windows, most Unix or unix- > like systems, and Macintosh OS X. > " > > but that doesn't necessarily mean that it will have native look and > feel on all supported platforms. (The two are not the same thing.) > That's why you will need to check. > > wxPython pros: Its fairly easy to learn, at least for simple GUI apps > (e.g. a few widgets / controls and a file dialog or two). I was able > to build these simple ones - see the code, article and screenshots > available here (or from links from here): > > http://www.packtpub.com/article/Using_xtopdf > > - in quite a short time, starting from zero knowledge of wxPython (I > did know some Python from before), just by looking at the sample apps, > and some reading of the docs. > > See the quotes about wxPython: http://www.wxpython.org/quotes.php > > >2. Databases - contemplating using ActiveRecord, but I would like to use > ODBC to support multiple types of DB's in a uniform way (if you know > of > alternatives to ODBC or ActiveRecord, please let me know). > > I think, but again, not sure, that Python DBI + appropriate database > drivers, may meet this need. Basically Python DBI is similar to ODBC > (roughly), and to Perl DBI + DBD, as I understand. There's also ODBC > support in the Win32 extensions package for Python - IIRC, Google for > 'win32all' to get it. Its also available as a link from the Python for > Win32 MSI installer on python.org. > I've used Python ODBC some, it works and is easy to use. > See this for a simple example: > > http://jugad.livejournal.com/2006/07/07/ > > (See the second post at that page, titled "Publishing ODBC database > content as PDF > ". The code shown in the post is not indented as per proper the Python > syntax (LiveJournal messed up the indentation), sorry about that, but > its trivial to correct if you know Python indenting rules). Also read > the Python ODBC docs and examples, of course. > > >3. Binary - Are there any utilities for compiling Ruby into a binary > executable? The issue is twofold, speed, and not handing the > customer > the source :) > > For Python, there is py2exe (for Windows only). I used py2exe recently > and it works well enough for the simple cases that I tried. (I tried > building EXEs for a simple Python hello-world program, and for a > simple wxPython GUI app based on my xtopdf toolkit. Both worked ok.) > For cross-platform (Windows and Linux, IIRC), there is PyInstaller > (Google for it), haven't tried it out yet, just downloaded it > recently. > > I don't think you'll gain much speed by this compiling step, though > (over and above what Python gives you itself, when it compiles > your .py files to .pyc files). The purpose of py2exe is more to hide > the source code than to speed it up, as I understand (could be wrong). > > Note: py2exe only creates an EXE and DLLs needed, from your source and > its required Python modules. To create an installer, try InnoSetup > (for Windows only). I recently tried it out, version 5, again, it > worked well. Could create Windows SETUP.EXE-type installers for the > two EXEs described above. Worked ok. > > I first learned Python, have been using it for some time for various > projects, and then learned Ruby, and have done some projects with Ruby > too. > > I've been reading both the Ruby Cookbook and the Python Cookbook > rather thoroughly in the last few weeks (and trying out and modifying > many of the recipes), and what I've observed is that the two languages > are roughly similar in features. For basic features common to most > languages (constants, variables, arrays, hashes/dictionaries, file I/ > O, classes, objects, modules/libraries, etc. - they work roughly in > the same fashion - though syntax obviously differs, you can mostly do > what you can in one of them, in the other as well. (Note that I'm not > talking about libraries here - this will obviously differ as each > language will have its own set of libraries for doing various tasks, > like networking and other areas - though even here there is a good > amount of overlap/similarity.) > > For more advanced language features related to object-orientation, > metaclasses / metaprogramming, both have some support, but you might > or might not be able to do in one, what you can do in the other. > > HTH > Vasudev Ram > Site: http://www.dancingbison.com > PDF toolkit (in Python): http://sourceforge.net/projects/xtopdf > Blog: http://jugad.livejournal.com > > You (or the OP) may be interested in Dabo (dabodev.org), which is a wxPython-based development environment. It's influenced by the easy database access and RAD of Delphi and Visual FoxPro. Python certainly meets the requirements listed, having mature, reliable tools to address all of the problems. From steve at holdenweb.com Tue Jul 31 22:34:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 31 Jul 2007 22:34:50 -0400 Subject: Finding documentation (WAS: Iteration over strings) In-Reply-To: <46AFEE96.5050007@jayloden.com> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> <46AF7A49.3040804@jayloden.com> <46AF8046.7090702@gmx.net> <496954360707311307y7d503b8eybd72795c8e699104@mail.gmail.com> <46AF9B2D.8040501@jayloden.com> <46AF9F55.20105@gmx.net> <46AFA1D9.1010707@gmx.net> <46AFCB8C.9060800@jayloden.com> <46AFEE96.5050007@jayloden.com> Message-ID: <46AFF14A.9030005@holdenweb.com> Jay Loden wrote: > Steve Holden wrote: >> In this particular case the documentation is quite explicit about the >> return value and the documentation for the function runs to almost 400 >> words. Do you expect *everything* to be in the source? That isn't >> practical, as documenting everything twice like that makes twice the >> work when the function changes and the documentation has to be rewritten. > > (starting a new thread so that we're not off topic for the original one) > Well, you *think* you have started a new thread, but in fact you have just changed the title of the existing one :-) > Hmmm. Jerry Hill pointed out also that this information is documented clearly in the online docs (as opposed to docstrings I was looking at with pydoc). I guess I'm just confused about the purpose of pydoc and module documentation. I was under the impression it was intended to serve as the API reference, so when people say "consult the documentation" I usually check pydoc first before hitting the web browser. I was under the impression earlier that docs.python.org was mostly generated from the docstrings similar to how javadocs are converted to html. > > That being said, it does make sense to me however that you should be able to use pydoc to tell you simple things like the return value of a function, the required parameters, etc. I'd be interested to hear from some more experienced programmers what your typical usage would be when reference documentation for a given module. > > Are the HTML docs (e.g. what's on http://docs.python.org/) the canonical source? Is that where I should generally be looking? Are there other documentation resources you all have found useful as well? I'm curious to see if there are useful resources I'm just missing due to lack of knowledge or experience. > When people say "read the documentation" they generally mean the docs as distributed with each release, and docs.python.org is the easiest way to find the docs for the current release. There are several groups whose plans for documentation world dominance would somehow merge the documentation and the source. Personally I think the documentation in the source should be just enough to remind you how to use something you have already used before, so not understanding them is a good clue you need to look at docs.python.org. 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 kw at codebykevin.com Tue Jul 24 13:30:47 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 24 Jul 2007 13:30:47 -0400 Subject: Tix not properly installed on OS X? In-Reply-To: <98214A15-2E34-4C0E-BB34-2FD8A92A2ACC@bryant.edu> References: <48B39FEC-D3B9-4FAF-AD45-0DD744D8D289@bryant.edu> <46A60C80.60502@codebykevin.com> <98214A15-2E34-4C0E-BB34-2FD8A92A2ACC@bryant.edu> Message-ID: <46A63747.7090107@codebykevin.com> Brian Blais wrote: > So I tried to build Tix, and it complains about a tcl header file > (tclPort.h). My Tcl stuff is in > /System/Library/Frameworks/Tcl.framework/Versions/8.4/, but the header > file doesn't exist. I assume I need to download the source for Tcl and > build that, or is it enough to have the headers from the source of tcl? > I just don't want to break something that is already there. > > You need the source for both Tcl and Tk, and Tix should be in the same directory tree. --Kevin From http Wed Jul 4 12:52:37 2007 From: http (Paul Rubin) Date: 04 Jul 2007 09:52:37 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> Message-ID: <7x4pkkun56.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > Because static type checks impose a lot of arbitrary restrictions, > boilerplate code etc, which tends to make code more complicated than > it needs to be, which is a good way of introducing bugs that wouldn't > have existed without static type checks. Why do you say that? By metrics and anecdotal evidence, Haskell code appears to be at least as compact as Python code. > Depending on the application domain and some technical and > non-technical constraints and requirements, it (often) happens that > it's better to have the application deployed now with an occasional > error message than to have it next year... I suppose that includes the thing I'm currently working on. For some other stuff I've done, such errors would have caused huge hassles, lost customer money, etc. > And FWIW, when it comes to "weird piece of input data", statically > typed languages are not specially better than dynamic ones... I know that ML gives compiler warning messages if you have a pattern match (sort of a variant of a case statement, not a regexp match) which is non-exhaustive. And Haskell's Maybe monad is part of an idiom that handles failing computations (like regexp matches) much more gracefully than Python can. Both of those would help this situation. From nospam.themindstorm at gmail.com Fri Jul 20 19:55:56 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Fri, 20 Jul 2007 23:55:56 +0000 (UTC) Subject: Sorting dict keys References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> Message-ID: Miles wrote in news:a49e45f50707201627n524f6a49n13f2ca97f55d4133 at mail.gmail.com: > On 7/20/07, Alex Popescu wrote: >> If you just want to iterate over your dict in an ordered manner than >> all you have to do is: >> >> for k in my_dict.keys().sort(): >> # rest of the code > > I think you meant sorted(my_dict.keys()), since, as you just pointed > out, the sort() method returns None. > >> If you just want to keep a list of ordered keys you can probably do >> something like: >> >> key_list = list(my_dict.keys()) >> key_list.sort() > > Creating a copy with list() is unnecessary, as keys() already returns > a copy. > > -Miles You are absolutely right about both points (it looks like answering python question very late in the evening doesn't work well for me, or at least not yet :-)). ./alex -- .w( the_mindstorm )p. From hey at mikehowarth.co.uk Fri Jul 27 04:42:06 2007 From: hey at mikehowarth.co.uk (Mike Howarth) Date: Fri, 27 Jul 2007 01:42:06 -0700 (PDT) Subject: Factory pattern again Message-ID: <11825158.post@talk.nabble.com> Hi I was wondering whether anyone could help me, I'm pretty new to python coming from a PHP background and I'm having a few products in getting my head round how to write the factory pattern within python. I'm currently looking to try to return values from a db and load up the relevant objects, values returned are product type (I,S) and product code (123). At the moment I've adapted some code I've found illustrating the factory method but ideally I would like to use the type to load up the relevant object. Another issue I've found is that I don't seem to be able to access to the price attribute of each of the object. I'm sure these are very straightforward issues however I seem to have tied myself in knots over this and could do with a fresh set of 'pythonic' eyes to help me out. registry = {} class MetaBase(type): def __init__(cls, name, bases, dict): registry[name] = cls class Product(object): __metaclass__ = MetaBase class Item(Product): def __init__(self, *args, **kw): self.price = 1 class Set(Product): def __init__(self, *args, **kw): self.price = 2 def factory(kind, *args, **kw): return registry[kind](*args, **kw) item = registry['Item'] print item.price -- View this message in context: http://www.nabble.com/Factory-pattern-again-tf4156186.html#a11825158 Sent from the Python - python-list mailing list archive at Nabble.com. From listservs at mac.com Thu Jul 12 14:49:11 2007 From: listservs at mac.com (Chris Fonnesbeck) Date: Thu, 12 Jul 2007 18:49:11 +0000 (UTC) Subject: Class decorators do not inherit properly Message-ID: I have a class that does MCMC sampling (Python 2.5) that uses decorators -- one in particular called _add_to_post that appends the output of the decorated method to a class attribute. However, when I subclass this base class, the decorator no longer works: Traceback (most recent call last): File "/Users/chris/Projects/CMR/closed.py", line 132, in class M0(MetropolisHastings): File "/Users/chris/Projects/CMR/closed.py", line 173, in M0 @_add_to_post NameError: name '_add_to_post' is not defined yet, when I look at the dict of the subclass (here called M0), I see the decorator method: In [5]: dir(M0) Out[5]: ['__call__', '__doc__', '__init__', '__module__', '_add_to_post', ... I dont see what the problem is here -- perhaps someone could shed some light. I thought it might be the underscore preceding the name, but I tried getting rid of it and that did not help. Thanks. From afriere at yahoo.co.uk Wed Jul 11 01:48:24 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 10 Jul 2007 22:48:24 -0700 Subject: pattern match ! In-Reply-To: <1184125206.034047.175340@n60g2000hse.googlegroups.com> References: <1184125206.034047.175340@n60g2000hse.googlegroups.com> Message-ID: <1184132904.797352.83030@i38g2000prf.googlegroups.com> On Jul 11, 1:40 pm, hari.sir... at gmail.com wrote: > Extract the application name with version from an RPM string like > hpsmh-1.1.1.2-0-RHEL3-Linux.RPM, i require to extract hpsmh-1.1.1.2-0 > from above string. Sometimes the RPM string may be hpsmh-1.1.1.2-RHEL3- > Linux.RPM. Now that list-like splicing and indexing works on strings, why not just splice the string, using .index to locate '-RHEL'? From no at no.no Fri Jul 13 14:18:47 2007 From: no at no.no (Daniel) Date: Fri, 13 Jul 2007 21:18:47 +0300 Subject: NoneType object not iterable References: <5fptm0F3d0jiiU1@mid.individual.net> Message-ID: On Fri, 13 Jul 2007 21:13:20 +0300, Bjoern Schliessmann wrote: > > Daniel wrote: > >> db is out of scope, you have to pass it to the function: > > What's wrong about module attributes? > I made a mistake From hniksic at xemacs.org Tue Jul 17 04:47:49 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 17 Jul 2007 10:47:49 +0200 Subject: Implementaion of random.shuffle References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> <1184597148.692325.36590@x35g2000prf.googlegroups.com> Message-ID: <87abtvl8lm.fsf@mulj.homelinux.net> Steven D'Aprano writes: > In the case of CPython, the current implementation uses the Mersenne > Twister, which has a huge period of 2**19937. However, 2081! is > larger than that number, which means that at best a list of 2081 > items or longer can't be perfectly shuffled (not every permutation > can be selected by the algorithm). Note that each shuffle requires n calls to the PRNG, not just one, which reduces the theoretically safe list size by 1. From omari at smileystation.com Tue Jul 17 18:54:55 2007 From: omari at smileystation.com (Omari Norman) Date: Tue, 17 Jul 2007 18:54:55 -0400 Subject: Interpreting non-ascii characters. In-Reply-To: References: Message-ID: <20070717225455.GA15032@cameron> > I want to create a script which reads files in a > current directory and renames them according to some > scheme. The file names are in Russian - sometimes > the names encoded as win-1251, sometimes as koi8-r etc. > I want to read in file name and convert it to list for > further processing. The problem is that Python treats Apparently os.listdir returns a list of Unicode objects if the pathname you give it is a Unicode object. So, Python should then convert the Russian filenames to Unicode, using whatever encoding necessary. (I don't know, however, how Python would know what to do if the filenames are in a bunch of different encodings, as you say.) If you can get the filenames into Unicode, then you can manipulate them however you like. -- For help at any time, press *H. From mccredie at gmail.com Wed Jul 11 01:43:03 2007 From: mccredie at gmail.com (Matimus) Date: Wed, 11 Jul 2007 05:43:03 -0000 Subject: SafeConfigParser can set unsafe values In-Reply-To: References: <46940a3e$0$18464$afc38c87@news.optusnet.com.au> <1184111631.293350.106340@o11g2000prd.googlegroups.com> Message-ID: <1184132583.087293.174890@e9g2000prf.googlegroups.com> > This not only happens when get() after a set(), but with all the use cases > above. An intervening write()/read() does not change things. > But I'm not sure it is a bug really. If all % were escaped automatically, > there is no way to write a templatized value. Maybe SafeConfigParser.set > should grow an escape argument, controlling whether one wants the value > escaped or not. For compatibility reasons should default to False, for > usability reasons should default to True. The exception is only raised when get is called, the "raw" paremeter for get(...) is set to False (default) and the string value for that parameter contains a single "%". None of the cases I stated above call get() after calling set(). So, the exception will never be raised because of something the user set. It will be raised if the input file happens to have a single "%" character in one of the parameter values, but that content could have been user generated, and it is not reasonable to assume that fixing the set() method would have prevented it. Adding an escape parameter to set will not be used properly. Its purpose would be to escape lone "%" characters, but if users are wanting to use the substitution they would always keep escaping off. It wouldn't allow them catch situations like this: cp.set("sect","param","this is my value %(key)s and here is a lone % and here is another %(sub)s", escape=False) The solution I would propose is to raise an exception on set() if the value contains a single "%" not followed by a key name enclosed in parens followed by "s". That puts the burden of escaping on the user, before passing it to set. From erexsha at gmail.com Wed Jul 25 17:57:44 2007 From: erexsha at gmail.com (Arash Arfaee) Date: Wed, 25 Jul 2007 14:57:44 -0700 Subject: TypeError: 'int' object is not callable for max(2,3) Message-ID: <266557d0707251457t5a9237abv2118ffebf58290cc@mail.gmail.com> Hi all, I have a problem. if I enter max(2,3) before I run my program in command line it returns 3. However if I start to debug my program, I have this error: [Dbg]>>> max(2,3) Traceback (most recent call last): File "", line 1, in TypeError: 'int' object is not callable Any idea what should be the reason? Cheers, Arash -------------- next part -------------- An HTML attachment was scrubbed... URL: From alia_khouri at yahoo.com Sun Jul 29 17:29:58 2007 From: alia_khouri at yahoo.com (Alia Khouri) Date: Sun, 29 Jul 2007 14:29:58 -0700 Subject: problems with logging module Message-ID: <1185744598.663382.126920@19g2000hsx.googlegroups.com> I've been struggling with the logging module in the stdlib which seems to me rather counter-intuitive: For some reason it refuses to recognize configuration options when they are set inside a class so I have had to initialize logging and set the configuration options in the global scope of my module with logging.basicConfig. Here's what I did within the class setup method: self.log = logging.getLogger() # format log_format= self.local.format date_format = self.local.date_format or "%d.%m.%y %H:%M:%S" self.logfile= self.local.logfile if self.local.log_to_file else None if self.logfile: handler = logging.FileHandler( self.logfile, self.local.logfile_mode) else: stream = None # can be sys.st something or other stream handler = logging.StreamHandler() format = logging.Formatter(log_format, date_format) handler.setFormatter(format) self.log.addHandler(handler) self.log.setLevel(self.local.log_level or logging.DEBUG) self.log gets initialized but the formatting options do not get recognized... this is a pain... What I do want is something like the log4r module in Ruby: e.g. require 'log4r' require 'getoptlong' require 'pathname' class Common def init_log @log = Log4r::Logger.new(self.class.name) @log.add Log4r::Outputter.stdout @log.info 'initialized' end end class Builder < Common def initialize(path, options) init_log if File.exist?(path) @path = Pathname.new(path) @options = options else @log.error "not a valid file or directory" exit end end def build() case @path.ftype when 'file' filehandlers = { '.txt' => TxtHandler, '.java' => JavaHandler, '.c' => CHandler, '.cpp' => CppHandler, '.py' => PyHandler, '.pyx' => PyxHandler, '.exe' => ExeHandler, '.hs' => HaskellHandler, '.rb' => RubyHandler, '.dot' => DotHandler, '.mp3' => MP3Handler, '.wav' => WavHandler, '.csd' => CSoundHandler, '.orc' => CSoundHandler, '.sco' => CSoundHandler, }[@path.extname].new(@path, @options).handle() when 'directory' @log.info "#{@path} is a directory" end end end etc... still to prefer to code in python though.... Just my 2c... AK From JHoover at fbi.gov Tue Jul 24 23:02:51 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Tue, 24 Jul 2007 23:02:51 -0400 Subject: idiom for RE matching In-Reply-To: References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> <1185157313.356112.159020@z24g2000prh.googlegroups.com> <2f6dnUlUxd2_7TjbnZ2dnUVZ_qy3nZ2d@comcast.com> Message-ID: Gabriel Genellina wrote: > As is often the case, a regular expression is NOT the right tool to use > in this case. > > --Gabriel Genellina Very interesting, thank you. I think 'pattern matching' and I automatically think 'regular expressions'. I did already find that it speeds things up to pre-test a line like if 'bets' or 'calls' or 'raises' in line: run the appropriate re's which isn't very pretty at all, and it seems I didn't manage to take the next steps to doing aways with the re's altogether. From laurent.pointal at wanadoo.fr Sun Jul 1 17:06:26 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Sun, 01 Jul 2007 23:06:26 +0200 Subject: The best platform and editor for Python References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> Message-ID: <46881750$0$25915$ba4acef3@news.orange.fr> kimiraikkonen wrote: > Hi, > For experienced with Pyhton users, which developing software and > enviroment would you suggest for Pyhton programming? Compiler+Editor > +Debugger. > > Also what are your suggestions for beginners of Pyhton programming? Under Windows, take a look at PyScripter. For students learning Python, we are switching from Scite to PyScripter, good editor, online Python shell, graphical debugger with step by step, showing variables values in popups and many other sympathic features... test it. From S.Mientki-nospam at mailbox.kun.nl Mon Jul 16 05:33:21 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 16 Jul 2007 11:33:21 +0200 Subject: running a Delphi part from Python ? In-Reply-To: <469b3530$0$26995$426a74cc@news.free.fr> References: <889c1$469b275c$d443bb3a$2876@news.speedlinq.nl> <469b2b65$0$21672$426a74cc@news.free.fr> <86c61$469b30d1$d443bb3a$15805@news.speedlinq.nl> <469b3530$0$26995$426a74cc@news.free.fr> Message-ID: <47dce$469b3a07$d443bb3a$26795@news.speedlinq.nl> tool69 wrote: > Stef Mientki a ?crit : > >> AFAIK, Scintilla is a code editor. >> What I need looks more like ms-word, >> handling lists, tables, images, formulas. >> >> thanks, >> Stef Mientki > > > So you'll need the RichTextCtrl > > http://www.wxpython.org/docs/api/wx.richtext.RichTextCtrl-class.html > > See a sample in the demo under "Recent Additions". Well it's better, - it has lists - it has images, but no image editing, It doesn't have - drag & drop - tables, - formula editing, - screen capture, - links - embedded code - CSS - .... so unfortunately it's not yet sufficient :-( thanks, Stef Mientki From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 13 11:03:54 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 13 Jul 2007 17:03:54 +0200 Subject: access to the namespace of a function from within its invocation In-Reply-To: References: Message-ID: <46979430$0$26406$426a74cc@news.free.fr> Poor Yorick a ?crit : > In the example below, the attribute "data" is added to a function > object. "me" can be used to get the function when it is invoked using > an identifier that matches the "co_name" attribute of function's code > object. Can anyone conjure an example of accessing fun2.data from > without prior knowledge of the value of fun2.f_code.co_name? > > ###code begin### > #!/bin/python > > import sys > > def me(): > t = sys._getframe(0) > return t.f_back.f_globals[t.f_back.f_code.co_name] > def fun1(): > m = me > print me().data > def makefun () : > def tmpfunc(): > print 'need something like me().data' > return tmpfunc > > fun1.s = fun1 > fun1.data=['one', 'two', 'three'] > fun1() > fun2 = makefun() > fun2.data=['four', 'five','six'] > fun2() > > ###code end### > Not a direct answer to your question, but anyway; As soon as you want to bundle data with behaviour, OO comes to mind. Good news is that Python is actually an OOPL which implements functions as objects and let you define function-like ('callable') objects. class DataFunc(object): def __init__(self, data): self.data = data def __call__(self, *args, **kw): print self.data fun2 = DataFunc(['four', 'five', 'forty-two']) fun2() Note that you'll also have to correctly implement the __get__ method if you want an instance of DataFunc to be usable as a method (look for the descriptor protocol in the FineManual(tm) for more information on this point). HTH From carsten at uniqsys.com Mon Jul 30 09:08:27 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 30 Jul 2007 09:08:27 -0400 Subject: Detecting __future__ features In-Reply-To: <1185800016.950517.43240@g4g2000hsf.googlegroups.com> References: <1185800016.950517.43240@g4g2000hsf.googlegroups.com> Message-ID: <1185800907.3415.6.camel@dot.uniqsys.com> On Mon, 2007-07-30 at 12:53 +0000, Andr? wrote: > On Jul 30, 9:39 am, Neil Cerutti wrote: > > On 2007-07-30, Steven D'Aprano > > > > wrote: > > > How would one tell at runtime if a particular feature has been > > > enabled by the "from __future__ import thing" statement? > > > > I don't understand the qualification, "at runtime," you're > > making. What's wrong with just importing what you want and using > > it? If it's already been enabled, no harm will come from the > > import statement. > > > > I'm not the OP, so perhaps I am missing his intent. However, I can see > a good reason for asking this question. > > I seem to recall that the "from __future__ import" statement can only > be done at the beginning of a script. Incorrect. It must be done at the beginning of the *file*. > What if you are designing a > module meant to be imported, and used by other programs over which you > have no control? You can't use "from __future__ import" in your > module. Incorrect. You can use a __future__ import in a module as long as you do it at the beginning of the modul file. > So, you may have to find a way to figure out what's been > done. (the example given with the division operator is a good one). No. __future__ directives are scoped to the module. Observe: $ cat f1.py def f1(): print 1/2 f1() import f2 f2.f2() $ cat f2.py from __future__ import division def f2(): print 1/2 $ python f1.py 0 0.5 As you can see, f1 uses past semantics, f2 uses future semantics. Just use whatever __future__ directives you need for your module at the beginning of your module, and everything will just work. HTH, -- Carsten Haese http://informixdb.sourceforge.net From thomas at jollans.com Sun Jul 1 15:38:06 2007 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 1 Jul 2007 21:38:06 +0200 Subject: How does py2exe work? In-Reply-To: <1183314093.002061.310700@m37g2000prh.googlegroups.com> References: <1183314093.002061.310700@m37g2000prh.googlegroups.com> Message-ID: <200707012138.10254.thomas@jollans.com> On Sunday 01 July 2007, vasudevram wrote: > Wondering how it works? Does it actually compile the Python source of > your script into machine language, or does it do something more like > bundling the Python interpreter, the Python libraries and the script > itself, into a file? essentially, that's what it does. -- 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 mail at microcorp.co.za Mon Jul 9 01:59:57 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 9 Jul 2007 07:59:57 +0200 Subject: socket: connection reset by server before client gets response References: <1183819907.249945.239700@o11g2000prd.googlegroups.com><1183827514.109496.252870@d30g2000prg.googlegroups.com> <1183900086.021428.83580@e9g2000prf.googlegroups.com> Message-ID: <003301c7c1ee$617ce220$03000080@hendrik> "ahlongxp" wrote: > > > Try to wait a while in the server thread, after sending the > > message before closing the connection, to give the message > > time to get transmitted. > > > > time.sleep(0.5) should do it... > > > > - Hendrik > > OMG, it works. > I can't believe the problem can be solved so easily. > > Thanks very much. It's a pleasure. Sometimes I think that all would be programmers should be forced to write a "Hello World" to transmit out of a serial port in assembler on hardware that carries no OS - just to teach them about interrupts and time. I would require them to hand assemble the code too, to make them appreciate what a compiler or an interpreter does. And if you fail the test, you get taken out and fed to the sacred crocodiles. - Hendrik -- For training with a bite, enrol now in Heavy Henry's Wholesome Hackadamy for Precocious Programmers From mfmorss at aep.com Thu Jul 5 13:30:17 2007 From: mfmorss at aep.com (Mark Morss) Date: Thu, 05 Jul 2007 10:30:17 -0700 Subject: The best platform and editor for Python In-Reply-To: References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> Message-ID: <1183656617.639789.106840@r34g2000hsd.googlegroups.com> On Jul 1, 3:30 pm, "S?nmez Kartal" wrote: "Emacs is the best for anything for me." Me too. Also, as pointed out by some others, a debugger is not really all that necessary for an interpreted language like Python. > > Hi, > > For experienced with Pyhton users, which developing software and > > enviroment would you suggest for Pyhton programming? Compiler+Editor > > +Debugger. > > > Also what are your suggestions for beginners of Pyhton programming? > > > Thank you. > > > -- > >http://mail.python.org/mailman/listinfo/python-list From rjh at see.sig.invalid Tue Jul 3 04:57:47 2007 From: rjh at see.sig.invalid (Richard Heathfield) Date: Tue, 03 Jul 2007 08:57:47 +0000 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> <7x645al8kc.fsf@ruckus.brouhaha.com> <1182894003.920335.317620@a26g2000pre.googlegroups.com> <7x7ipoy6cf.fsf@ruckus.brouhaha.com> <1183041149.275562.114490@o11g2000prd.googlegroups.com> <7xbqethpr8.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin said: > sla29970 at gmail.com writes: >> As for the primacy of UTC vs. TAI, this is the classical chicken and >> egg problem. The bureaucratic reality is opposed to the physical >> reality. > > Well, if you're trying to pick just one timestamp standard, I'd say > you're better off using a worldwide one rather than a national one, no > matter how the bureaucracies work. In that case, the obvious choice is Greenwich Mean Time. :-) Seriously, GMT is recognised all over the world (far more so, in fact, than UTC, which tends to be recognised only by some well-educated people, and there are precious few of those), so why not use it? I always leave my PC's clock set to GMT, partly out of this desire to support a single timestamp standard, and (it must be said) partly out of general cussedness. -- Richard Heathfield Email: -www. +rjh@ Google users: "Usenet is a strange place" - dmr 29 July 1999 From WChunming at gmail.com Wed Jul 4 23:15:48 2007 From: WChunming at gmail.com (WChunming at gmail.com) Date: Wed, 04 Jul 2007 20:15:48 -0700 Subject: debug(read source code and test) pypy in pydev Message-ID: <1183605348.485897.236880@e16g2000pri.googlegroups.com> Hi, I am a newbie to python and pypy. I choose to read pypy source code to learn about python and python library. But when I try to run pypy in debug mode in pydev, I got the following problem: /// error message begin pydev debugger Traceback (most recent call last): File "F:\TOOLS\eclipse\plugins\org.python.pydev.debug_1.3.4\pysrc \pydevd.py", line 754, in debugger.run(setup['file'], None, None) File "F:\TOOLS\eclipse\plugins\org.python.pydev.debug_1.3.4\pysrc \pydevd.py", line 597, in run execfile(file, globals, locals) #execute the script File "E:\Java\pySamples\pypy\bin\py.py", line 14, in from pypy.tool import option File "E:\Java\pySamples\pypy\tool\option.py", line 4, in from pypy.config.pypyoption import get_pypy_config File "E:\Java\pySamples\pypy\config\pypyoption.py", line 2, in import py, os File "E:\Java\pySamples\pypy\bin\py.py", line 14, in from pypy.tool import option ImportError: cannot import name option Exception in thread pydevd.Writer (most likely raised during interpreter shutdown): Traceback (most recent call last): File "C:\Python25\lib\threading.py", line 460, in __bootstrap File "F:\TOOLS\eclipse\plugins\org.python.pydev.debug_1.3.4\pysrc \pydevd_comm.py", line 258, in run /// error message end I try to figure out why this exception or error come out. I found that py.py import option.py, and option.py import pypyoption.py, and pypyoption.py import py.py again. Is this the problem of pypy(I don't think so), or the problem of pydev debugger, or something else? why? Any comments or assistance that can light up the way are much appreciated.Thanks. Wang Chunming From cbfalconer at yahoo.com Sun Jul 1 14:34:24 2007 From: cbfalconer at yahoo.com (CBFalconer) Date: Sun, 01 Jul 2007 14:34:24 -0400 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> Message-ID: <4687F3B0.1A9E2B54@yahoo.com> Roedy Green wrote: > On 25 Jun 2007 18:46:25 -0700, Paul Rubin > ... snip ... > >> TAI really does seem like the most absolute--if you are a user >> in orbit or on Mars, then UTC timestamps will seem pretty >> meaningless and artificial. > > According to Einstein all time is local time, so perhaps our wish > for a clean UT is a pipedream. > > To add to the confusion you have GPS, Loran and Julian day also > used as scientific times. In summary, time is now defined as a non-continuous function, and is thus proof against manipulation by most standard algebraic techniques. Take that :-) In fact, it is not even quanticized. -- cbfalconer at maineline dot net -- Posted via a free Usenet account from http://www.teranews.com From stevensenior at f2s.com Sat Jul 7 08:55:53 2007 From: stevensenior at f2s.com (Steve Senior) Date: Sat, 07 Jul 2007 13:55:53 +0100 Subject: wxPython - ListCtrl ColumnSorterMixin sometimes works sometimes doesn't! Message-ID: <468F8D59.4030900@f2s.com> Hi, My application has a tree control in which a user can select a filter. This filter is then applied to the results and the results are constructed in the ListControl (report style) widget. This all works fine. Recently I added the wx.lib.mixins.listctrl.ColumnSorterMixin mixin to the ListCtrl widget. Now here is the problem. On some of the filters you can sort all of the columns both ascending and descending - i.e. if you click a column once it will sort properly, then if you click the column again it will happily reverse the sort. On some of the filters you can only sort the column once. Repeated clicks do not reverse the sort order. I added some print statments to the listctrl.py to see what was happening here and it appears that when you click the column for the second time, it actually sorts it twice which means that the display doesn't change! This is really perplexing me, I've exhausted all of my options and need some help please. Many Thanks, Steve. From robert.kern at gmail.com Fri Jul 13 23:13:00 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 13 Jul 2007 22:13:00 -0500 Subject: interactive graphical script builder In-Reply-To: References: <1184196856.996182.25040@k79g2000hse.googlegroups.com> Message-ID: James Stroud wrote: > nik wrote: >> Hi, >> >> I am looking for an interactive graphical script builder for python. >> Basically, something like the os X automator. I have made a group of >> methods that some non-programmers need to combine into a script. I >> don't need a python IDE necessarially, but more of a sequence builder. >> I am imagining a tool that could show graphical representations of my >> different commands and then string them together in a single "script." >> I've done a lot of googling, and the closest things that I can find >> are apple automator or labview, but before I go through the process of >> making one of those interact with python I would like to know if >> anybody already knows of something like them that is more tuned to >> python. > > Check out Viper at Scripps (Sanner, lab). He has a prototype of this > type of thing for working with molecular models. I'm not sure how the > code is liscensed. It's called Vision, now, and it's only available for noncommercial, scientific research use. http://www.scripps.edu/%7Esanner/python/vision/index.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 george.trojan at noaa.gov Tue Jul 17 07:46:17 2007 From: george.trojan at noaa.gov (George Trojan) Date: Tue, 17 Jul 2007 07:46:17 -0400 Subject: Compiling python2.5 on IBM AIX In-Reply-To: <1184659090.881833.124240@x35g2000prf.googlegroups.com> References: <1184581796.377610.98230@o61g2000hsh.googlegroups.com> <1184600488.343686.263220@d55g2000hsg.googlegroups.com> <1184659090.881833.124240@x35g2000prf.googlegroups.com> Message-ID: bravo.loic at gmail.com wrote: >> I haven't compiled it myself, but I'm told that the installation I >> work with was compiled with: >> >> export PATH=$PATH:/usr/vacpp/bin:/usr/vacpp/lib >> ./configure --with-gcc="xlc_r -q64" --with-cxx="xlC_r -q64" --disable- >> ipv6 AR="ar -X64" >> make >> make install > > I've tried with the followong configuration : > ---------- > export PATH=$PATH:/usr/vacpp/bin:/usr/vacpp/lib > ./configure --prefix=${BASE} --with-gcc="xlc_r -q64" --with-cxx="xlC_r > -q64" --disable-ipv6 AR="ar -X64" LDFLAGS="-L\${BASE}/lib/" PPFLAGS="-I > \${BASE}/include/" > > make > --------- > > but it doesn't compile either : > > make > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Modules/python.o ./Modules/python.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Modules/_typesmodule.o Modules/_typesmodule.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/acceler.o Parser/acceler.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/grammar1.o Parser/grammar1.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/listnode.o Parser/listnode.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/node.o Parser/node.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/parser.o Parser/parser.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/parsetok.o Parser/parsetok.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/bitset.o Parser/bitset.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/metagrammar.o Parser/metagrammar.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/firstsets.o Parser/firstsets.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/grammar.o Parser/grammar.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/pgen.o Parser/pgen.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/myreadline.o Parser/myreadline.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Parser/tokenizer.o Parser/tokenizer.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Objects/abstract.o Objects/abstract.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Objects/boolobject.o Objects/boolobject.c > xlc_r -q64 -c -DNDEBUG -O -I. -I./Include -DPy_BUILD_CORE - > o Objects/bufferobject.o Objects/bufferobject.c > "Objects/bufferobject.c", line 22.15: 1506-275 (S) Unexpected text ',' > encountered. > make: 1254-004 The error code from the last command is 1. > > any idea ? > > thanks > > -- > BL > It works fine with my compiler: > what $(which xlc) /usr/vac/bin/xlc: 61 1.14 src/bos/usr/ccs/lib/libc/__threads_init.c, libcthrd, bos510 7/11/00 12:04:14 Licensed Materials - Property of IBM. IBM XL C/C++ Enterprise Edition V8.0 for AIX (5724-M12) IBM XL C Enterprise Edition V8.0 for AIX (5724-M11) (C) Copyright IBM Corp. 1991, 2005 and by others. All Rights Reserved. US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp. ----------------------------------------- Version: 08.00.0000.0010 Intermediate Language 060405.07 Driver 060518a Date: Thu May 18 22:08:53 EDT 2006 ----------------------------------------- I suspect the trailing comma is the issue. Googling for "xlc enumerator trailing comma" gave me http://sources.redhat.com/ml/gdb/1999-q1/msg00136.html which says "AIX 4.2.0.0 xlc gives an error for trailing commas in enum declarations". George From MooMooBunnyLips at gmail.com Wed Jul 18 14:53:55 2007 From: MooMooBunnyLips at gmail.com (MooMooBunnyLips at gmail.com) Date: Wed, 18 Jul 2007 11:53:55 -0700 Subject: "The basics" difficulties Message-ID: <1184784835.875577.69000@i13g2000prf.googlegroups.com> I'm trying to get this basic sample to work: http://docs.python.org/ext/dnt-basics.html When I get to the last step: $ python setup.py build I get this error: error: Python was build with Visual Studio version 8.0 and extensions need to be built with the same version of the compiler, but it isn't installed. This is bogus, as I do have VS8 installed. I used it to compile the python stuff actually. Is there anyway to get this to work without using the distutils; i.e. just compiling it myself? Thank you From wildemar at freakmail.de Fri Jul 27 14:26:55 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 27 Jul 2007 20:26:55 +0200 Subject: a simple string question In-Reply-To: <1185558406.916313.32980@r34g2000hsd.googlegroups.com> References: <1185549793.114644.62170@k79g2000hse.googlegroups.com> <1185558406.916313.32980@r34g2000hsd.googlegroups.com> Message-ID: <46AA38EF.1080104@freakmail.de> vedrandekovic at v-programs.com wrote: >> If I understand you correctly you want to replace ";" by ";\n" and ":" >> by ":\n\t\t\t\t\t\t\t". >> Well guess what? The replace() method does just this. Have a read: >> >> > No,that's not what I need... > When this function detect ";" or ":" ,it must append character "\n" or > "\n\t" ahead ":" or ";" another e.g > > 1) text="Hello world;Hello:Hello2" > > 2) When function detect ";" or ":" it must append character "\n" or "\n > \t" ahead ":" or ";", so that must look like this: > > NEW TEXT : "Hello world;\nHello:\n\t\t\n\n\n\n\n\nHello2" > > Isn't that what I said? Please note that appending "\n" to ";" is the very same thing as replacing ";" with ";\n". Also note that the your description of the desired behavior does not match your example. You say "append "\n\t" after ":"", but thats not what happens in your example. There you append "\n\t\t\n\n\n\n\n\n" instead of "\n\t". That is confusing to me. Can you explain? /W From laurent.pointal at limsi.fr Tue Jul 3 03:21:22 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Tue, 03 Jul 2007 09:21:22 +0200 Subject: Correct abstraction for TK In-Reply-To: <1183412267.513714.183800@q75g2000hsh.googlegroups.com> References: <1183412267.513714.183800@q75g2000hsh.googlegroups.com> Message-ID: luke.hoersten at gmail.com a ?crit : > I'm looking for a good example of how to correctly abstract TK code > from the rest of my program. I want to just get some user info and > then get 4 values from the GUI. Right now I've written it OOP per the > examples on python.org but it doesn't seem to be meshing very well > with the rest of my project. > > Can anyone suggest some examples so that I can get more ideas? > > Thanks, > Luke > Maybe try with easygui [1]. The multenterbox [2] seem to be right to enter 4 values [3]... Its really a nice tool to have a quick and clean user input solution with GUI in a function. A+ Laurent. [1] http://www.ferg.org/easygui/ [2] http://www.ferg.org/easygui/screenshot-multenterbox.png [3] From the doc: MULTENTERBOX AND MULTPASSWORDBOX -- GETTING INFORMATION FROM THE USER ABOUT MULTIPLE FIELDS ======================================================================= Multenterbox is a simple way of showing multiple enterboxes on a single screen. Multpasswordbox has the same interface as multenterbox, but when it is displayed, the last of the fields is assumed to be a password, and is masked with asterisks. def multenterbox(message="Fill in values for the fields." , title="" , argListOfFieldNames = [] , argListOfFieldValues = [] ): """Show screen with multiple data entry fields. The third argument is a list of fieldnames. The the forth argument is a list of field values. If there are fewer values than names, the list of values is padded with empty strings until the number of values is the same as the number of names. If there are more values than names, the list of values is truncated so that there are as many values as names. Returns a list of the values of the fields, or None if the user cancels the operation. Here is some example code, that shows how values returned from multenterbox can be checked for validity before they are accepted. -------------------------------------------------------------- msg = "Enter your personal information" title = "Credit Card Application" fieldNames = ["Name","Street Address","City","State","ZipCode"] fieldValues = [] # we start with blanks for the values fieldValues = multenterbox(msg,title, fieldNames) # make sure that none of the fields was left blank while 1: if fieldValues == None: break errmsg = "" for i in range(len(fieldNames)): if fieldValues[i].strip() == "": errmsg = errmsg + ('"%s" is a required field.\n\n' % fieldNames[i]) if errmsg == "": break # no problems found fieldValues = multenterbox(errmsg, title, fieldNames, fieldValues) print "Reply was:", fieldValues ------------------------------------------------------------ """ From lance at augustmail.com Mon Jul 16 10:49:14 2007 From: lance at augustmail.com (Lance Hoffmeyer) Date: Mon, 16 Jul 2007 14:49:14 GMT Subject: win32com ppt saveas, not allowing spaces? Message-ID: Hey all, As always, thanks in advance! I am trying to save a ppt presentation but am having problems regarding spaces and am wondering if I am doing something wrong or whether this is a bug? Also, is there a way around this other than not using spaces in paths or filenames? I can create filesnames without spaces but don't have much control over paths. Lance WB.SaveAs("C:/temp/00_FINAL." + time.strftime("%Y.%m.%d.(%I.%M.%S%p)", time.localtime()) + ".ppt") saves the file C:\temp\00_FINAL.2007.07.16.(09.43.50AM).ppt but WB.SaveAs("C:/tmp dir/00_FINAL." + time.strftime("%Y.%m.%d.(%I.%M.%S%p)", time.localtime()) + ".ppt") gives the error: Traceback (most recent call last): File "C:\temp\ppt.py", line 412, in ? WB.SaveAs("C:/tmp dir/00_FINAL." + time.strftime("%Y.%m.%d.(%I.%M.%S%p)", time.localtime()) + ".ppt") File "C:\Program Files\Python\lib\site-packages\win32com\gen_py\91493440-5A91-11CF-8700-00AA0060263Bx0x2x8.py", line 6827, in SaveAs return self._oleobj_.InvokeTypes(2036, LCID, 1, (24, 0), ((8, 1), (3, 49), (3, 49)),FileName, FileFormat, EmbedTrueTypeFonts) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Microsoft Office PowerPoint 2003', 'Presentation.SaveAs : The path or file name for C://tmp%20dir/00_FINAL.2007.07.16.(09.44.01AM).ppt is invalid. Please check that the path and file name are correct.', '', 0, -2147467259), None) Tool completed with exit code 1 Also, WB.SaveAs("C:/temp/00 FINAL." + time.strftime("%Y.%m.%d.(%I.%M.%S%p)", time.localtime()) + ".ppt") yields: C:/temp/00%20FINAL.2007.07.16.(09.45.35AM).ppt Lance From roger.dahlstrom at gmail.com Fri Jul 13 12:05:24 2007 From: roger.dahlstrom at gmail.com (rdahlstrom) Date: Fri, 13 Jul 2007 16:05:24 -0000 Subject: web page text extractor In-Reply-To: <1184331458.125253.161510@j4g2000prf.googlegroups.com> References: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> <1184319891.778537.71000@m3g2000hsh.googlegroups.com> <1184331458.125253.161510@j4g2000prf.googlegroups.com> Message-ID: <1184342724.991978.133980@m3g2000hsh.googlegroups.com> To maintain paragraphs, replace any p or br tags with your favorite operating system's crlf. On Jul 13, 8:57 am, kublai wrote: > On Jul 13, 5:44 pm, Paul McGuire wrote: > > > > > On Jul 12, 4:42 am, kublai wrote: > > > > Hello, > > > > For a project, I need to develop a corpus of online news stories. I'm > > > looking for an application that, given the url of a web page, "copies" > > > the rendered text of the web page (not the source HTNL text), opens a > > > text editor (Notepad), and displays the copied text for the user to > > > examine and save into a text file. Graphics and sidebars to be > > > ignored. The examples I have come across are much too complex for me > > > to customize for this simple job. Can anyone lead me to the right > > > direction? > > > > Thanks, > > > gk > > > One of the examples provided with pyparsing is an HTML stripper - view > > it online athttp://pyparsing.wikispaces.com/space/showimage/htmlStripper.py. > > > -- Paul > > Stripping tags is indeed one strategy that came to mind. I'm wondering > how much information (for example, paragraphing) would be lost, and if > what would be lost would be acceptable (to the project). I looked at > pyparsing and I see that it's got a lot of text processing > capabilities that I can use along the way. I sure will try it. Thanks > for the post. > > Best, > gk From p at ulmcnett.com Sun Jul 22 14:36:01 2007 From: p at ulmcnett.com (Paul McNett) Date: Sun, 22 Jul 2007 11:36:01 -0700 Subject: Advice on sending images to clients over network In-Reply-To: <76fd5acf0707221115y5cfa7742s3228263640376436@mail.gmail.com> References: <1185095666.627415.108450@w3g2000hsg.googlegroups.com> <7xlkd8mktt.fsf@ruckus.brouhaha.com> <46A39BC8.6030106@ulmcnett.com> <76fd5acf0707221115y5cfa7742s3228263640376436@mail.gmail.com> Message-ID: <46A3A391.3030004@ulmcnett.com> Calvin Spealman wrote: > On 7/22/07, Paul McNett

wrote: >> Paul Rubin wrote: >> > Frank Millman writes: >> >> Any suggestions will be much appreciated. >> > >> > Why on earth don't you write the whole thing as a web app instead of >> > a special protocol? Then just use normal html tags to put images >> > into the relevant pages. >> >> I believe he has a full desktop client app, not a web app. Believe it or >> not, there's still a solid place for desktop applications even in this >> ever-increasing webified world. >> >> Use the right tool for the job... > > There is no reason that something being a "desktop app" means they > can't use HTTP instead of reinventing the protocol wheel all over > again. Absolutely! Which is why I recommended setting up an httpd to serve the images... I interpreted Paul Rubin's response to say "rewrite the whole thing (client, server, everything) as a web app". Cheers! -- pkm ~ http://paulmcnett.com From stefan.behnel-n05pAM at web.de Thu Jul 26 10:06:15 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 26 Jul 2007 16:06:15 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? In-Reply-To: <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> Message-ID: <46A8AA57.4010802@web.de> Stefan Scholl wrote: > Stefan Behnel wrote: >> Stefan Scholl wrote: >>> Well, http://docs.python.org/lib/module-xml.sax.html is missing >>> the fact, that I can't use Unicode with parseString(). >>> >>> This parseString() uses cStringIO. >> Well, Python unicode is not a valid *byte* encoding for XML. >> >> lxml.etree can parse unicode, if you really want, but otherwise, you should >> maybe stick to well-formed XML. > > The XML is well-formed. Works perfect in Python 2.4 with Python > unicode and Python sax parser. The XML is *not* well-formed if you pass Python unicode instead of a byte encoded string. Read the XML spec. It would be well-formed if you added the proper XML declaration, but that is system specific (UCS-4 or UTF-16, BE or LE). So don't even try. Stefan From horpner at yahoo.com Fri Jul 6 08:31:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 06 Jul 2007 12:31:18 GMT Subject: Where is the syntax for the dict() constructor ?! References: <468D1D9D.6060002@gmail.com> <468D3445.2060408@gmail.com> <1183675552.466967.136360@i13g2000prf.googlegroups.com> Message-ID: On 2007-07-05, John Machin wrote: > On Jul 6, 5:31 am, Neil Cerutti wrote: >> >> Mostly you can use the default 'excel' dialect and be quite >> happy, since Excel is the main reason anybody still cares about >> this unecessarily hard to parse (it requires more than one >> character of lookahead for no reason except bad design) data >> format. > > One cares about this format because people create data files of > millions of rows (far exceeding the capacity of Excel (pre-2007)) in > many imaginative xSV dialects, some of which are not handled by the > Python csv module. > > I don't know what you mean by "requires more than one > character of lookahead" It's because of the silly way that quotes are quoted in quoted fields. "a,""b",c But I'm not a parsing expert by any means. -- Neil Cerutti From rustompmody at gmail.com Wed Jul 18 02:05:13 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 18 Jul 2007 11:35:13 +0530 Subject: dejagnu equivalent Message-ID: Does anyone know if a dejagnu equivalent exists for python? [Dejagnu is in tcl] From mark_s_robey at hotmail.com Fri Jul 20 01:09:13 2007 From: mark_s_robey at hotmail.com (gravey) Date: Thu, 19 Jul 2007 22:09:13 -0700 Subject: Open HTML file in IE In-Reply-To: References: <1184739605.732844.321180@m37g2000prh.googlegroups.com> Message-ID: <1184908153.349581.164580@i13g2000prf.googlegroups.com> On Jul 19, 5:59 am, brad wrote: > gravey wrote: > > Hello. > > > Apologies if this is a basic question, but I want to open a HTML > > file from my local drive (is generated by another Python script) > > in Internet Explorer. I've had a look at the webbrowser module and > > this doesn't seem to be what I need. Any help much appreciated. > > You may try something like this example: > > import time > import win32com.client > > wie = win32com.client.Dispatch('InternetExplorer.Application') > > # Make IE Window Visible. > wie.Visible = 1 > > # Open this URL > wie.Navigate('www.your_url.com') > > # Print 'Busy' while Busy. > while wie.Busy: > print 'Busy' > > # Sleep 2 secs, then go home. > time.sleep(2) > wie.GoHome() > > # Sleep 2 secs, then go back. > time.sleep(2) > wie.GoBack() > > # Refresh the page > time.sleep(2) > wie.Refresh() > > # Close IE Window > time.sleep(2) > wie.Quit() Thanks to all who replied. All your approaches work but (!!) the HTML page that I want to open contains Javascript that parses some parameters from the URL. The URL looks like this: file:///C|/Temp/Google%20Maps/linktothis.htm?lat=45.0&lng=-20.0&zoom=4&type=k The Javascript gets the URL from the Javascript location object and parses it. I'm assuming that the location object has some kind of Windows equivalent that might be set using win32com.client. Can anyone shed any light on this? Thanks From thn at mail.utexas.edu Wed Jul 11 13:28:52 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: Wed, 11 Jul 2007 10:28:52 -0700 Subject: condor_compiled python interpreter Message-ID: <1184174932.530506.13300@r34g2000hsd.googlegroups.com> Does anyone know where I could find help on condor_compiling a python interpreter? My own attempts have failed, and I can't find anything on google. Here's the condor page: http://www.cs.wisc.edu/condor/ Thanks, Tom From arkanes at gmail.com Wed Jul 11 11:20:08 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 11 Jul 2007 10:20:08 -0500 Subject: Should I use Python for these programs? In-Reply-To: References: <1395v33mpci3p5c@corp.supernews.com> <5fh8s2F3crmfnU1@mid.individual.net> Message-ID: <4866bea60707110820n4edbf492r656d6c8f2f3d5981@mail.gmail.com> On 7/10/07, CC wrote: > Bjoern Schliessmann wrote: > > Grant Edwards wrote: > > > >>Most of the graphics I do with Python is with Gnuplot (not > >>really appropriate for what you want to do. > >>wxWidgets/Floatcanvas might be worth looking into. > > > > Agreed (I'm quite sure you mean wxPython though). Also, in "wxPython > > in Action" (the official book) a simple drawing app is constructed. > > It could help to start from there. > > Ooh, that's interesting. > > The programming contractor at work who does all our DAQ stuff also uses > wxPython so it's looking like I should use that since I can get lots of > help. > > Since the book was written, wxPython has grown a vector graphics system that might be more suitable for your needs. Look at the wxGraphicsContext class. From tenax.raccoon at gmail.com Tue Jul 24 11:32:26 2007 From: tenax.raccoon at gmail.com (Jason) Date: Tue, 24 Jul 2007 08:32:26 -0700 Subject: Closures / Blocks in Python In-Reply-To: <1185289112.771239.200260@n60g2000hse.googlegroups.com> References: <1185289112.771239.200260@n60g2000hse.googlegroups.com> Message-ID: <1185291146.753573.280420@n60g2000hse.googlegroups.com> On Jul 24, 8:58 am, treble54 wrote: > Does anyone know a way to use closures or blocks in python like those > used in Ruby? Particularly those used in the { } braces. Python isn't Ruby. Python has a lambda function for creating anonymous functions, but many of the common use cases expired with the introduction of iterators and comprehensions. Python's functions are first class objects, and can be passed around, bound to names, and used like any other object. (I don't know whether Ruby's functions are first class objects.) Python's function objects are callable, but so are classes (calling them creates a class instance) and some instances (those that define the __call__ special method). If you can't find a way of doing what you want with iterators, comprehensions, or lambda, consider writing a little function. Heck, you can even nest functions in Python or pass a function as a parameter. For example, removing all names that start with a 'J' from a list of names: newListOfNames = [ name for name in nameList if not name.startswith('J') ] # List comprehension newListOfNames = filter(lambda name: not name.startswith('J'), nameList) # Filter with lambda # Explicit for-loop newListOfNames = [] for name in nameList: if not name.startswith('J'): newListOfNames.append(name) Take a look at "http://ivan.truemesh.com/archives/000392.html" for a comparison between some simple Ruby code and Python. Hope this helps. --Jason From rdm at rcblue.com Fri Jul 27 19:27:57 2007 From: rdm at rcblue.com (Dick Moores) Date: Fri, 27 Jul 2007 16:27:57 -0700 Subject: OOP in Python book? In-Reply-To: <1185550866.950455.61240@g12g2000prg.googlegroups.com> References: <1185550866.950455.61240@g12g2000prg.googlegroups.com> Message-ID: <20070727232820.7CEAD1E400A@bag.python.org> At 08:41 AM 7/27/2007, Bill wrote: >Does anyone out there have any information about this book. It's >listed on Amazon to be published in November of this year. A simple >Google search (1st page only) doesn't show anything useful, and I >can't find a reference on the web sites of the authors. Neither of the >authors appears to be heavily into OOP theory, just some CS areas that >I don't understand. > >I'm particularly interested in why this book is worth the $100 tag >that Amazon shows. Well, the publisher is Prentice Hall, "The world's leading educational publisher". Textbooks are typically expensive. Here's the Amazon link: Dick Moores From marduk at nbk.hopto.org Mon Jul 16 17:31:19 2007 From: marduk at nbk.hopto.org (marduk) Date: Mon, 16 Jul 2007 16:31:19 -0500 Subject: Break up list into groups In-Reply-To: <1184620307.340479.253430@z28g2000prd.googlegroups.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> Message-ID: <1184621479.15828.23.camel@blackwidow.nbk> On Mon, 2007-07-16 at 14:11 -0700, danmcleran at yahoo.com wrote: > I can't seem to find an answer to this question anywhere, but I'm > still looking. My problem is I have a list of values like this: > > l = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, > 13, 0xF0, 14, 0xF1, 15] > > A value with bit 0x80 set delineates the start of a new packet of > information. What I want to do is to group the packets so that 1, 2, 3 > go with the 1st packet tagged 0xF0, 4 ,5, 6 go with the 2nd packet > tagged 0xF0, 7 & 8 go with the packet tagged 0xF1 and so on. The > length of the data associated with each tag can vary. I've already > written an algorithm to do this but I was wondering if some > combination of itertools functions could do the job faster? > > Here's what I've done and the expected output of the algorithm: > > def splitIntoGroups(data): > groups = [] > local = [] > > for value in data: > if 0x80 & value: > if len(local) > 0: > groups.append(local) > > local = [] > local.append(value) > else: > local.append(value) > > if len(local) > 0: > groups.append(local) > > return groups > > l = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, > 13, 0xF0, 14, 0xF1, 15] > > print splitIntoGroups(l) > > Desired result: > > [[240, 1, 2, 3], [240, 4, 5, 6], [241, 7, 8], [242, 9, 10, 11, 12, > 13], [240, 14], [241, 15]] Assuming you meant '0xF0' instead of '0x80'.... do you mean any value >=240 starts a new group? If so: groups = [] current = [] # probably not necessary, but as a safety for i in l: if i >= 240: current = [] groups.append(current) current.append(i) From __peter__ at web.de Wed Jul 11 10:34:27 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 11 Jul 2007 16:34:27 +0200 Subject: bool behavior in Python 3000? References: <7xodijdd8r.fsf@ruckus.brouhaha.com> Message-ID: Steven D'Aprano wrote: > How could Python cast objects to bool before bool > existed? Time machine? Sorry, I couldn't resist. Peter From nitte.sudhir at gmail.com Thu Jul 5 03:48:11 2007 From: nitte.sudhir at gmail.com (kath) Date: Thu, 05 Jul 2007 07:48:11 -0000 Subject: [True] results 'b' But how? In-Reply-To: References: <1183618481.636297.96080@e9g2000prf.googlegroups.com> Message-ID: <1183621691.761230.138600@i13g2000prf.googlegroups.com> Hi Kelvie and RBH, Thanks for your quick reply. That was very much helpful indeed. regards, kath. From this at is.invalid Wed Jul 18 02:46:23 2007 From: this at is.invalid (ddtl) Date: Wed, 18 Jul 2007 09:46:23 +0300 Subject: Interpreting non-ascii characters. References: <469d42e6@news.eftel.com.au> Message-ID: On Wed, 18 Jul 2007 08:29:58 +1000, John Machin wrote: > ... I have a bunch of directories and files from different systems (each directory contains files from the same system) which are encoded differently (though all of them are in Russian), so the following encodings are present: koi8-r, win-1251, utf-8 etc., and I want to transliterate them into a regular ASCII so that they would be readable regardless of the system. Personally I use both Linux and Windows. So what I do, is read file name using os.listdir, convert to list ('foo.txt' => ['f', 'o', ... , 't'], except that file names are in Russian), transliterate (some letters in Russian have to be transliterated into 2 or even 3 Latin letters), and then rename file. It seems though that after all I solved the problem - I thought that my Windows (2000) used win-1251 and Linux used koi8-r and because of that I couldn't understand what are those strange codes I got while experimenting with locally created Cyrillic file names, but in effect Linux uses utf-8, and Windows uses cp866, so after getting it and reading the article you suggested I solved the problem. Thanks. From hniksic at xemacs.org Thu Jul 5 03:50:41 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 05 Jul 2007 09:50:41 +0200 Subject: Memory leak issue with complex data structure References: Message-ID: <87d4z78f1q.fsf@mulj.homelinux.net> Alan Franzoni writes: > I have a serious "leak" issue; even though I clear all those sets > and I delete all the references I can have to the current namespace, > memory is not freed. Maybe the memory is freed (marked as available for further use by Python), just not released to the operating system.[1] To test against that, try to allocate more Python structures and see if they reuse the freed memory or if they allocate even more memory. Even better, run code like this: while 1: ... populate your data structures ... clear() If this causes Python to allocate more and more memory, it means you have a real leak. If not, it means that the GC is working fine, but it's not possible to release the memory to the OS. [1] Not giving freed memory back to the system is not (necessarily) a Python bug; the same thing happens in C and is a consequence of managed memory being assigned to the process as a contiguous block. From http Mon Jul 16 04:03:30 2007 From: http (Paul Rubin) Date: 16 Jul 2007 01:03:30 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <468565a0$0$3686$426a74cc@news.free.fr> <7xvecumrte.fsf@ruckus.brouhaha.com> <1i13w96.kyyobph71qxrN%aleax@mac.com> <7xwsx63we6.fsf@ruckus.brouhaha.com> <878x9llv5x.fsf@benfinney.id.au> <5fovr8F3eglkfU1@mid.uni-berlin.de> Message-ID: <7x1wf8kc6l.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > For example, SPARK does not support dynamic allocation of memory so > things such as pointers and heap variables are not supported. Right, Spark uses a profile intended for embedded systems, so no unpredictable gc delays etc. > Which is not to say that trivial code couldn't have errors, and if > it's extremely cruical code, it's important that it hasn't errors. But > all I can see is that you can create trustable, simple sub-systems in > such a language. And by building upon them, you can ensure that at > least these won't fail. Yes, that's the usual approach. > But to stick with the example: if the path-planning of the UAV that > involves tracking a not before-known number of enemy aircrafts steers > the UAV into the ground, no proven-not-to-fail radius calculation will > help you. Whether the program uses dynamic memory allocation or not, there either has to be some maximum number of targets that it can be required to track, or else it's subject to out-of-memory errors. If a maximum number is specified, then memory requirements can be computed from that. From sturlamolden at yahoo.no Tue Jul 31 15:53:05 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Tue, 31 Jul 2007 12:53:05 -0700 Subject: Why no maintained wrapper to Win32? In-Reply-To: References: <46ab694e$0$17577$9b622d9e@news.freenet.de> <59kna3p8r0cu2gk6hs5lbig8cjj8klatju@4ax.com> <1185762820.496821.298530@19g2000hsx.googlegroups.com> <1185770944.301464.85060@b79g2000hse.googlegroups.com> Message-ID: <1185911585.744934.92040@d55g2000hsg.googlegroups.com> On Jul 31, 4:35 am, Gilles Ganault wrote: > Because I'd like to avoid having to pack several MB + having to > install the toolkit. Considering the size of the typical Python > script, it seemed overkill. But you are happy to pack a Python runtime and PyWin32? This is really a dumb argument. > >Sure, you could use ctypes to make calls into user32.dll, gdi32.dll > >and kernel32.dll. Then you can program Python GUIs using the plain > >Win32 API, avoiding PyWin32's MFC or wxPython. But who would do such a > >thing? > So the PyWin32 interface doesn't make it easier to program Win32 GUI > apps? It's just C that looks like Python? PyWin32 wraps MFC, which is a C++ library for Windows (and Motif) GUI programming. It is not more 'native' than wxPython. MFC and wxWidgets does the same job, except that wxWidgets does it better. PyWin32 does not expose the GUI parts of the 'native' Win32 API directly. You will have to use ctypes to access that directly. > Guess I have the answer as to no one seems to write GUI apps for > Windows natively :-) wxPyhton is 'native' enough. Is uses native widgets on Windows (unlike Qt, GTK and tk). From bj_666 at gmx.net Tue Jul 31 10:29:05 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Jul 2007 14:29:05 GMT Subject: get directory and file names References: <1185891786.452267.57120@57g2000hsv.googlegroups.com> Message-ID: <5h8v9hF3j641tU2@mid.uni-berlin.de> On Tue, 31 Jul 2007 07:23:06 -0700, Alchemist wrote: > I am working with Python 2.5 on Windows XP (SP2). > > How can I traverse a folder, loop through a list of files and get > their file name and extension in an elegant, pythonic way? Take a look at the `os` and the `os.path` modules. In particular `os.listdir()`, `os.path.isfile()` and `os.path.splitext()`. Ciao, Marc 'BlackJack' Rintsch From kirk at strauser.com Fri Jul 6 11:53:05 2007 From: kirk at strauser.com (Kirk Strauser) Date: Fri, 06 Jul 2007 10:53:05 -0500 Subject: Auto-parallelizing with decorators? References: <468E601B.3020008@web.de> Message-ID: <1452m4xsdl1.ln2@news.conpoint.com> Stefan Behnel wrote: > Wouldn't that require parallelism in the interpreter first? Mind the > GIL... That may be. I'd bet though that I could whip up a native Python workalike using os.fork() that would work around GIL, at least on Unix (just because I don't know if Windows has os.fork(), having never looked for it). I know something like this wouldn't be the easiest thing to implement, but honestly, having such beautiful constructs as map() and list comprehensions available is just begging for an application like this. -- Kirk Strauser From steveo at syslang.net Wed Jul 18 18:02:23 2007 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 18 Jul 2007 18:02:23 -0400 (EDT) Subject: Question about how to use cog as a preprocessor :-( Message-ID: I have the following module: #! /usr/bin/python COG_DEBUG=1 def wrapper( dd ): if dd == 1: def dfunc( *args ): print "print ", for ii in args: print repr(ii) print "compd dfunc" return dfunc else: def nfunc( *args ): pass print "compd nfunc" return nfunc dbgprint = wrapper(COG_DEBUG) print "dbgprint = ", repr(dbgprint) dbgprint("called from def hunk") print "hello1" This does what I want, but when I use this code inside cog then the call to dbgprint doesn't do anything. Here's the input to cog: #! /usr/bin/python [[[cog import cog def wrapper( dd ): if dd == 1: def dfunc( *args ): cog.out( "print " ) for ii in args: cog.out( repr(ii) ) print print "compd dfunc" return dfunc else: def nfunc( *args ): pass print "compd nfunc" return nfunc dbgprint = wrapper(COG_DEBUG) print "dbgprint = ", repr(dbgprint) dbgprint("called from def hunk") ]]] [[[end]]] print "hello1" [[[cog dbgprint( "Hello from dbg" )]]] [[[end]]] print "Doo dis" and this is the cmdline: cog.py -D COG_DEBUG=1 -d -o d1out.py d1.py And the output is just #! /usr/bin/python import sys print "hello1" print "Doo dis" DOes anyone have any ideas? :-( -- 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 nikbaer at gmail.com Fri Jul 6 11:08:11 2007 From: nikbaer at gmail.com (nik) Date: Fri, 06 Jul 2007 15:08:11 -0000 Subject: VB frontend to Python COM backend In-Reply-To: References: <1183701494.979323.301500@d30g2000prg.googlegroups.com> Message-ID: <1183734491.781706.298910@o11g2000prd.googlegroups.com> Thank you for the lead. That is exactly what I was wishing for. Thank you, Nik From toby at tobiah.org Wed Jul 18 17:59:20 2007 From: toby at tobiah.org (Tobiah) Date: Wed, 18 Jul 2007 14:59:20 -0700 Subject: Exiting from python shell Message-ID: <469e8068$0$8912$88260bb3@free.teranews.com> For years now, I've been exiting the shell by typing 'exit\n', being chid by the shell, and then typing ^D. I can't remember a time that I typed the ^D the first time. Call me an idiot if you must, but since someone took the trouble to catch the command 'exit' in a special way, would it have been so awful to just let it be a way to exit when the shell? Thanks, Toby -- Posted via a free Usenet account from http://www.teranews.com From james.harris.1 at googlemail.com Wed Jul 4 15:10:55 2007 From: james.harris.1 at googlemail.com (James Harris) Date: Wed, 04 Jul 2007 12:10:55 -0700 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <138jml0ldeucf32@corp.supernews.com> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <138jml0ldeucf32@corp.supernews.com> Message-ID: <1183576255.668414.256990@q69g2000hsb.googlegroups.com> On 3 Jul, 06:12, Scott David Daniels wrote: ... > Inspired format: > Days since a some standard date (the TAI date may be a good such > date) expressed as fixed point 64-bit (32-bit day part, 32-bit > day-fraction part) or floating point (using Intel's double-precision, > for example, gives you 26 bits each for day and day-fraction, though > the binary point moves for particular stamps). This is close to or the same as my original suggestion. The break between days and sub-days seems to make more sense than breaking the fractional part elsewhere. It also gives a convenient point to hang datestamps on rather than just timestamps. FWIW I wonder if a 64-bit version of the above would cope with all practical time needs. With that the time would range to +/- 9000 quintillion years (18 digits) and there would be over 200 trillion ticks per second or 200 in a picosecond making, I think, each tick 5 femtoseconds. From ladynikon at gmail.com Sun Jul 8 18:33:12 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Sun, 8 Jul 2007 18:33:12 -0400 Subject: python extra In-Reply-To: <1183919191.840576.204450@n60g2000hse.googlegroups.com> References: <1183919191.840576.204450@n60g2000hse.googlegroups.com> Message-ID: <59f9c5160707081533n39305cq3358d376e1f8aecb@mail.gmail.com> Nope.. not a one.. On 7/8/07, mensanator at aol.com wrote: > On Jul 8, 12:59?pm, Neal Becker wrote: > > Just a little python humor: > > > > http://www.amazon.com/Vitamin-Shoppe-Python-Extra-tablets/dp/B00012NJ... > > Aren't there any female Python programmers? > > -- > http://mail.python.org/mailman/listinfo/python-list > From sjmachin at lexicon.net Thu Jul 26 17:32:29 2007 From: sjmachin at lexicon.net (John Machin) Date: Thu, 26 Jul 2007 14:32:29 -0700 Subject: CSV Issue In-Reply-To: <1185484756.890736.10890@q75g2000hsh.googlegroups.com> References: <1185484756.890736.10890@q75g2000hsh.googlegroups.com> Message-ID: <1185485549.302845.3420@b79g2000hse.googlegroups.com> On Jul 27, 7:19 am, Rohan wrote: > f = open("/home/t/tp/va/e7.csv", "ab") a means Append -- you are appending the data that you expect to the EXISTING contents of the file. From deets at nospam.web.de Mon Jul 16 09:49:54 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 16 Jul 2007 15:49:54 +0200 Subject: Accessing Python variables in an extension module References: <1184553584.757696.92630@g4g2000hsf.googlegroups.com> <1i1b7zw.64m7g071sk32N%aleax@mac.com> <1184591293.938223.105800@o61g2000hsh.googlegroups.com> Message-ID: <5g1bc2F3e2digU1@mid.uni-berlin.de> MD wrote: > Hi Alex, > Thanks for your reply. It was exactly what I was looking for. Two > additional questions > 1) Is there anyway to find out which modules a variable belongs to > when I have only its name (and its not qualified with the complete > name like module.varname) No. > 2) Is there anyway to find the type of the object in C using something > like a switch statement? I was looking for something like this > switch type(object) { > STRING: "This is a string object"; > break; > INTEGER: "This is an integer object"; > break; > BOOLEAN: "This is a boolean object"; > ......... > ......... > } > I don't want to run all the C Py***_Check functions on the object. > Something like the switch statement above will lead to nice and clean > code. In python, obj.__class__.__name__ should work. I don't know what to write in C to accomplish that, but it can't be too hard. Factor it away in a function. Diez From mail at microcorp.co.za Sat Jul 14 03:43:37 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 14 Jul 2007 09:43:37 +0200 Subject: Can a low-level programmer learn OOP? References: Message-ID: <01a401c7c5ee$69b1d960$03000080@hendrik> "Aahz" wrote: > Newbie. ;-) > > (I started with BASIC in 1976.) > *grinz @ Newbie* I was writing COBOL and NEAT/3 in 1968... - Hendrik From carsten at uniqsys.com Sun Jul 8 22:42:42 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 08 Jul 2007 22:42:42 -0400 Subject: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc) In-Reply-To: <1183947480.922943.8370@o11g2000prd.googlegroups.com> References: <1183939608.088756.178320@m37g2000prh.googlegroups.com> <1183947480.922943.8370@o11g2000prd.googlegroups.com> Message-ID: <1183948962.3165.54.camel@localhost.localdomain> On Sun, 2007-07-08 at 19:18 -0700, socialanxiety at gmail.com wrote: > On Jul 8, 5:37 pm, Carsten Haese wrote: > > On Sun, 2007-07-08 at 17:06 -0700, socialanxi... at gmail.com wrote: > > > i hope someone here can help me. > > > > > basically, me and my friend have a summer project. > > > > > in this project, we need something that would basically function as a > > > blender. we know we'll need to buy a motor that spins, but what we're > > > having trouble with is figuring out how to program it. we want to be > > > able to control the speed of the motor. how would we accomplish this? > > > > > i'm new to all of this, so i'm having a hard time wrapping my mind > > > around how it'd be possible to program one of those things :\ > > > > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then > > > turn the other direction. > > > > > would you program it the same way you would on a personal computer > > > (via c, python, etc)? > > > > The answers to your questions depend very much on what you're working > > with and how the motor is controlled. Is this supposed to be a > > self-contained machine, or is it supposed to be connected to a personal > > computer as a peripheral device? > > [...] > I would like the robot to be self contained. basically, I'd like to be > able to program functions in python, ex: > > while True: > motor.rotate(1) Good luck with that. Your best bet IMHO is to find a single-board computer (commonly referred to as SBC) that is small enough to fit your form-factor, capable of running Linux, and equipped with a suitable I/O interface (e.g. serial or parallel port). In theory, this should allow you to put Linux and Python on it and control your motor in Python as if it were a peripheral device connected to a personal computer. In practice, I've never done anything like this, and the devil is in the details that you'll need to work out for yourself. -- Carsten Haese http://informixdb.sourceforge.net From wbrehaut at mcsnet.ca Fri Jul 13 14:20:34 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Fri, 13 Jul 2007 12:20:34 -0600 Subject: 2**2**2**2**2 wrong? Bug? References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> Message-ID: On Mon, 09 Jul 2007 23:51:25 -0700, "mensanator at aol.com" wrote: >On Jul 9, 11:42?pm, Paul McGuire wrote: >> On Jul 9, 11:21 pm, "Jim Langston" wrote:> In Python 2.5 on intel, the statement >> > 2**2**2**2**2 >> > evaluates to>>> 2**2**2**2**2 >> >> > 200352993040684646497907235156025575044782547556975141926501697371089405955 63114 >> > 530895061308809333481010382343429072631818229493821188126688695063647615470 29165 >> > 041871916351587966347219442930927982084309104855990570159318959639524863372 36720 >> >> >> >> Exponentiation is right associative, so this is the same as: >> >> 2**(2**(2**(2**2))) >> 2**2**2**4 >> 2**2**16 >> 2**65536 >> >> 2=10**0.3010, so 2**65536 is approx 10**19726 >> >> There are 19730 digits in your answer, > >>>> import gmpy >>>> n = 2**2**2**2**2 >>>> gmpy.numdigits(n) >19729 > >Did you count the 'L'? numdigits(n)? What? 'L' is a digit in Python? I'm going back to Fortran! wwwayne >>so this seems to be at least in >> the ball park. >> >> -- Paul > From attn.steven.kuo at gmail.com Mon Jul 9 14:09:06 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Mon, 09 Jul 2007 11:09:06 -0700 Subject: compressing consecutive spaces In-Reply-To: <1183991894.508562.16430@g4g2000hsf.googlegroups.com> References: <1183991894.508562.16430@g4g2000hsf.googlegroups.com> Message-ID: <1184004546.833125.20310@i13g2000prf.googlegroups.com> On Jul 9, 7:38 am, Beliavsky wrote: > How can I replace multiple consecutive spaces in a file with a single > character (usually a space, but maybe a comma if converting to a CSV > file)? Ideally, the Python program would not compress consecutive > spaces inside single or double quotes. An inelegant method is to > repeatedly replace two consecutive spaces with one. One can try mx.TextTools. E.g., from mx.TextTools import * import re string_inside_quotes=re.compile(r'(?P["\']).*?(? References: <1183524527.709730.190290@q75g2000hsh.googlegroups.com> <5f30vsF3aicltU1@mid.individual.net> Message-ID: <1183647423.458469.166460@m36g2000hse.googlegroups.com> greg wrote: > sjdevnull at yahoo.com wrote: > > > wxWidgets will give you native looking apps on both Linux and Windows > > Well, maybe. There's more to getting a native feel than > just using the right widgets. I once saw a Qt-based app on > MacOSX that had tiny little buttons that were too small > for the text they contained -- Aqua buttons just don't > scale down like that. :-( wxWidgets isn't Qt-related. wx wraps the Aqua widgets on MacOS, the gtk widgets on Linux, and the Windows widgets on Windows. So you're actually using the real platform-specific widgets, and if you follow the style guidelines you'll get pretty native-looking apps (including things like the menubar showing up in the app on Linux/Windows but using the main menubar on Mac). Last I looked (3.1-ish), Qt didn't use the Aqua widgets but rather tried to write their own widgets that looked (kinda) like the MacOS widgets. I hear that may have changed in more recent versions, but I no longer have a Mac. They did do the menubar correctly even at that time, though. From eddie at holyrood.ed.ac.uk Tue Jul 17 11:29:22 2007 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Tue, 17 Jul 2007 15:29:22 +0000 (UTC) Subject: Can a low-level programmer learn OOP? References: <7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com> Message-ID: aahz at pythoncraft.com (Aahz) writes: >In article <7cqo93pona4qoc4s94hh9rjrjalniilqts at 4ax.com>, >Wolfgang Strobl wrote: >> >>SNOBOLs powerfull patterns still shine, compared to Pythons clumsy >>regular expressions. >Keep in mind that Python regular expressions are modeled on the >grep/sed/awk/Perl model so as to be familiar to any sysadmin -- but >there's a reason why Python makes it a *library* unlike Perl. So adding >SNOBOL patterns to another library would be a wonderful gift to the >Python community... I don't believe you can get the benefit of SNOBOL matching without direct language support. There's only so much a library can do. However a valiant and interesting effort: http://www.wilmott.ca/python/patternmatching.html Eddie From tleeuwenburg at gmail.com Sun Jul 8 21:42:58 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: Mon, 09 Jul 2007 01:42:58 -0000 Subject: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc) In-Reply-To: <1183939608.088756.178320@m37g2000prh.googlegroups.com> References: <1183939608.088756.178320@m37g2000prh.googlegroups.com> Message-ID: <1183945378.856202.240820@g37g2000prf.googlegroups.com> First you'll need a computer interface to your robot. Lego Mindstorm, for example, comes with ways to program the onboard CPU. Other standard robotic toolkits will also come with some kind of interface, which may or may not have Python bindings. Cheers, -T On Jul 9, 10:06 am, socialanxi... at gmail.com wrote: > i hope someone here can help me. > > basically, me and my friend have a summer project. > > in this project, we need something that would basically function as a > blender. we know we'll need to buy a motor that spins, but what we're > having trouble with is figuring out how to program it. we want to be > able to control the speed of the motor. how would we accomplish this? > > i'm new to all of this, so i'm having a hard time wrapping my mind > around how it'd be possible to program one of those things :\ > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then > turn the other direction. > > would you program it the same way you would on a personal computer > (via c, python, etc)? From raims at dot.com Tue Jul 31 05:57:09 2007 From: raims at dot.com (Lawrence Oluyede) Date: Tue, 31 Jul 2007 11:57:09 +0200 Subject: simple string backspace question References: <1185875052.153091.23300@19g2000hsx.googlegroups.com> Message-ID: <1i246fs.1wnv4yeynnakoN%raims@dot.com> wrote: > >>> text="Hello\bworld" > >>> print text > "HelloBSworld" > > Should this character "\b" (backspace) in this text return this: > "Helloworld"? 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. >>> text="Hello\bworld" >>> print text Hellworld What system are u using? -- 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 hey at mikehowarth.co.uk Fri Jul 27 11:26:39 2007 From: hey at mikehowarth.co.uk (Mike Howarth) Date: Fri, 27 Jul 2007 08:26:39 -0700 (PDT) Subject: Factory pattern again In-Reply-To: <46a9c21f$0$18765$426a74cc@news.free.fr> References: <11825158.post@talk.nabble.com> <46a9c21f$0$18765$426a74cc@news.free.fr> Message-ID: <11831500.post@talk.nabble.com> Having overcome my first hurdle with the factory pattern, I've now hit another stumbling block At the moment I'm trying to return around 2000 records from a db and load up the relevant product object, what I've found is this is running extremely slowly (> 20mins), the db is normalized and indexes exist. Can anyone advise on how best I could speed this up? def getWebRangeProducts(self): if self.c.connected: cu = self.c.cursor #create the cursor sql = "SELECT type, code FROM products" cu.execute(sql) if cu.rowcount > 0: rows = cu.fetchall() for row in rows: self.loadProduct(row[0].strip(),row[1].strip()) return self.products def loadProduct(self,type,product_code): print type + ":" + product_code if type == 'I': try: product = factory('Item', product_code) self.products.append(product) except: print 'problem occured:' + type + ':' + product_code elif type == 'S': try: item_set = factory('Set', product_code) item_set.getItems() self.products.extend(item_set.getItems()) except: print 'problem occured:' + type + ':' + product_code else: pass Bruno Desthuilliers-5 wrote: > > Mike Howarth a ?crit : >> Hi >> >> I was wondering whether anyone could help me, I'm pretty new to python >> coming from a PHP background and I'm having a few products in getting my >> head round how to write the factory pattern within python. >> >> I'm currently looking to try to return values from a db and load up the >> relevant objects, values returned are product type (I,S) and product code >> (123). >> >> At the moment I've adapted some code I've found illustrating the factory >> method but ideally I would like to use the type to load up the relevant >> object. >> >> Another issue I've found is that I don't seem to be able to access to the >> price attribute of each of the object. I'm sure these are very >> straightforward issues however I seem to have tied myself in knots over >> this >> and could do with a fresh set of 'pythonic' eyes to help me out. >> >> registry = {} >> >> class MetaBase(type): >> def __init__(cls, name, bases, dict): >> registry[name] = cls >> >> class Product(object): >> __metaclass__ = MetaBase >> >> class Item(Product): >> def __init__(self, *args, **kw): >> self.price = 1 >> >> class Set(Product): >> def __init__(self, *args, **kw): >> self.price = 2 >> >> def factory(kind, *args, **kw): >> return registry[kind](*args, **kw) >> >> >> item = registry['Item'] > > This returns the Item *class*, not an instance of... So the following: > >> print item.price > > cannot work, since price is an instance attribute, not a class attribute. > > What you want is: > > item = factory('Item') > print item.price > > HTH > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Factory-pattern-again-tf4156186.html#a11831500 Sent from the Python - python-list mailing list archive at Nabble.com. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 27 08:36:13 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 27 Jul 2007 14:36:13 +0200 Subject: Filtering content of a text file In-Reply-To: <5gu70dF3i0lfsU3@mid.uni-berlin.de> References: <1185528507.750436.91140@j4g2000prf.googlegroups.com> <46a9c5a5$0$9208$426a34cc@news.free.fr> <5gu70dF3i0lfsU3@mid.uni-berlin.de> Message-ID: <46a9e6a4$0$16759$426a34cc@news.free.fr> Marc 'BlackJack' Rintsch a ?crit : > On Fri, 27 Jul 2007 12:15:25 +0200, Bruno Desthuilliers wrote: > >> 4/ print "//-+alibaba sinage"[4:].startswith('a') > > print "//-+alibaba sinage".startswith('a', 4) > > This does not create an extra string from the slicing. One learns everyday... Thanks Marc. From vedrandekovic at v-programs.com Fri Jul 27 11:23:13 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Fri, 27 Jul 2007 08:23:13 -0700 Subject: a simple string question Message-ID: <1185549793.114644.62170@k79g2000hse.googlegroups.com> Hello, I have one question about string.I am trying to make an function to analyze line of some text, this is my example: "HELLO;HELLO2:WORLD:", if that function in this text find ";" and ":" ( in this example will find both) e.g that function must return this: "HELLO;\nHELLO2:\n\t\t\t\t\t\t\tWORLD:" Regards, Vedran From openopt at ukr.net Sun Jul 1 05:38:53 2007 From: openopt at ukr.net (dmitrey) Date: Sun, 01 Jul 2007 02:38:53 -0700 Subject: howto resend args and kwargs to other func? In-Reply-To: References: <1183279997.244378.105810@n60g2000hse.googlegroups.com> <1183280667.542964.175570@u2g2000hsc.googlegroups.com> Message-ID: <1183282733.179683.174350@c77g2000hse.googlegroups.com> Thanks all, I have solved the problem. D. From arkanes at gmail.com Fri Jul 27 12:02:07 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 27 Jul 2007 11:02:07 -0500 Subject: zip() function troubles In-Reply-To: <7xfy3ae4lb.fsf@ruckus.brouhaha.com> References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> <7xfy3ae4lb.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60707270902r3cf36f7akd772575cf9051c94@mail.gmail.com> On 26 Jul 2007 23:35:44 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Peter Otten <__peter__ at web.de> writes: > > When you are allocating a lot of objects without releasing them the garbage > > collector kicks in to look for cycles. Try switching it off: > > I think that is the answer. The zip took almost 2 minutes without > turning gc off, but takes 1.25 seconds with gc off. It turned a > linear-time algorithm into a quadratic one. I think something is > broken about a design where that can happen. Maybe Pypy will have > a generational GC someday. > -- 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. 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. > http://mail.python.org/mailman/listinfo/python-list > From sebzzz at gmail.com Sun Jul 15 23:01:01 2007 From: sebzzz at gmail.com (sebzzz at gmail.com) Date: Mon, 16 Jul 2007 03:01:01 -0000 Subject: Right tool and method to strip off html files (python, sed, awk?) In-Reply-To: <4698B377.8040306@web.de> References: <1184353058.660535.140110@m3g2000hsh.googlegroups.com> <4698B377.8040306@web.de> Message-ID: <1184554861.361090.129970@g4g2000hsf.googlegroups.com> Thank you guys for all the good advice. All be working on defining a clearer problem (I think this advice is good for all areas of life). I appreciate the help, the python community looks really open to learners and beginners, hope to be helping people myself in not too long from now (well, reasonably long to learn the theory and mature with it of course) ;-) From timid.Gentoo at gmail.com Thu Jul 5 15:42:33 2007 From: timid.Gentoo at gmail.com (_spitFIRE) Date: Thu, 05 Jul 2007 19:42:33 -0000 Subject: SMTP server w/o using Twisted framework In-Reply-To: References: <1183659790.338100.199900@g4g2000hsf.googlegroups.com> <1183661809.613856.312100@57g2000hsv.googlegroups.com> Message-ID: <1183664553.892218.225170@n60g2000hse.googlegroups.com> On Jul 5, 2:37 pm, "Jeff McNeil" wrote: > You could try pyDNS (http://pydns.sourceforge.net). You should simply > be able to call the 'DNS.mxlookup' function. The other option would > be twisted.names... > Thanks for the pointers. > What about simply running an SMTP server on the machine running your > application? Is that a possible approach? > I guess that would be my last resort :) > Not that I know of. The protocol is standard, the queuing and retry > logic, not so much. Someone else may know more than I, though. > I understand what you are saying. I guess, I would fall back to my last option! > http://mtamark.space.net/draft-stumpf-dns-mtamark-04.htmlhttp://en.wikipedia.org/wiki/Sender_Policy_Framework > > > -- > >http://mail.python.org/mailman/listinfo/python-list Thanks, once again. From jeff at jmcneil.net Wed Jul 25 19:53:06 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 25 Jul 2007 19:53:06 -0400 Subject: first, second, etc line of text file In-Reply-To: <46A7D0F5.8090609@jayloden.com> References: <5f56302b0707251244p24080f1ct87a5f459cb175dae@mail.gmail.com> <13afdpp7a6t24c5@corp.supernews.com> <1185396840.702955.31890@l70g2000hse.googlegroups.com> <13aff82d1v7ge0f@corp.supernews.com> <46A7D0F5.8090609@jayloden.com> Message-ID: <82d28c40707251653t7f546d8bre52d160289065ac7@mail.gmail.com> Yup, I actually had log files in mind, too. I process Apache logs from an 8-way cluster every 15 minutes. There are 32,000 sites on said cluster; that's a lot of log data! I didn't actually think anyone would go *try* to open("war_and_peace.txt").readlines().. I just meant it as a generalization for "really large file." =) -Jeff On 7/25/07, Jay Loden wrote: > > Grant Edwards wrote: > > On 2007-07-25, Jeff wrote: > > > >> That might be a memory problem if you are running multiple processes > >> regularly, such as on a webserver. > > > > I suppose if you did it in parallel 50 processes, you could use > > up 250MB of RAM. Still not a big deal on many servers. A > > decent OS will swap regions that aren't being used to disk, so > > it's likely not to be a problem. > > Or, you might be reading from a text file dramatically larger than a 3MB > copy of War and Peace. I regularly deal with log files that are often many > times that, including some that have been well over a GB or more. Trust me, > you don't want to read in the entire file when it's a 1.5GB text file. > It's true that many times readlines() will work fine, but there are also > certainly cases where it's not acceptable for memory and performance > reasons. > > -Jay > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Thu Jul 5 04:17:59 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 05 Jul 2007 08:17:59 -0000 Subject: MethodType/FunctionType and decorators In-Reply-To: <1i0qoq9.u1fu2g63fkmxN%aleax@mac.com> References: <1183589529.198694.109440@m36g2000hse.googlegroups.com> <1183591053.434640.119550@o61g2000hsh.googlegroups.com> <1i0qoq9.u1fu2g63fkmxN%aleax@mac.com> Message-ID: <1183623479.913816.301230@g4g2000hsf.googlegroups.com> On Jul 5, 3:41 am, a... at mac.com (Alex Martelli) wrote: > Alex already explained everything beautifully. I will just add a link to the definite guide to descriptors: http://users.rcn.com/python/download/Descriptor.htm Michele Simionato (who spent lot of brain cycles studying descriptors *before* that guide was written :-() From thenault at gmail.com Fri Jul 13 05:34:30 2007 From: thenault at gmail.com (syt) Date: Fri, 13 Jul 2007 09:34:30 -0000 Subject: patching pylint.el In-Reply-To: <86ps3164xd.fsf@localhost.my.domain.i-did-not-set--mail-host-address--so-tickle-me> References: <86ps3164xd.fsf@localhost.my.domain.i-did-not-set--mail-host-address--so-tickle-me> Message-ID: <1184319270.442107.315920@57g2000hsv.googlegroups.com> On Jul 9, 4:13 pm, lgfang wrote: > Hi, > > I think this is a bug ofpylint.el. But I failed finding a way to > submit the bug neither in its official site nor in google. So I post > it here wishing it may be useful for some buddies. > > The bug is that it uses "compile-internal" from "compile" without > require compile. So "M-xpylint" will fail if compile hadn't been > loaded in advance by any means. > > My fix is rather straightforward: add "(require 'compile)" in the code. > > ------ begin diff output ------ > 2a3> (require 'compile) > > ------ end diff output ------ fyi, pylint related bug should be reported on the python- projects at logilab.org mailing list. I've opened a ticket for your bug/patch: http://www.logilab.org/bug/eid/4026 cheers, Sylvain From duncan.booth at invalid.invalid Tue Jul 24 04:53:01 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Jul 2007 08:53:01 GMT Subject: Hacking with __new__ References: <1185241394.990936.206360@k79g2000hse.googlegroups.com> Message-ID: Sandra-24 wrote: > So thinking myself clever with python I thought I could change > S3ResponseError to have a __new__ method which returns one of the 30 > new exceptions. That way none of the raise S3ResponseError code needs > changing. No problem. The trouble comes with those exceptions being > subclasses of S3ResponseError, because __new__ is called again and > goofs everything up. I think what you want for Bar is something more along the lines: class Foo(object): def __new__(cls, *args): print 'Foo.__new__', len(args) return super(Foo, cls).__new__(cls, *args) def __init__(self, a, b, c): print 'Foo.__init__', 3 self.a = a self.b = b self.c = c class Bar(Foo): def __new__(cls, a, b, c, *args): print 'Bar.__new__', len(args) target = cls if not args: cls = Zoo obj = super(Bar, cls).__new__(cls, a, b, c, *args) if args: return obj obj.__init__(a, b, c, 7) class Zoo(Bar): def __init__(self, a, b, c, d): print 'Zoo.__init__', 4 Foo.__init__(self, a, b, c) self.d = d Bar(1,2,3) Output from this is: Bar.__new__ 0 Foo.__new__ 3 Zoo.__init__ 4 Foo.__init__ 3 Bar can instantiate a subclass, but to do that it wants to call the constructor __new__ only for the base classes, and because it has changed the type of the object being constructed it has to call __init__ explicitly. From exarkun at divmod.com Fri Jul 20 18:45:11 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 20 Jul 2007 18:45:11 -0400 Subject: Sorting dict keys In-Reply-To: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> Message-ID: <20070720224511.4947.478439525.divmod.quotient.13939@ohm> On Fri, 20 Jul 2007 15:27:51 -0700, montyphyton at gmail.com wrote: >Consider the following: >>>> a = {1:2, 3:4, 2:5} > >Say that i want to get the keys of a, sorted. First thing I tried: > >>>> b = a.keys().sort() >>>> print b >None > >Doesn't work. Probably because I am actually trying to sort the keys >of the dictionary without copying them first. If that is the case, >fine. Next thing I do: > >>>> b = a.keys() >>>> b.sort() >[1, 2, 3] This is a mis-observation. b.sort() does /not/ return [1, 2, 3]. b.sort() returns None. The sort method of the list type performs an in-place sort and always returns None. With that in mind, the rest of your code snippets might make more sense. I'll leave it to you to figure out how to jam everything into one line (or, more realistically, another poster in about 2 seconds, I'm sure), since I don't really see the value in that exercise myself. Jean-Paul From deets at nospam.web.de Fri Jul 6 16:06:14 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 06 Jul 2007 22:06:14 +0200 Subject: C++ Modules for python: How to? In-Reply-To: <1183750094.154566.248170@m36g2000hse.googlegroups.com> References: <1183750094.154566.248170@m36g2000hse.googlegroups.com> Message-ID: <5f7llqF3bfvstU1@mid.uni-berlin.de> Robert Dailey schrieb: > Hi, > > I'm interested in making a C++ library of mine usable through python. > Python does a similar thing with Expat (the non-validating XML > parser). I notice that with Expat, python is importing a C++ header > file into a PY file and the interface is available to python. I've > read through the python documentation as well as done a little bit of > google research and I've not been able to find a tutorial of some sort > on how to do this. Perhaps I just don't know the right words to search > for. > > If anyone could lead me in the right direction (possibly an article, > tutorial, etc) I would greatly appreciate it. The best thing to do is to offer your C++-lib with a C-style interface. Then you can use python's ctypes (included since python2.5) to access the shared library. If you insist on using C++, you can expose the lib using several available wrapper generators. I know of three: SIP, Swig & Boost::Python. The first I've got some very good first-hand experience. The second is somewhat primitive IHMO. The third I never used. Use these to google in this group, you'll find plenty of stuff. Diez From millerdev at gmail.com Mon Jul 16 17:30:32 2007 From: millerdev at gmail.com (Daniel) Date: Mon, 16 Jul 2007 21:30:32 -0000 Subject: Dynamic method In-Reply-To: <469b80bb$0$23769$426a34cc@news.free.fr> References: <46939ba9$0$32159$426a74cc@news.free.fr> <46949c19$0$23164$426a34cc@news.free.fr> <1i1clx6.1qpf4ykihdj1oN%raims@dot.com> <469b80bb$0$23769$426a34cc@news.free.fr> Message-ID: <1184621432.556914.238840@o61g2000hsh.googlegroups.com> Bruno Desthuilliers wrote: > > > Another way is to use the 'types' module: > > True - and that's somewhat cleaner since it doesn't expose the internals > of the descriptor protocol. OTHO, it can lead to strange results with > callables not implementing the descriptor protocol: Actually, the result is not "strange" at all if you understand what's going. The reason you got an exception is because your __call__() method only takes a single argument (the implicit self argument, which is the instance of MyCallable). However, if you define it with two arguments it works just fine: >>> class MyCallable(object): ... def __call__(self, inst): ... print self, inst ... >>> class Foo(object): ... pass ... >>> fun = MyCallable() >>> f = Foo() >>> f.fun = types.MethodType(fun, f, Foo) >>> f.fun() <__main__.MyCallable object at 0x648d0> <__main__.Foo object at 0x64810> >>> ~ Daniel From apardon at forel.vub.ac.be Fri Jul 13 05:16:27 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jul 2007 09:16:27 GMT Subject: Fast powerset function References: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> Message-ID: On 7/12/07, Arash Arfaee wrote: > I need a powerset generator function. It's really slow with recursion. Does > anybody have any idea or code(!!) to do it in an acceptable time? > Thanks My idea would be the following. 1) Turn your set into a list: lst 2) let lng be the number of elements. 3) let n range from 0 to 2 ** lng 4) now n represents subset as follows consider n as a binary number bit k is set in n <=> lst[k] is a member of the subset. -- Antoon Pardon From deets at nospam.web.de Wed Jul 25 09:04:55 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 25 Jul 2007 15:04:55 +0200 Subject: 16-bit colour representation References: <1185364424.797757.84620@22g2000hsm.googlegroups.com> Message-ID: <5gp03nF3hl7siU1@mid.uni-berlin.de> beertje wrote: > This has me a bit stumped... > > I'm trying to extract pictures from a file. So far I'm successfully > retrieved the header and what I think is the colour for each pixel. > Here's the description: > > """ > 3) The picture data format: > The color information is 15 bit data stored in 16 bit. This means the > most > significant bit is unused. The data is stored line for line in little > endian Intel format starting with top left edge to bottom right edge. > This > is normally called chunky format. > > Bit 0.. 4 blue value > Bit 5.. 9 green value > Bit 10..14 red value > """ > > So I've got a list of 16-bit numbers, but how to extract RGB info from > those I'm a bit lost. I thought at first I should convert the decimal > (say 23294) into a binary (say 0101101011111110) into something like > this: > blue: 01011 > green: 01011 > red: 11111 > > But encountered two problems: First, I don't know what the best way is > to do this conversion, but more importantly I don't see how every > colour could possibly be represented like this. 65535 is presumably > white, but converting this into chunks of 5 gives me a 31, 31, 31, a > dark shade of grey. > > I guess I'm on the wrong track completely? > > I'm a bit unsure about how to treat what the guide calls 'UWORD'... ANDing and SHIFTing are your friends here: v = 0x0bcd b = v & 0xf v >>= 4 g = v & 0xf v >>= 4 r = v & 0xf print r, g, b Diez From ahlongxp at gmail.com Mon Jul 9 05:16:11 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Mon, 09 Jul 2007 09:16:11 -0000 Subject: socket: connection reset by server before client gets response In-Reply-To: <1183969844.697022.298650@w3g2000hsg.googlegroups.com> References: <1183819907.249945.239700@o11g2000prd.googlegroups.com> <1183900086.021428.83580@e9g2000prf.googlegroups.com> <1183969844.697022.298650@w3g2000hsg.googlegroups.com> Message-ID: <1183972571.875740.13930@z28g2000prd.googlegroups.com> On Jul 9, 4:30 pm, Adriano Varoli Piazza wrote: > > Gives a whole new meaning to chomp(), byte, nybble, and more :) > I wholeheartedly endorse this effort. I'm sick of reading about > students from WTF University (check thedailywtf.com if you don't know, > but beware. There be dragons). > > -- > Adriano > Once bitten, one arm less to code snafus with. I feel officially offended. From gagsl-py2 at yahoo.com.ar Tue Jul 24 20:47:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Jul 2007 21:47:51 -0300 Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> Message-ID: En Tue, 24 Jul 2007 11:10:53 -0300, Stargaming escribi?: > On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote: > >> There are various things I like about the D language that I think Python >> too may enjoy. Here are few bits (mostly syntactical ones): >> >> 1) (we have discussed part of this in the past) You can put underscores >> inside number literals, like 1_000_000, the compiler doesn't enforce the >> position of such underscores, so you can also put them like this: >> 1_00_000. You can put them in literals of decimals, binary, hex, etc. I > > Sounds like a good thing to be but the arbitrary positioning doesnt make > any sense. Additionally, I'd suggest 10**n in such cases (eg. 10**6). Why not? Because in English major numbers are labeled in thousands? (thousand, million, billion...) In India, they're grouped by two after the first thousand; in China, they're grouped each 4 digits (that is, there is a single word for "ten thousands" = wan4 = ?, and the next required word is for 10**8 = yi4 = ?) -- Gabriel Genellina From stefan.behnel-n05pAM at web.de Sat Jul 28 13:49:08 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 28 Jul 2007 19:49:08 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? In-Reply-To: <0T49iehiIt1hNv8%stesch@parsec.no-spoon.de> References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> <0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de> <0T49iehiIt1hNv8%stesch@parsec.no-spoon.de> Message-ID: <46AB8194.2060906@web.de> Stefan Scholl wrote: > Chris Mellon wrote: >> On 7/26/07, Stefan Scholl wrote: >>> Chris Mellon wrote: >>>> XML is not a string. It's a specific type of bytestream. If you want >>>> to work with XML, then generate well-formed XML in the correct >>>> encoding. There's no reason you should have an XML document (as >>>> opposed to values extracted from that document) in unicode objects at >>>> all. >>> The affected method in xml.sax is called parseString() >> The imprecision of the english language has caused greater problems >> than this. Since you've now had everything clarified for you, and the >> imprecision is resolved, I'm sure that this won't be a problem again. > > > Right. I now know that xml.sax's parseString() has undocumented > implementation dependent behavior. That there are libraries (not > included with Python) which can parse Unicode strings. And that > the reason to change cStringIO's behavior is acceptable. > > But the style of the answers makes me wonder if I should report > the bug in xml.sax (or its documentation) or just ignore it. Note that PyXML is no longer actively maintained, so it's unlikely that reporting the bug would get you a version that raises an exception when passing a unicode string *independent of the Python version*. Besides, the bug has been fixed in Python 2.5 already. Stefan From mshiltonj at gmail.com Sun Jul 8 14:21:41 2007 From: mshiltonj at gmail.com (mshiltonj) Date: Sun, 08 Jul 2007 18:21:41 -0000 Subject: In search of python idiom for accessing arbitrary fields at run time Message-ID: <1183918901.388300.220620@o61g2000hsh.googlegroups.com> I'm trying to find the preferred python idiom for access arbitrary fields of objects at run time. For example, say I have an object the business code will do *something* with three arbitrary fields at a given time, but I don't know what the three fields are at run time. In perl, I'd do something like this: sub three_fields{ my $self = shift; my @fields = @_; foreach my $field (@fields) { my $value = $self->$field; # this is the one I'm interested in [...] } } In python, I'm doing something like this: def three_fields(self, field1, field2, field3): for field in (field1, field2, field3): value = eval('self.' + field) # this is the one I'm interested in [...] This seems to do what I expect it to do. I'm wondering if that's the preferred or standard way to do this in python. I wasn't sure how to tease the answer to this question out of Google. Thanks. From stesch at no-spoon.de Thu Jul 26 04:28:00 2007 From: stesch at no-spoon.de (Stefan Scholl) Date: Thu, 26 Jul 2007 10:28:00 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? Message-ID: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> After an hour searching for a potential bug in XML parsing (PyXML), after updating from 2.4 to 2.5, I found this one: $ python2.5 Python 2.5 (release25-maint, Dec 9 2006, 14:35:53) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import StringIO >>> x = StringIO.StringIO(u"m\xf6p") >>> import cStringIO >>> x = cStringIO.StringIO(u"m\xf6p") Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128) >>> $ python Python 2.4.4 (#2, Apr 5 2007, 20:11:18) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import StringIO >>> x = StringIO.StringIO(u"m\xf6p") >>> import cStringIO >>> x = cStringIO.StringIO(u"m\xf6p") >>> OK, that's why my code was fine with Python 2.4 and breaks with 2.5. {sigh} -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From hari.siri74 at gmail.com Tue Jul 10 23:40:06 2007 From: hari.siri74 at gmail.com (hari.siri74 at gmail.com) Date: Wed, 11 Jul 2007 03:40:06 -0000 Subject: pattern match ! Message-ID: <1184125206.034047.175340@n60g2000hse.googlegroups.com> Extract the application name with version from an RPM string like hpsmh-1.1.1.2-0-RHEL3-Linux.RPM, i require to extract hpsmh-1.1.1.2-0 from above string. Sometimes the RPM string may be hpsmh-1.1.1.2-RHEL3- Linux.RPM. From tokauf at web.de Tue Jul 3 06:36:06 2007 From: tokauf at web.de (TK) Date: Tue, 03 Jul 2007 12:36:06 +0200 Subject: newbie-question Message-ID: <468a2607$0$14903$9b622d9e@news.freenet.de> Hi, how can I implement a socket timeout? Thanx for help. o-o THomas From kimiraikkonen85 at gmail.com Mon Jul 2 13:50:45 2007 From: kimiraikkonen85 at gmail.com (kimiraikkonen) Date: Mon, 02 Jul 2007 10:50:45 -0700 Subject: The best platform and editor for Python In-Reply-To: <1183380558.135204.83790@e16g2000pri.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> Message-ID: <1183398645.511107.258700@n2g2000hse.googlegroups.com> Thanks for the replies so far. Also i have to learn: What is the most reliable and easy way to start learning Ptyhon? Books? Trusted code sammples(where?)? I know the importance and eases of Python quiet. Thanks. From ladaan at iptel.org Tue Jul 24 05:58:47 2007 From: ladaan at iptel.org (Ladislav Andel) Date: Tue, 24 Jul 2007 11:58:47 +0200 Subject: display image through cgi python html Message-ID: <46A5CD57.1010406@iptel.org> Hi, I'm trying to display image through my cgi script in HTML page via Can you give me an example, please? What should be in the cgi script to display it? Here is what I have in image.cgi but it is incorrect and i'm not able to find it on the web. #!/usr/bin/python print "Content-Type: image/png\n" print 'image.png' thanks, Lada From bj_666 at gmx.net Fri Jul 27 02:59:26 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jul 2007 06:59:26 GMT Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> <0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de> Message-ID: <5gtjeeF3i0lfsU2@mid.uni-berlin.de> On Fri, 27 Jul 2007 06:47:48 +0200, Stefan Scholl wrote: > Chris Mellon wrote: >> XML is not a string. It's a specific type of bytestream. If you want >> to work with XML, then generate well-formed XML in the correct >> encoding. There's no reason you should have an XML document (as >> opposed to values extracted from that document) in unicode objects at >> all. > > The affected method in xml.sax is called parseString() Exactly. It's *not* called `parseUnicode()`. In Python you have the types `str` which is a bunch of bytes and `unicode` which is a character string that can hold unicode characters. How those are internally represented is an implementation detail. You shouldn't know or depend on the internal representation, other modules like XML parsers shouldn't do either. XML, the serialized form, is about bytes in some encoding. So this can only be stored in `str` objects. `unicode` is already decoded. If you want to feed `unicode` objects to an XML parser, simply encode it before passing it. The question remains why you have "serialized XML" as `unicode` in the first place as it is about bytes not unicode characters. Ciao, Marc 'BlackJack' Rintsch From jmoy.matecon at gmail.com Thu Jul 5 17:40:17 2007 From: jmoy.matecon at gmail.com (Jyotirmoy Bhattacharya) Date: Thu, 05 Jul 2007 21:40:17 -0000 Subject: Extracting arbitrary amounts of data from a dictionary. In-Reply-To: <1183670496.169639.287310@n2g2000hse.googlegroups.com> References: <1183663916.635440.185720@e9g2000prf.googlegroups.com> <1183670496.169639.287310@n2g2000hse.googlegroups.com> Message-ID: <1183671617.744541.31110@w5g2000hsg.googlegroups.com> On Jul 6, 2:21 am, Jyotirmoy Bhattacharya wrote: > On Jul 6, 12:31 am, robinsieb... at gmail.com wrote: > > > > > I had nothing better to do, so I thought I would make a database that > > contained the songs played on the internet radio station I listen to > > (hardradio.com) so I could see how many differents songs/artists they > > played. > > So I end up with a the number of times any given song by a given > > artist is played in a day. Want I want to do is to be able to print > > out a report for X number of weeks and I am trying to determine the > > best way to interate through the 'week' key of the dictionary. > > > For example, this is week 27, the dictonary has 6 'week' keys and I > > want the data from the last 3 weeks. Is this the best way to iterate > > through the dictionary? > > > for date in dates[year][week].keys()[-3]: > > > Or is there a better way with all the new features that have been > > added to Python? > > Here is an implementation using as many 'new' features of Python as I > could think of.http://phpfi.com/247634 A bit shortened and improved: http://phpfi.com/247642 From zacherates at gmail.com Thu Jul 19 20:31:31 2007 From: zacherates at gmail.com (zacherates) Date: Fri, 20 Jul 2007 00:31:31 -0000 Subject: How to check if an item exist in a nested list In-Reply-To: References: <266557d0707191443h36eceddoca7bb626f0e0a022@mail.gmail.com> Message-ID: <1184891491.713699.291800@q75g2000hsh.googlegroups.com> > One way is to check the length of each dimension. Does any body > know a simpler way? No need to check the length of the list: """ >>> foo = [0, 1, 2, [3, 4, 5, 6, 7, [8, 9, 10]]] >>> isInNested(0, foo) True >>> isInNested(11, foo) False >>> isInNested(3, foo) True >>> isInNested(8, foo) True """ def isInNested(k, l): try: if k in l: return True for i in l: if isInNested(k, i): return True except TypeError: #l is not iterable pass return False if __name__ == "__main__": import doctest doctest.testmod() From http Fri Jul 13 05:25:59 2007 From: http (Paul Rubin) Date: 13 Jul 2007 02:25:59 -0700 Subject: Fast powerset function References: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> Message-ID: <7xodigr6xk.fsf@ruckus.brouhaha.com> Antoon Pardon writes: > On 7/12/07, Arash Arfaee wrote: > > I need a powerset generator function. It's really slow with recursion. Does > > anybody have any idea or code(!!) to do it in an acceptable time? > My idea would be the following. ... > 3) let n range from 0 to 2 ** lng That may help a little but my guess is the slowness comes from the size (2**n) of the power set. From nick at craig-wood.com Wed Jul 4 05:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 04 Jul 2007 04:30:04 -0500 Subject: what is wrong with that r"\" References: Message-ID: Neil Cerutti wrote: > From the Python Language Reference 2.4.1 String Literals: > > When an "r" or "R" prefix is present, a character following a > backslash is included in the string without change, and all > backslashes are left in the string. For example, the string > literal r"\n" consists of two characters: a backslash and a > lowercase "n". So far so good. > String quotes can be escaped with a backslash, > but the backslash remains in the string; for example, r"\"" is > a valid string literal consisting of two characters: a > backslash and a double quote; a) That is weird! Why would you ever want to do that - ie insert \" into your string as a special case? If I wanted a " in a raw string then I'd use a r'' string or a triple quoted string. > r"\" is not a valid string literal (even a raw string cannot end > in an odd number of backslashes). Specifically, a raw string > cannot end in a single backslash (since the backslash would > escape the following quote character). b) That is a logical consequence of a) > Note also that a single backslash followed by a newline is > interpreted as those two characters as part of the string, not > as a line continuation. As I'd expect. If we removed a) then we could remove b) also and r"" strings would work as everyone expects. Does anyone know the justification for a)? Maybe we should remove it in py3k? -- Nick Craig-Wood -- http://www.craig-wood.com/nick From martin at v.loewis.de Sun Jul 1 08:28:57 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 01 Jul 2007 14:28:57 +0200 Subject: Python app as a Display Manager In-Reply-To: References: Message-ID: <46879e09$0$22529$9b622d9e@news.freenet.de> > I feel at this stage that what I miss is: assuming I manage to get a > python-based dialog box started automatically from init.rc (instead of xdm, > gdm, ...): how do I start an X11 session with the user/pw information > retrieved ... + set the correct *nix environment variables. First, the user will enter username and password into your dialog box. You need to verify this, either by using the pwd module, or by using PAM (through python-pam). Then you need start a session. Fork a subprocess, and use setuid/setgid to take the identity of the subprocess. In the parent process, wait for this child process to terminate, then display your dialog again (perhaps restarting the X server in-between). What you do in your session is your own choice. It is custom to set a few environment variables, and then run /etc/X11/Xsession (or whereever the standard X11 session script lives); the latter is done through exec, i.e. when Xsession returns, the user has chosen to logout. This is the basic working principle; different display managers deviate in how precisely they setup the session, and what precisely they run in what order. However, this entire discussion is off-topic for comp.lang.python; please ask on comp.windows.x instead. HTH, Martin From danb_83 at yahoo.com Sat Jul 21 02:05:10 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Fri, 20 Jul 2007 23:05:10 -0700 Subject: Permutations with generators In-Reply-To: <1184996537.069416.211730@g4g2000hsf.googlegroups.com> References: <1184996537.069416.211730@g4g2000hsf.googlegroups.com> Message-ID: <1184997910.266858.4550@e9g2000prf.googlegroups.com> On Jul 21, 12:42 am, Pablo Torres wrote: > Hey guys! > For the last couple of days, I've been fighting a war against > generators and they've beaten the crap out of me several times. What I > want to do is implement one that yields every possible permutation of > a given sequence (I had lists in mind, but I could swear that this > would work on strings too...if it worked at all). > > Here's what I have so far: > > def perm(seq): > "Reshuffles the elements of seq in every possible way" > if len(seq) == 1: > yield seq > else: > for p in perm(seq[1:]): > for i in range(len(seq)): > yield p.insert(i, seq[0]) > > Basically, I let the recursion reshuffle the elements of the > subsequence that starts from the second element of the original one, > and then I insert seq[0], the first element of the original sequence, > in every position of the shuffled sublist. > > Here's what I get when I try to list the permutations of [1, 2, 3, 4] > (print list(perm([1, 2, 3, 4]))): > > Traceback (most recent call last): > File "perm.py", line 15, in > print list(perm([1, 2, 3, 4])) > File "perm.py", line 11, in perm > for p in perm(seq[1:]): > File "perm.py", line 13, in perm > yield p.insert(i, seq[0]) > AttributeError: 'NoneType' object has no attribute 'insert' > > Could somebody please explain to me why my p variable has no type at > all? > For every call to perm(seq), seq should always be of the same type as > the sequence that was used in the first call. Any ideas as to where > seq loses it's type? list.insert returns None. Thus, except in the one-element case, your generator is yielding None all the time. Try this: def permutations(seq): if len(seq) == 1: yield seq else: for i, x in enumerate(seq): for perm in permutations(seq[:i] + seq[i+1:]): yield [x] + perm From tim.arnold at sas.com Thu Jul 26 15:16:50 2007 From: tim.arnold at sas.com (Tim Arnold) Date: Thu, 26 Jul 2007 15:16:50 -0400 Subject: encode/decode misunderstanding Message-ID: Hi, I'm beginning to understand the encode/decode string methods, but I'd like confirmation that I'm still thinking in the right direction: I have a file of latin1 encoded text. Let's say I put one line of that file into a string variable 'tocline', as follows: tocline = 'Ficha Datos de p\xe9rdida AND acci\xf3n' import codecs tocFile = codecs.open('mytoc.htm','wb',encoding='utf8',errors='replace') tocline = tocline.decode('latin1','replace') tocFile.write(tocline) tocFile.close() What I think is that tocFile is wrapped to insure that anything written to it is in utf8 I decode the latin1 string into python's internal unicode encoding and that gets written out as utf8. Questions: what exactly is the tocline when it's read in with that \xe9 and \xed in the string? A latin1 encoded string? Is my method the right way to write such a line out to a file with utf8 encoding? If I read in the latin1 file using codecs.open(filename,encoding='latin1') and write out the utf8 file by opening with codecs.open(othername,encoding='utf8'), would I no longer have a problem -- I could just read in latin1 and write out utf8 with no more worries about encoding? thanks, --Tim From tednospam at sbcglobal.net Mon Jul 16 00:28:17 2007 From: tednospam at sbcglobal.net (news.sf.sbcglobal.net) Date: Sun, 15 Jul 2007 21:28:17 -0700 Subject: BeautifulSoup prettify help Message-ID: <_tCmi.10652$rL1.10124@newssvr19.news.prodigy.net> Hi, Is there a way to make the prettify() use 4 spaces instead of 1 for each level of indentation? Or maybe make it use tabs instead? TIA, TEd From roy at panix.com Wed Jul 4 21:56:38 2007 From: roy at panix.com (Roy Smith) Date: Wed, 04 Jul 2007 21:56:38 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> Message-ID: In article , John Nagle wrote: > Non-enforced static typing requires a quality assurance group that > reads code and checks coding standards. In other words, it's enforced, but it's enforced by QA people instead of the compiler. From apardon at forel.vub.ac.be Fri Jul 13 04:30:24 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Jul 2007 08:30:24 GMT Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: On 2007-07-13, Hendrik van Rooyen wrote: > "Donn Cave" wrote: > >>In its day, goto was of course very well loved. > > Does anybody know for sure if it is in fact possible to > design a language completely free from conditional jumps? I think you have to be more clear on what you mean. I would consider a while loop as a conditional jump but I have the impression you don't. Is that correct? > At the lower level, I don't think you can get away with > conditional calls - hence the "jumps with dark glasses", > continue and break. Would you consider raise as belonging in this collection? > I don't think you can get that functionality in another way. > > Think of solving the problem of reading a text file to find > the first occurrence of some given string - can it be done > without either break or continue? (given that you have to > stop when you have found it) It depend on what the language offers. Should PEP 325 be implemented the code would look something like: do: line = fl.readline() while st not in line: pass -- Antoon Pardon From andre.roberge at gmail.com Tue Jul 24 08:26:15 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Tue, 24 Jul 2007 12:26:15 -0000 Subject: Parsing XML with ElementTree (unicode problem?) In-Reply-To: <1185200976.082516.105420@57g2000hsv.googlegroups.com> References: <1185200976.082516.105420@57g2000hsv.googlegroups.com> Message-ID: <1185279975.254458.7510@57g2000hsv.googlegroups.com> On Jul 23, 11:29 am, oren.t... at gmail.com wrote: > (this question was also posted in the devshed python forum:http://forums.devshed.com/python-programming-11/parsing-xml-with-elem... > ). > ----------------------------- > > (it's a bit longish but I hope I give all the information) > > 1. here is my problem: I'm trying to parse an XML file (saved locally) > using elementtree.parse but I get the following error: > xml.parsers.expat.ExpatError: not well-formed (invalid token): line > 13, column 327 > apparently, the problem is caused by the token 'Sauni?re' due to the > apostrophe. > > the thing is that I'm sure that python (ElementTree module and parse() > function) can handle this type of encoding since I obtain my xml file > from the web by opening it with: > > from elementtree import ElementTree > from urllib import urlopen > query = r'http://ecs.amazonaws.com/onca/xml? > Service=AWSECommerceService&AWSAccessKeyId=189P5TE3VP7N9MN0G302&Operation=ItemLookup&ItemId=1400079179&ResponseGroup=Reviews&ReviewPage=166' > root = ElementTree.parse(urlopen(query)) > How about trying root = ElementTree.parse(urlopen(query), encoding ='utf-8') Andr? From orsenthil at users.sourceforge.net Wed Jul 4 10:36:41 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Wed, 4 Jul 2007 20:06:41 +0530 Subject: using subprocess for non-terminating command In-Reply-To: <1183550943.531211.306410@n60g2000hse.googlegroups.com> References: <1183549118.773813.132940@r34g2000hsd.googlegroups.com> <1183550943.531211.306410@n60g2000hse.googlegroups.com> Message-ID: <20070704143641.GA3434@gmail.com> * zacherates [2007-07-04 12:09:03]: > > How should I handle these kind of commands (ping 127.0.0.1) with > > subprocess module. I am using subprocess, instead of os.system because > > at anypoint in time, I need access to stdout and stderr of execution. > > Ping, for one, allows you to set an upper bound on how long it runs > (the -c option). This is probably the cleanest approach if it's > available. > Yes, I am aware of the ping -c option. But again even that does not help. try process = subprocess.Popen('ping -c 10 127.0.0.1', stdin=subprocess.PIPE, shell=True) process.stdout.read() # This will hang again. I am not sure, why subprocess is behaving so. > You can also send the subprocess signals if you need it to exit > (although, this is a unix thing so I'm not sure how portable it is). Yes, I have tried to kill and then get the standard output result. But the result has been the same. I could not read the Popen returned file object. > You could emulate having a timeout on child.stdout.read by registering > a callback with Timer to kill the child. I dont know how to do this. I shall give it a try ( by looking around ) and trying. -- O.R.Senthil Kumaran http://uthcode.sarovar.org From len-l at telus.net Thu Jul 5 20:52:30 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Fri, 06 Jul 2007 00:52:30 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <1183659478.231468.229590@57g2000hsv.googlegroups.com> References: <9uRhi.17027$xk5.14289@edtnps82> <1183659478.231468.229590@57g2000hsv.googlegroups.com> Message-ID: Falcolas wrote: >> f = some_file() #maybe it's the file store for a database implementation >> f.write('a bunch of stuff') >> del f >> #insert code that assumes f is closed. >> >> This is the sort of code that I warn against writing. >> >> f = some_file() >> with f: >> f.write("a bunch of stuff") >> #insert code that assumes f is closed, but correctly this time >> >> is better. > > This has raised a few questions in my mind. So, here's my newbie > question based off this. > > Is this: > > f = open(xyz) > f.write("wheee") > f.close() > # Assume file is closed properly. > This will not immediately close f if f.write raises an exception since the program stack is kept alive as a traceback. > as "safe" as your code: > > f = some_file() > with f: > f.write("a bunch of stuff") > #insert code that assumes f is closed, but correctly this time > The with statement is designed to be safer. It contains an implicit try/finally that lets the file close itself in case of an exception. -- Lenard Lindstrom From rcdailey at gmail.com Fri Jul 13 15:10:32 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 13 Jul 2007 19:10:32 -0000 Subject: Pass by reference or by value? Message-ID: <1184353832.314694.228270@n60g2000hse.googlegroups.com> Hi, I noticed in Python all function parameters seem to be passed by reference. This means that when I modify the value of a variable of a function, the value of the variable externally from the function is also modified. Sometimes I wish to work with "copies", in that when I pass in an integer variable into a function, I want the function to be modifying a COPY, not the reference. Is this possible? Thanks. From steve at holdenweb.com Wed Jul 11 21:14:14 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 11 Jul 2007 21:14:14 -0400 Subject: Best architecture for proxy? In-Reply-To: <1184162418.341166.160580@n60g2000hse.googlegroups.com> References: <1184076639.815417.48390@g4g2000hsf.googlegroups.com> <5ficu5F3cram2U4@mid.individual.net> <1184162418.341166.160580@n60g2000hse.googlegroups.com> Message-ID: Andrew Warkentin wrote: > On Jul 10, 8:19 pm, Steve Holden wrote: >> Bjoern Schliessmann wrote: >>> Andrew Warkentin wrote: >>>> I am going to write a general-purpose modular proxy in Python. It >>>> will consist of a simple core and several modules for things like >>>> filtering and caching. I am not sure whether it is better to use >>>> multithreading, or to use an event-driven networking library like >>>> Twisted or Medusa/ Asyncore. Which would be the better >>>> architecture to use? >>> I'd definitely use an event-driven approach with Twisted. >>> Generally, multithreading is less performant than multiplexing. High >>> performance servers mostly use a combination of both, though. >> Converselt I'd recommend Medusa - not necessarily because it's "better", >> but becuase I know it better. There's also a nice general-purpose proxy >> program (though I'd be surprised if Twisted didn't also have one). >> >> > Would an event-driven proxy be able to handle multiple connections > with large numbers of possibly CPU-bound filters? I use The > Proxomitron (and would like to write my own proxy that can use the > same filter sets, but follows the Unix philosophy) and some of the > filters appear to be CPU-bound, because they cause The Proxomitron to > hog the CPU (although that might just be a Proxomitron design flaw or > something). Wouldn't CPU-bound filters only allow one connection to be > filtered at a time? On the Medusa site, it said that an event-driven > architecture only works for I/O-bound programs. > Well since Medusa doesn't thread or fork you are correct, it's likely that connection requests could be rejected if the response processors take a significant amount of real and CPU 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 gwill at wirelesstcp.net Sat Jul 21 11:11:02 2007 From: gwill at wirelesstcp.net (george williams) Date: Sat, 21 Jul 2007 08:11:02 -0700 Subject: [ANN] Python documentation team looking for members! References: Message-ID: <000901c7cba9$5a5945a0$c9b6d5cf@george644090dd> Take me off mailing list thank you george ----- Original Message ----- From: "Georg Brandl" Newsgroups: comp.lang.python.announce To: Sent: Saturday, July 21, 2007 4:10 AM Subject: [ANN] Python documentation team looking for members! > Dear fellow Pythonistas, > > as you may have heard, Python is going to get a new documentation system > soon [1]. As part of that effort, and in order to maintain the excellent > quality of the docs, we are looking for members of the maintainers team. > This is your chance to get involved with Python development! > > There will be two main objectives of the group, or maybe two subgroups can > be formed: > > * Maintaining the documentation contents: > - processing user submitted comments, bugs and patches > - helping out developers with docs-related matters, keeping an eye > on commits to ensure quality > - keeping the docs up-to-date, e.g. write new sections for new > Python 3000 features > > The docs source will be in reStructuredText, which is already known to > a > relatively high percentage of Python developers. > > The new online version of the docs will contain features to add > comments > and suggest changes, so it is expected that there will be some amount > of user involvement. > > > * Development of the toolset: > - fixing bugs in the package > - adding new output formats, e.g. info or pdf > - adding new features to the web application > - adapting it to new docutils features > > The software is written in pure Python. It is currently located in the > docutils Subversion repository, at > http://svn.berlios.de/viewcvs/docutils/trunk/sandbox/py-rest-doc/ > > The README file gives you a rough idea what you find there and how to > get started, all other questions can be directed to georg at python.org, > I'll answer them gladly. > > > An additional objective in the near future will, of course, be handling > the > switch to the new system. > > Okay, so you've read until here? And you're interested in joining the > team? > Wow! Write to the docs at python.org and become a documentation maintainer! > > cheers, > Georg > > > [1] see http://pyside.blogspot.com/2007/06/introducing-py-rest-doc.html > for some details, and http://pydoc.gbrandl.de:3000/ [2] for a demo. > (Commenting doesn't work yet, but it's worked upon fiercely...) > > [2] the demo server is a small vserver with the application served by a > single wsgiref instance, and as such not fit to handle large amounts > of requests, so it may well be that you don't get good reponse times. > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations.html > From fperez.net at gmail.com Tue Jul 31 15:23:30 2007 From: fperez.net at gmail.com (Fernando Perez) Date: Tue, 31 Jul 2007 13:23:30 -0600 Subject: Plotting Images References: <508774.60673.qm@web72009.mail.tp2.yahoo.com> Message-ID: Pei-Yu CHAO wrote: > Hi ALL: > > I have only been switched from matlab to python few > months ago. I having trouble of plotting images from a > matrix size of 8x10000 (unfortunately that is the size > of my data.....) > > for example, > x = rand(8,10000) > inshow(x) > Read the docstrings, they explain how to use the function: imshow(x,aspect=300) gives a reasonable size to look at such a thin matrix, after you widen the window a fair bit. Cheers, f From ratchetgrid at googlemail.com Sat Jul 7 14:47:12 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Sat, 7 Jul 2007 19:47:12 +0100 Subject: Creating logged functions using decorators Message-ID: <676224240707071147n743f5a20w891772aea269f934@mail.gmail.com> Hi, I m thinking about writing some code which logs the input and output of a function/script and stores it in a database using sqlalchemy (although I havent started on this yet). I want to do this via a decorator ( I think this is the best way ). def log(fn): def newfn(*args): print datetime.date.today() print __file__ print fn.__name__ print args return fn(*args) return newfn @log def doAnalysis(a, b): print a, b return a + b doAnalysis(3, 7) I can access the arguments passed to the "logged" function, but is there anyway I can capture the output of the function i.e. 10. Many Thanks in advance, Nathan From martin at v.loewis.de Sun Jul 1 16:14:18 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 01 Jul 2007 22:14:18 +0200 Subject: unicode In-Reply-To: <1183318859.305908.218960@w5g2000hsg.googlegroups.com> References: <1183267580.178435.265640@o61g2000hsh.googlegroups.com> <1183318859.305908.218960@w5g2000hsg.googlegroups.com> Message-ID: <46880b1a$0$22417$9b622d9e@news.freenet.de> > 1) If you print a unicode string: > > *print implicitly calls str()* No. print does nothing if the object is already a string or unicode object, and calls str() only otherwise. > a) str() calls encode(), and encode() tries to convert the unicode > string to a regular string. encode() uses the default encoding, which > is ascii. If encode() can't convert a character, then encode() raises > an exception. Yes and no. This is what str() does, but str() isn't called. Instead, print inspects sys.stdout.encoding, and uses that encoding to encode the string. That, in turn, may raise an exception (in particular if sys.stdout.encoding is "ascii" or not set). > b) repr() calls encode(), but if encode() raises an exception for a > character, repr() catches the exception and skips over the character > leaving the character unchanged. No. repr() never calls encode. Instead, each type, including unicode, may have its own __repr__ which is called. unicode.__repr__ escapes all non-ASCII characters. > 2) If you print a regular string containing characters in unicode > syntax: No. There is no such thing: py> len("\u") 2 py> "\u"[0] '\\' py> "\u"[1] 'u' In a regular string, \u has no meaning, so \ stands just for itself. > a) str() calls encode(), but if encode() raises an exception for a > character, str() catches the exception and skips over the character > leaving the character unchanged. Same as 1b. No. Printing a string never invokes .encode(), and no exception occurs at all. Instead, the \ just gets printed as is. > b) repr() similar to a), but repr() then escapes the escapes in the > string. str.__repr__ escapes the backslash just in case, so that it won't have to check for the next character; in that sense, it generates a normal form. > 3) If you print a regular string containing characters in utf-8 > syntax: > > a) str() outputs the string to your terminal, and if your terminal can > convert the utf-8 numerical codes to characters it does so. Correct. In general, you should always use the terminal's encoding when printing to the terminal. That way, you can print everything just fine what the terminal can display, and get an exception if you try to print something that the terminal would be unable to display. > b) repr() blocks your terminal from interpreting the characters by > escaping the escapes in your string. Why don't I see two slashes like > in the output for 2b? str.__repr__ produces an output that is legal Python syntax for a string literal. len(u'\u9999'.encode('utf-8')) is 3, so this Chinese character really encodes as three separate bytes. As these are non-ASCII bytes, __repr__ choses a representation that is legal Python syntax. For that characters, only \xe9, \xa6 and \x99 are valid Python syntax (each representing a single byte). For a backslash, Python could have generated \x5c or \134 as well, which are all different spellings of "backslash in a string literal". Python chose the most legible one, which is the double-backslash. HTH, Martin From mmara at fibertel.com.ar Wed Jul 4 15:27:34 2007 From: mmara at fibertel.com.ar (Mariano Mara) Date: Wed, 04 Jul 2007 16:27:34 -0300 Subject: Help search files In-Reply-To: References: Message-ID: <468BF4A6.4030307@fibertel.com.ar> Alejandro Decchi escribi?: > Hello Someone can help me how to search file in a directory. I need to > do a form where the user write the word to search and if the file was > found the user must could download the file making click in the link > Sorry my english > thz > Alex > You could try os.walk (search for "walk" here: http://docs.python.org/lib/os-file-dir.html) and then loop the results to find the file (sure there are some out of the box methods for this but right now I don't know any). One thing I'm not sure if you want to search for a word within the file or if the submitted word matches the name of the file. My suggestion should work for the last option. Good luck. From tjreedy at udel.edu Tue Jul 3 19:45:40 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 3 Jul 2007 19:45:40 -0400 Subject: object references/memory access References: <1183247524.662884.153830@n60g2000hse.googlegroups.com><4687c63b$0$22513$9b622d9e@news.freenet.de><7xfy48871j.fsf@ruckus.brouhaha.com><4687cf4b$0$24940$9b622d9e@news.freenet.de><7xfy48f486.fsf@ruckus.brouhaha.com><1183318690.661279.256900@n2g2000hse.googlegroups.com><1183407411.397142.304790@e16g2000pri.googlegroups.com><1183417108.245203.158830@x35g2000prf.googlegroups.com><4689e535$0$23896$9b622d9e@news.freenet.de><1183488824.131448.62720@x35g2000prf.googlegroups.com><468ac0b1$0$9090$9b622d9e@news.freenet.de> <1183501376.537918.154340@i38g2000prf.googlegroups.com> Message-ID: "Karthik Gurusamy" wrote in message news:1183501376.537918.154340 at i38g2000prf.googlegroups.com... |If all you had is just two processes, P and C and the amount of data |flowing is less (say on the order of 10's of buffer-size ... e.g. 20 |times 4k), *a lot* may not be right quantifier. Have pipe buffer sizes really not been scaled up with RAM sizes? 4K on a 4M machine is sensible, but on my 1G machine, up to 1M might be ok. tjr From steve at holdenweb.com Mon Jul 2 18:01:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Jul 2007 18:01:29 -0400 Subject: object references/memory access In-Reply-To: <1183407411.397142.304790@e16g2000pri.googlegroups.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1183407411.397142.304790@e16g2000pri.googlegroups.com> Message-ID: Karthik Gurusamy wrote: > On Jul 1, 12:38 pm, dlomsak wrote: [...] > > I have found the stop-and-go between two processes on the same machine > leads to very poor throughput. By stop-and-go, I mean the producer and > consumer are constantly getting on and off of the CPU since the pipe > gets full (or empty for consumer). Note that a producer can't run at > its top speed as the scheduler will pull it out since it's output pipe > got filled up. > But when both processes are in the memory of the same machine and they communicate through an in-memory buffer, what's to stop them from keeping the CPU fully-loaded (assuming they are themselves compute-bound)? > When you increased the underlying buffer, you mitigated a bit this > shuffling. And hence saw a slight increase in performance. > > My guess that you can transfer across machines at real high speed, is > because there are no process swapping as producer and consumer run on > different CPUs (machines, actually). > As a concept that's attractive, but it's easy to demonstrate that (for example) two machines will get much better throughput using the TCP-based FTP to transfer a large file than they do with the UDP-based TFTP. This is because the latter protocol requires the sending unit to stop and wait for an acknowledgment for each block transferred. With FTP, if you use a large enough TCP sliding window and have enough content, you can saturate a link as ling as its bandwidth isn't greater than your output rate. This isn't a guess ... > Since the two processes are on the same machine, try using a temporary > file for IPC. This is not as efficient as real shared memory -- but it > does avoid the IPC stop-n-go. The producer can generate the multi-mega > byte file at one go and inform the consumer. The file-systems have > gone thru' decades of performance tuning that this job is done really > efficiently. > I'm afraid this comes across a bit like superstition. Do you have any evidence this would give superior performance? > > >> Thanks for the replies so far, I really appreciate you guys >> considering my situation and helping out. > > 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 Jul 1 17:47:50 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 1 Jul 2007 14:47:50 -0700 Subject: Reversing a string References: <1182997438.541012.54100@o61g2000hsh.googlegroups.com> Message-ID: <1i0kuau.pvs4131kz0oelN%aleax@mac.com> Jay Loden wrote: ... > For what it's worth, with python 2.5 on my Macbook: Hmmm, doesn't look to me as if it's worth much...: > [jloden at macbook jloden]$ python -m timeit 's = "onomatopoeia"; s = s.join(s[::-1])' since what you're doing is...: >>> s = "onomatopoeia" >>> s = s.join(s[::-1]) >>> s 'aonomatopoeiaionomatopoeiaeonomatopoeiaoonomatopoeiaponomatopoeiaoonoma topoeiatonomatopoeiaaonomatopoeiamonomatopoeiaoonomatopoeianonomatopoeia o' >>> ...which isn't really just reversing the string, but quite a bit more work!-) Alex From vasudevram at gmail.com Mon Jul 16 13:25:39 2007 From: vasudevram at gmail.com (vasudevram) Date: Mon, 16 Jul 2007 17:25:39 -0000 Subject: Technology solutions for Ruby? In-Reply-To: References: <469B059C.2050802@cesmail.net> Message-ID: <1184606739.054580.197740@g37g2000prf.googlegroups.com> [ Though the OP posted his message to comp.lang.ruby, I'm cross- posting it to comp.lang.python, since he mentions Python as a possible alternative he's looking at, and also because I've recommended Python for his stated needs. Also, interested to see what other Pythonistas have to say in response to my reply. - Vasudev] > On Jul 16, 2007, at 2:21 AM, Michael Reiland wrote: > At the heart of the issue is the fact that I refuse to use Java for this project, I prefer not to use .Net because of the portability issues, and I'd like to get away from C++ for obvious reasons. > To me this means Ruby, Python, or, as mentioned above, Perl. If anyone can tell me of a way to meet the above requirements in either Python or Perl, I'm all ears (I just prefer Ruby). Yes, I think it would be really great for the Ruby community and for the growth of the language if wxRuby was more mature as a GUI toolkit. (Not knocking the wxRuby developers at all, its great that they've even done what they have - I know that creating other language (like Ruby) bindings to a C++ lib is a non-trivial task). My suggestion: Python + wxPython + Python DBI + (Py2Exe + InnoSetup) *might* meet all your needs. (As with any decision about what software technologies to use, you'll have to evaluate the suggested options to see if they fit your needs.) Note: I've used and like both Ruby and Python (saying this after using many, though not all, language features and libraries of both languages), and am not trying to discourage you from using Ruby for your needs; its just that, based on your needs as described, it looks to me as if Python meets them better than Ruby at present: > 1. GUI - Native Look and Feel. According to wxRuby the bindings aren't mature enough for production use. Does anyone have any experience with this and/or can you offer alternatives that provide a native look and feel (I I don't know enough about wxRuby to comment. wxPython has this (Native Look and Feel), I think (used it some, a while ago), not 100% sure, you can check on the site - http:/ www.wxpython.org - to make sure. The site does say that it is cross-platform: "wxPython is a cross-platform toolkit. This means that the same program will run on multiple platforms without modification. Currently supported platforms are 32-bit Microsoft Windows, most Unix or unix- like systems, and Macintosh OS X. " but that doesn't necessarily mean that it will have native look and feel on all supported platforms. (The two are not the same thing.) That's why you will need to check. wxPython pros: Its fairly easy to learn, at least for simple GUI apps (e.g. a few widgets / controls and a file dialog or two). I was able to build these simple ones - see the code, article and screenshots available here (or from links from here): http://www.packtpub.com/article/Using_xtopdf - in quite a short time, starting from zero knowledge of wxPython (I did know some Python from before), just by looking at the sample apps, and some reading of the docs. See the quotes about wxPython: http://www.wxpython.org/quotes.php >2. Databases - contemplating using ActiveRecord, but I would like to use ODBC to support multiple types of DB's in a uniform way (if you know of alternatives to ODBC or ActiveRecord, please let me know). I think, but again, not sure, that Python DBI + appropriate database drivers, may meet this need. Basically Python DBI is similar to ODBC (roughly), and to Perl DBI + DBD, as I understand. There's also ODBC support in the Win32 extensions package for Python - IIRC, Google for 'win32all' to get it. Its also available as a link from the Python for Win32 MSI installer on python.org. I've used Python ODBC some, it works and is easy to use. See this for a simple example: http://jugad.livejournal.com/2006/07/07/ (See the second post at that page, titled "Publishing ODBC database content as PDF ". The code shown in the post is not indented as per proper the Python syntax (LiveJournal messed up the indentation), sorry about that, but its trivial to correct if you know Python indenting rules). Also read the Python ODBC docs and examples, of course. >3. Binary - Are there any utilities for compiling Ruby into a binary executable? The issue is twofold, speed, and not handing the customer the source :) For Python, there is py2exe (for Windows only). I used py2exe recently and it works well enough for the simple cases that I tried. (I tried building EXEs for a simple Python hello-world program, and for a simple wxPython GUI app based on my xtopdf toolkit. Both worked ok.) For cross-platform (Windows and Linux, IIRC), there is PyInstaller (Google for it), haven't tried it out yet, just downloaded it recently. I don't think you'll gain much speed by this compiling step, though (over and above what Python gives you itself, when it compiles your .py files to .pyc files). The purpose of py2exe is more to hide the source code than to speed it up, as I understand (could be wrong). Note: py2exe only creates an EXE and DLLs needed, from your source and its required Python modules. To create an installer, try InnoSetup (for Windows only). I recently tried it out, version 5, again, it worked well. Could create Windows SETUP.EXE-type installers for the two EXEs described above. Worked ok. I first learned Python, have been using it for some time for various projects, and then learned Ruby, and have done some projects with Ruby too. I've been reading both the Ruby Cookbook and the Python Cookbook rather thoroughly in the last few weeks (and trying out and modifying many of the recipes), and what I've observed is that the two languages are roughly similar in features. For basic features common to most languages (constants, variables, arrays, hashes/dictionaries, file I/ O, classes, objects, modules/libraries, etc. - they work roughly in the same fashion - though syntax obviously differs, you can mostly do what you can in one of them, in the other as well. (Note that I'm not talking about libraries here - this will obviously differ as each language will have its own set of libraries for doing various tasks, like networking and other areas - though even here there is a good amount of overlap/similarity.) For more advanced language features related to object-orientation, metaclasses / metaprogramming, both have some support, but you might or might not be able to do in one, what you can do in the other. HTH Vasudev Ram Site: http://www.dancingbison.com PDF toolkit (in Python): http://sourceforge.net/projects/xtopdf Blog: http://jugad.livejournal.com From wojciech_mula at poczta.null.onet.pl.invalid Wed Jul 4 16:13:06 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?iso-8859-2?Q?Mu=B3a?=) Date: Wed, 4 Jul 2007 20:13:06 +0000 (UTC) Subject: Tkinter toggle a Label Widget based on checkbutton value References: Message-ID: O.R.Senthil Kumaran wrote: > Any suggestions on how can i make this checkbutton effect. > 1) Press Enable IP, the Label IP should be shown. > 2) Toggle Enable IP (So that its unset). the Label IP should not be shown. > > #!/usr/bin/python > from Tkinter import * > root = Tk() > root.title('something') > x = StringVar() ip = Label(root,text="IP:") > def display(): global ip > if x.get(): > #ip = Label(root,text="IP:") > ip.grid(row=3,column=0) else: ip.grid_forget() From tedpottel at gmail.com Mon Jul 2 19:02:46 2007 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Mon, 02 Jul 2007 16:02:46 -0700 Subject: How to FTP a ASCII file Message-ID: <1183417366.036607.233910@n60g2000hse.googlegroups.com> Hi, My program has the following code to transfer a binary file f = open(pathanme+filename,'rb') print "start transfer" self.fthHandle.storbinary('STOR '+filename, f) How can I do an ASCII file transfer?????? -Ted From jm.suresh at gmail.com Mon Jul 2 08:35:45 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: Mon, 02 Jul 2007 05:35:45 -0700 Subject: freeze: standard modules unknown Message-ID: <1183379745.981284.67770@e16g2000pri.googlegroups.com> I am trying to use freeze to create a single binary executable for one of my program. When I run freeze, it runs fine with the following modules. These modules are available in the dyn-load directory and I can import them from the python interpreter. Warning: unknown modules remain: _bisect _heapq _locale _random _socket Make also runs fine, but when I run the program on another machine, it compiles saying could not import these modules. Any idea how to get this working... Thanks. - Suresh From deets at nospam.web.de Wed Jul 25 12:18:57 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 25 Jul 2007 18:18:57 +0200 Subject: Flatten a list/tuple and Call a function with tuples References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> Message-ID: <5gpbfhF3gj6fdU1@mid.uni-berlin.de> beginner wrote: > On Jul 25, 10:19 am, Stargaming wrote: >> On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote: >> > Hi, >> >> > I am wondering how do I 'flatten' a list or a tuple? For example, I'd >> > like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4]. >> >> A recursive function, always yielding the first element of the list, >> could do the job. See the ASPN Python Cookbook for a few >> implementations.http://aspn.activestate.com/ASPN/search? >> query=flatten§ion=PYTHONCKBK&type=Subsection >> >> > Another question is how do I pass a tuple or list of all the aurgements >> > of a function to the function. For example, I have all the arguments of >> > a function in a tuple a=(1,2,3). Then I want to pass each item in the >> > tuple to a function f so that I make a function call f(1,2,3). In perl >> > it is a given, but in python, I haven't figured out a way to do it. >> > (Maybe apply? but it is deprecated?) >> >>> def foo(a, b, c): print a, b, c >> ... >> >>> t = (1, 2, 3) >> >>> foo(*t) >> >> 1 2 3 >> >> Have a look at the official tutorial, 4.7.4http://www.python.org/doc/ >> current/tut/node6.html#SECTION006740000000000000000 >> >> > Thanks, >> > cg >> >> HTH, >> Stargaming > > Hi Stargaming, > > I know the * operator. However, a 'partial unpack' does not seem to > work. > > def g(): > return (1,2) > > def f(a,b,c): > return a+b+c > > f(*g(),10) will return an error. > > Do you know how to get that to work? f(*(g() + (10,)) Not the most beautiful solution, but it works. Diez From hniksic at xemacs.org Thu Jul 12 08:32:18 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 12 Jul 2007 14:32:18 +0200 Subject: os.wait() losing child? References: <4694903B.8000105@cosc.canterbury.ac.nz> Message-ID: <87bqehg5v1.fsf@mulj.homelinux.net> Jason Zheng writes: > greg wrote: >> Jason Zheng wrote: >>> Hate to reply to my own thread, but this is the working program >>> that can demonstrate what I posted earlier: >> I've figured out what's going on. The Popen class has a >> __del__ method which does a non-blocking wait of its own. >> So you need to keep the Popen instance for each subprocess >> alive until your wait call has cleaned it up. >> The following version seems to work okay. >> > It still doesn't work on my machine. I took a closer look at the Popen > class, and I think the problem is that the __init__ method always > calls a method _cleanup, which polls every existing Popen > instance. Actually, it's not that bad. _cleanup only polls the instances that are no longer referenced by user code, but still running. If you hang on to Popen instances, they won't be added to _active, and __init__ won't reap them (_active is only populated from Popen.__del__). This version is a trivial modification of your code to that effect. Does it work for you? #!/usr/bin/python import os from subprocess import Popen pids = {} counts = [0,0,0] for i in xrange(3): p = Popen('sleep 1', shell=True, cwd='/home', stdout=file(os.devnull,'w')) pids[p.pid] = p, i print "Starting child process %d (%d)" % (i,p.pid) while (True): pid, ignored = os.wait() try: p, i = pids[pid] except KeyError: # not one of ours continue del pids[pid] counts[i] += 1 #terminate if count>10 if (counts[i]==10): print "Child Process %d terminated." % i if reduce(lambda x,y: x and (y>=10), counts): break continue print "Child Process %d terminated, restarting" % i p = Popen('sleep 1', shell=True, cwd='/home', stdout=file(os.devnull,'w')) pids[p.pid] = p, i From jan.m.danielsson at gmail.com Wed Jul 4 10:22:11 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Wed, 04 Jul 2007 16:22:11 +0200 Subject: [mostly OT] mod_python & doc file system layout Message-ID: <468bad13$1@griseus.its.uu.se> Hello all, This is probably more of an apache question, but I'm guessing there will be other mod_python-beginners who are wondering the same thing. Let's say I have a web app called MyApp. It uses the usual images and style sheets. I keep it all in ~/projects/MyApp/{styles,images,index.py,.htaccess}. I configure up apache to use virtual hosts, and point it to MyApp. Now when I access myapp.local (which points to 127.0.0.1, obviously), my index.py is parsed properly. However, any access made to /images or /styles end up being handled by mod_python, which isn't good, because it won't load images or style sheets. I have solved this by moving index.py (and the associated .htaccess) to a subdirectory "main". I guess one solution would be to make an access to / on the virtual server redirect to main. Another solution, I guess, would be to make the python script load the images and style sheets.. A solution which I find to be particularly ugly. :-) Any mod_python users out there with any other solutions? -- Kind regards, Jan Danielsson From semanticist at gmail.com Wed Jul 25 01:54:52 2007 From: semanticist at gmail.com (Miles) Date: Wed, 25 Jul 2007 01:54:52 -0400 Subject: idiom for RE matching In-Reply-To: References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> <1185157313.356112.159020@z24g2000prh.googlegroups.com> <2f6dnUlUxd2_7TjbnZ2dnUVZ_qy3nZ2d@comcast.com> Message-ID: On 7/24/07, Gordon Airporte wrote: > I did already find that it speeds things up to pre-test a line like > > if 'bets' or 'calls' or 'raises' in line: > run the appropriate re's Be careful: unless this is just pseudocode, this Python doesn't do what you think it does; it always runs the regular expressions, so any speed-up is imaginary. >>> line = 'eggs' >>> bool('spam' or 'ham' in line) True >>> 'spam' or 'ham' in line # Equivalent to: 'spam' or ('ham' in line) 'spam' AFAIK, the (Python 2.5) idiom for what you want is: >>> any(s in line for s in ('spam', 'ham')) False >>> line = 'Spam, spam, spam, spam' >>> any(s in line for s in ('spam', 'ham')) True -Miles From bdesth.quelquechose at free.quelquepart.fr Sun Jul 15 18:38:33 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 16 Jul 2007 00:38:33 +0200 Subject: Private functions and inheritance In-Reply-To: <1184596318.146981.242830@n60g2000hse.googlegroups.com> References: <1184596318.146981.242830@n60g2000hse.googlegroups.com> Message-ID: <469be39f$0$2726$426a74cc@news.free.fr> Maciej Blizi?ski a ?crit : (snip the rest - already answered by at least 3 persons). > I > don't want to expose the __bar() function outside, but on the other > hand i want to defer its implementation to a subclass. It seems like I > need to make it public, doesn't it? First, keep in mind that that Python *does not* have any notion of (languaged enforced) access restriction. All that the __name thingie does is to mangle the name with the class name, so A.bar become A._A__bar. This can be useful. Sometimes. Perhaps. (FWIW, I think I've used it once in seven years and I'm not sure it was really necessary after all). Now there's a strong convention which says that _names prefixed by a single underscore are implementation stuff, and that anyone messing with implementation stuff implicitely accepts all the possible consequences. From dbd at ieee.org Wed Jul 25 15:16:29 2007 From: dbd at ieee.org (dbd) Date: Wed, 25 Jul 2007 12:16:29 -0700 Subject: How to create a single executable of a Python program In-Reply-To: References: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> Message-ID: <1185390989.565702.37330@z28g2000prd.googlegroups.com> On Jul 25, 10:20 am, Larry Bates wrote: > NicolasG wrote: > > Dear fellows, > > > I'm trying to create a executable file using py2exe . Unfortunately > > along with the python executable file it also creates some other files > > that are needed in order to the executable be able to run in a system > > that doesn't have Python installed. Can some one guide me on how can I > > merge all this files created by py2exe in a single exe file ? If I > > have a python program that uses an image file I don't want this image > > file to be exposed in the folder but only to be accessible through the > > program flow.. > > > Regards, > > Nicolas. > > You need to tell us why you "think" you need this and perhaps we can make a > suggestion. Question: Have you installed ANY applications recently that > consisted of only a single file on your hard drive? Answer: No. Most > applications install many (sometimes hundreds) of files. So what is the > problem. If you want a single file to distribute, look at Inno Installer. Use > it to make a single, setup.exe out of all the files that come out of py2exe > along with documentation, shortcuts, etc. that a good modern application needs. > > -Larry I use a number of utilities that install as a single executable file. In fact, that is why I use them. I can install them on systems and remove them with simple fast tools and I can count on not leaving any extraneous crap behind. Utilities can afford to trade off simplicity for the efficiencies in memory footprint and programmer time that giant apps must struggle for. But, not everyone writes utilities. Does this multi-file stance mean that there is an automatic assumption that python is only for Microsoft wannabes? Dale B. Dalrymple From oneelkruns at hotmail.com Mon Jul 2 19:48:12 2007 From: oneelkruns at hotmail.com (rtk) Date: Mon, 02 Jul 2007 16:48:12 -0700 Subject: Tiny/small/minimalist Python? In-Reply-To: <7xmyyeizf8.fsf@ruckus.brouhaha.com> References: <1183332951.122782.212720@o11g2000prd.googlegroups.com> <7xved3satm.fsf@ruckus.brouhaha.com> <1183389420.175712.59460@z28g2000prd.googlegroups.com> <7xmyyeizf8.fsf@ruckus.brouhaha.com> Message-ID: <1183420092.036559.242680@e16g2000pri.googlegroups.com> On Jul 2, 9:43 am, Paul Rubin wrote: > rtk writes: > > FYI.. I wanted a simple version of Python to run on an ancient DEC > > Alpha box. I got VMS Python 2.5 up and running but it is too slow to > > use. It takes *minutes* to get the interpreter prompt after typing > > 'python'! > > Something is wrong. Maybe it's trying to DNS itself and timing out, > or something like that. The trouble is that the Alpha is too old. VMS Python is compiled for a newer machine with a different instruction set and the Alpha is emulating the machine instructions it does not have (a nice feature of OpenVMS, but of dubious value). For my needs, the effort of recompiling all of Python wasn't worth it. Since Lua runs under Unix it will be perfect for my project. I'm writing a compiler for a simple language to 6502 assembly code. I've already written one in Python for small PIC microcontrollers (see PIC0 at http://www.geocities.com/oneelkruns/) and was planning on using Python for this compiler project as well but it will be fun to use something new, too. I am thinking of doing most of the development in OpenVMS, just for the heck of it. Ron From davefowler at gmail.com Fri Jul 20 14:42:33 2007 From: davefowler at gmail.com (godavemon) Date: Fri, 20 Jul 2007 18:42:33 -0000 Subject: path error Message-ID: <1184956953.317214.69370@i38g2000prf.googlegroups.com> I'm on an intel macbook using OS X 10.4 and for some reason my path is being interpreted incorrectly. See the example: dave at jared3-jared$ pwd /Users/dave/til/jared <----- dirname = jared dave at jared3-jared$ python ... >>> import os >>> os.path.abspath('') '/Users/dave/til/Jared' <----- dirname = Jared python is capitalizing my jared directory. It has worked for a long time but suddenly doesn't. I'm working on the project over SVN, could it be some kind of incompatibility with someone who submitted using windows or something? Any solutions for this? From doug at alum.mit.edu Mon Jul 9 14:31:28 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Mon, 09 Jul 2007 14:31:28 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <9uRhi.17027$xk5.14289@edtnps82> Message-ID: "Chris Mellon" writes: >> And why would you do that? People rely very heavily in C++ on when >> destructors will be called, and they are in fact encouraged to do so. >> They are, in fact, encouraged to do so *so* much that constructs like >> "finally" and "with" have been rejected by the C++ BDFL. Instead, you >> are told to use smart pointers, or what have you, to clean up your >> allocated resources. > For the record, C++ doesn't have a BDFL. Yes, I know. http://dictionary.reference.com/browse/analogy > And yes, I know that it's used all the time in C++ and is heavily > encouraged. However, C++ has totally different object semantics than > Python, That would depend on how you program in C++. If you use a framework based on refcounted smart pointers, then it is rather similar. Especially if you back that up in your application with a conservative garbage collector, or what have you. >> I so no reason not to make Python at least as expressive a programming >> language as C++. > I have an overwhelming urge to say something vulgar here. I'm going > to restrain myself and point out that this isn't a discussion about > expressiveness. Says who? >> That's a poor analogy. C doesn't guarantee that pointers will be >> initialized to 0, and in fact, they typically are not. CPython, on >> other other hand, guarantees that the refcounter behaves a certain >> way. > It's a perfect analogy, because the value of an uninitialized pointer > in C is *implementation dependent*. Name one common C implementation that guarantees that uninitialized pointers will be initialized to null. None that I have *ever* used make such a guarantee. In fact, uninitialized values have always been garbage with every C compiler I have ever used. If gcc guaranteed that uninitialized variables would always be zeroed, and you knew that your code would always be compiled with gcc, then you would be perfectly justified in coding in a style that assumed null values for uninitialized variables. Those are some big if's, though. > The Python language reference explicitly does *not* guarantee the > behavior of the refcounter. Are you suggesting that it is likely to change? If so, I think you will find a huge uproar about it. > By relying on it, you are relying on an implementation specific, > non-specified behavior. I'm relying on a feature that has worked fine since the early '90s, and if it is ever changed in the future, I'm sure that plenty of other language changes will come along with it that will make adapting code that relies on this feature to be the least of my porting worries. > Exactly like you'd be doing if you rely on the value of > uninitialized variables in C. Exactly like I'd be doing if I made Unix system calls in my C code. After all, system calls are implementation dependent, aren't they? That doesn't mean that I don't rely on them every day. >> There are languages other than C that guarantee that values are >> initialized in certain ways. Are you going to also assert that in >> those languages you should not rely on the initialization rules? > Of course not. Because they *do* guarantee and specify that. C > doesn't, and neither does Python. CPython does by tradition *and* by popular will. Also the language reference manual specifically indicates that CPython uses a refcounter and documents that it collects objects as soon as they become unreachable (with the appropriate caveats about circular references, tracing, debugging, and stored tracebacks). |>oug From treble54 at gmail.com Tue Jul 24 10:58:32 2007 From: treble54 at gmail.com (treble54) Date: Tue, 24 Jul 2007 14:58:32 -0000 Subject: Closures / Blocks in Python Message-ID: <1185289112.771239.200260@n60g2000hse.googlegroups.com> Does anyone know a way to use closures or blocks in python like those used in Ruby? Particularly those used in the { } braces. From alia_khouri at yahoo.com Sun Jul 22 21:28:25 2007 From: alia_khouri at yahoo.com (Alia Khouri) Date: Sun, 22 Jul 2007 18:28:25 -0700 Subject: recursively expanding $references in dictionaries In-Reply-To: <1185145795.478500.229370@57g2000hsv.googlegroups.com> References: <1185144473.592477.27570@w3g2000hsg.googlegroups.com> <1185145795.478500.229370@57g2000hsv.googlegroups.com> Message-ID: <1185154105.845388.35240@r34g2000hsd.googlegroups.com> Ok. I've reached a nice little conclusion here. Time to go to bed, but before that I thought I'd share the results (-; I can now read a yaml file which natively produces a dict tree and convert it into an object tree with attribute read/write access, dump that back into a readable yaml string, and then expand references within that using cheetah in a very nifty self-referential way.* (see: http://pyyaml.org/wiki/PyYAML) and cheetah templates (http:// www.cheetahtemplate.org/) Enjoy! AK from Cheetah.Template import Template from pprint import pprint import yaml class Object(dict): def __getattr__(self, name): if name in self: return self[name] #~ if name in self.__dict__: return getattr(self, name) def __setattr__(self, name, value): self[name] = value def getTree(tree, to_dict=False): _tree = Object() if not to_dict else dict() def recurse(targetDict, sourceDict): for key, value in sourceDict.items(): if isinstance(value, dict): value = Object(value) if not to_dict else dict(value) new_target = targetDict.setdefault(key, value) recurse(new_target, value) else: targetDict[key] = value recurse(_tree, tree) return _tree config = ''' app: name: appname copyright: me.org 2007 dir: src: /src/$app.name ''' # from yml dict tree to obj tree root = getTree(yaml.load(config)) print root print assert root.app.name == root.app['name'] root.app.name = "the_monster" # from obj tree to dict tree root = getTree(root, to_dict=True) # from dict tree to yaml string s = yaml.dump(root) print s # use cheetah templates to expand references print str(Template(s, searchList=[root])) From rampeters at gmail.com Sun Jul 8 21:45:03 2007 From: rampeters at gmail.com (johnny) Date: Sun, 08 Jul 2007 18:45:03 -0700 Subject: How to Machine A python script execute Machine B python script? Message-ID: <1183945503.875939.292420@57g2000hsv.googlegroups.com> Anyone know how I can make Machine A python script execute a python script on Machine B ? From gerard.blais at gmail.com Fri Jul 6 12:48:15 2007 From: gerard.blais at gmail.com (Gerry) Date: Fri, 06 Jul 2007 16:48:15 -0000 Subject: file reading anomaly Message-ID: <1183740495.413999.133660@g13g2000hsf.googlegroups.com> Python 2.5, Windows XP. I have a 48-line text file written by a Windows python script, I try to read it as follows: f = open ("depstats.txt", "r", 0) for index, line in enumerate(f): print index, len(line), len(line.split()) f.close() On one PC, this runs without any problem. On another, it appears to succeed (no run-time errors) but does not read all the lines. If I print the lines and sum of the line lengths so far inside the loop, the program can be seen to have only read the first N bytes, where N is either 4096, or 8192. Any ideas? Thanks, Gerry From aleax at mac.com Thu Jul 19 11:22:31 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 19 Jul 2007 08:22:31 -0700 Subject: A way to re-organize a list References: <1184857535.033057.49150@m3g2000hsh.googlegroups.com> Message-ID: <1i1hnzn.1y3inwr10yw43iN%aleax@mac.com> 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. If it's already sorted as in your example, itertools.groupby may be what you want. To pick a key, you can use operator.itemgetter, which builds functions picking a specified N-th item of a sequence. Consider...: >>> l [('A', 'a', 1), ('A', 'a', 2), ('A', 'a', 3), ('A', 'b', 1), ('A', 'b', 2), ('B', 'a', 1), ('B', 'b', 1)] >>> itm=operator.itemgetter >>> gb=itertools.groupby >>> list(gb(l, itm(0))) [('A', ), ('B', )] the items in the sequence groupby returns are (key, subsequence) pairs; you don't care about the key, so here's a first step (grouping by first item only): >>> [list(ss) for k, ss in gb(l, itm(0))] [[('A', 'a', 1), ('A', 'a', 2), ('A', 'a', 3), ('A', 'b', 1), ('A', 'b', 2)], [('B', 'a', 1), ('B', 'b', 1)]] However, you want a second level of grouping -- so, instead of the plain list(ss), you need to apply this concept again: >>> [[list(sss) for k,sss in gb(ss,itm(1))] for k, ss in gb(l, itm(0))] [[[('A', 'a', 1), ('A', 'a', 2), ('A', 'a', 3)], [('A', 'b', 1), ('A', 'b', 2)]], [[('B', 'a', 1)], [('B', 'b', 1)]]] ...and there you are. May be more readable with a little auxiliary function to capture what I just called "this concept" with a readable name: >>> def group(s, i): return [list(ss) for k, ss in gb(s, itm(i))] ... >>> [group(ss,1) for ss in group(l,0)] [[[('A', 'a', 1), ('A', 'a', 2), ('A', 'a', 3)], [('A', 'b', 1), ('A', 'b', 2)]], [[('B', 'a', 1)], [('B', 'b', 1)]]] This does one more "list(...)" step, but if your lists aren't huge the readability may be worth the small slow-down. Alex From stefan.behnel-n05pAM at web.de Mon Jul 30 04:33:39 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 30 Jul 2007 10:33:39 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? In-Reply-To: <1T49jcp3Iu8vNv8%stesch@parsec.no-spoon.de> References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> <0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de> <0T49iehiIt1hNv8%stesch@parsec.no-spoon.de> <46AB8194.2060906@web.de> <0T49il77ItapNv8%stesch@parsec.no-spoon.de> <0T49ish0ItfaNv8%stesch@parsec.no-spoon.de> <1T49jcp3Iu8vNv8%stesch@parsec.no-spoon.de> Message-ID: <46ADA263.1020805@web.de> Stefan Scholl wrote: > Michael L Torrie wrote: >> xml.sax's use of parseString() is exactly correct. xml.sax should >> *never* parse python unicode strings as by definition XML must be >> encoded as a *byte stream*, which is what a python string is. > > I don't care about the definition of XML at this point of the > program. Maybe you should, as you're dealing with XML. But then, maybe you're lucky and no-one will have to use your software. > It's not parseString() that tells me something is wrong with the > parameter. It's cStringIO, which is used on platforms where it is > available. On other platforms no exceptions are thrown, because > then StringIO is used, which behaves in Python 2.4 and Python 2.5 > the same, regarding unicode strings. > > Other libraries like LXML (not included) parse unicode strings. But only in very well defined cases. lxml actually checks if the string uses an XML declaration. And if it does, you will get an exception. lxml's parser only accepts a unicode object as input if the unicode object is the only way to determine the encoding. That's lxml's interpretation of transport-provided encoding information, which is allowed by the spec. If you want PyXML to behave the same, go ahead and send a patch to python-dev or xml-sig. > And these are two additional lines in my code now: > > if isinstance(string, unicode): > string = string.encode("utf-8") This will only work as long as your XML does not have an encoding declaration. Does your code guarantee that? Because otherwise it is broken. Have you documented that? >> A python /unicode/ string could be held internally in any number of >> ways, 2, 3, 4, or even 8 bytes per character if the implementation >> demanded it (a bit contrived, I admit). Since the xml parser is only >> ever intended to parse *XML*, why should it ever know what to do with >> python unicode strings, which could be stored any number of ways, making >> byte-parsing impossible. > > xml.sax is no external parser. Right, it's a package. But it contains an *XML* parser. > The program doesn't have to > communicate with the outside world at this point of execution. > The Python programm calls a Python function of a Python class and > passes a Python unicode string as parameter. A sequence of unicode characters, right. Why not just pass XML? Would make your life easier. > The behavior of cStringIO (the original topic of this thread) is > correct and documented. parseString() uses the old idiom where > cStringIO is imported as StringIO, when available. Despite the > fact that they behave differently. > > In my personal opinion: If parseString() shouldn't support > unicode strings, then it should check for it and throw a > meaningful exception. Well, it does. But not because you passed a unicode string but because you passed a unicode string that does not map 1:1 to the standard XML 1-byte encoding. A sequence of plain ASCII characters passed as a unicode string is perfectly ok. So, the API is even forgiving enough to accept unicode strings, it just obeys the XML spec after that, that's all. > At the moment the code just looks as if someone has overlooked > the fact that unicode strings (with non-ascii characters in it) > cause a problem. Missing test? No, just wrong assumption on your side. Read the spec, learn, think, understand. >> So your code is faulty in its assumptions, not xml.sax. > > As I said in the conclusion, a few messages before: Undocumented, > implementation dependent behavior. Well, the implementation was correct *under the assumption* that cStringIO behaved as expected. But as cStringIO deviated from its documentation, xml.sax.parseString could not work as expected. > Or maybe just a bug, considering the following on > http://docs.python.org/lib/module-xml.sax.html > > A typical SAX application uses three kinds of objects: > readers, handlers and input sources. ``Reader'' in this > context is another term for parser, i.e. some piece of > code that reads the bytes or characters from the input > source, and produces a sequence of events. > > > Bytes _or_ characters. I think they were just trying to have more people understand what they wanted to say, not only those who know XML. Stefan From xdicry at gmail.com Sun Jul 29 23:06:52 2007 From: xdicry at gmail.com (Evan) Date: Sun, 29 Jul 2007 20:06:52 -0700 Subject: What is the difference about "pycap" and "pylibpcap"? Message-ID: <1185764812.494730.248820@i38g2000prf.googlegroups.com> Hi, I'm a new hire with python program, I want to write script for changing/moniter/filter the network packet, it seems there are two extensions in python, pycap and pylibcap. I was confused, what is the difference about pycap and pylibpcap? Differnet user interface only? Thanks, From saint.infidel at gmail.com Thu Jul 5 12:07:18 2007 From: saint.infidel at gmail.com (infidel) Date: Thu, 05 Jul 2007 09:07:18 -0700 Subject: list.append not working? In-Reply-To: <1183651138.209079.37620@q75g2000hsh.googlegroups.com> References: <1183651138.209079.37620@q75g2000hsh.googlegroups.com> Message-ID: <1183651638.584640.300240@a26g2000pre.googlegroups.com> On Jul 5, 8:58 am, Hardy wrote: > I experience a problem with append(). This is a part of my code: > > for entity in temp: > md['module']= entity.addr.get('module') > md['id']=entity.addr.get('id') > md['type']=entity.addr.get('type') > #print md > mbusentities.append(md) > #print mbusentities > > I want something like: [{'module': 'home', 'id': 123, 'type': 'core'}, > {'module': 'work', 'id': 456, 'type': 'core'}] > md is always correct, BUT:mbusentities is wrong. Length of > mbusentities is same of temp, so it appended everything. BUT: > mbusentities only shows the values of the last append: [{'module': > 'work', 'id': 456, 'type': 'core'}, {'module': 'work', 'id': 456, > 'type': 'core'}] > > What's wrong? You're reusing the same "md" dictionary over and over, appending the same object to the list each time. So what you have is a list of references to the same dictionary. You need to set md = {} first thing each iteration. From larry.bates at websafe.com Wed Jul 18 11:35:34 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 18 Jul 2007 10:35:34 -0500 Subject: Open HTML file in IE In-Reply-To: <1184739605.732844.321180@m37g2000prh.googlegroups.com> References: <1184739605.732844.321180@m37g2000prh.googlegroups.com> Message-ID: <5ZSdnUHAFPTVrgPbnZ2dnUVZ_hisnZ2d@comcast.com> gravey wrote: > Hello. > > Apologies if this is a basic question, but I want to open a HTML > file from my local drive (is generated by another Python script) > in Internet Explorer. I've had a look at the webbrowser module and > this doesn't seem to be what I need. Any help much appreciated. > There are several ways. Assuming that IE is your default browser, just do: import os os.system('filename.html') If you want to make certain that IE is launched (and not FireForx or some other defult broswer) you can do: os.system("start iexplore filename.html") (at least this works on my system). -Larry From samwyse at gmail.com Sun Jul 8 07:25:11 2007 From: samwyse at gmail.com (samwyse) Date: Sun, 08 Jul 2007 11:25:11 -0000 Subject: what is wrong with that r"\" In-Reply-To: References: Message-ID: <1183893911.627400.232100@r34g2000hsd.googlegroups.com> On Jul 4, 7:15 am, Matthieu TC wrote: > May I suggest giving the possibility to use any delimiter for a raw string? just like in Vi or ruby. > > Vi: > %s_a_b_g is valid and so is %s/a/b/g > > Ruby: > %q{dj'\ks'a\'"} or %q-dj'\ks'a\'"- > > So as long as your regex does not use all the valid characters, readability is maintained. first, you'll need a way to flag that something is an arbitrarily quoted string; 'r' is taken, so let's use 'q'. next, you need to distinguish strings from variables, perhaps by adding a flag to all variables; $ should do nicely and has some historical precident. once you've done all that, you can write something like this: $q = q|this so-called "string" doesn't use conventional quotes| congratulations! you've just invented perl! From mccredie at gmail.com Mon Jul 16 20:13:35 2007 From: mccredie at gmail.com (Matimus) Date: Tue, 17 Jul 2007 00:13:35 -0000 Subject: Semantics of file.close() In-Reply-To: <1184628945.314844.53300@k79g2000hse.googlegroups.com> References: <1184628945.314844.53300@k79g2000hse.googlegroups.com> Message-ID: <1184631215.294683.317790@g12g2000prg.googlegroups.com> > How do I ensure that the close() methods in my finally clause do not > throw an exception? You have no choice. If close is going to fail, it will fail. Fortunately you can catch the exception and continue on. try: try: file1.write(somestuff) finally: file1.close() except IOError: pass or you could wrap it in the inner scope: try: file1.write(somestuff) finally: try: file1.close() except IOError: pass This doesn't prevent the exception from happening, but it prevents the user for seeing it. Also, you don't need to use semicolons in python. From godzillaismad at gmail.com Thu Jul 12 23:05:31 2007 From: godzillaismad at gmail.com (Godzilla) Date: Thu, 12 Jul 2007 20:05:31 -0700 Subject: Fastest way to convert a byte of integer into a list In-Reply-To: <1184289204.494179.244820@w3g2000hsg.googlegroups.com> References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> <1184284461.506663.75500@g12g2000prg.googlegroups.com> <1184284861.695430.99300@e9g2000prf.googlegroups.com> <7xr6ndtae7.fsf@ruckus.brouhaha.com> <1184287796.252097.46660@x35g2000prf.googlegroups.com> <1184289204.494179.244820@w3g2000hsg.googlegroups.com> Message-ID: <1184295931.938495.239720@x35g2000prf.googlegroups.com> On Jul 13, 11:13 am, bsneddon wrote: > On Jul 12, 8:49 pm, John Machin wrote: > > > On Jul 13, 10:28 am, Paul Rubin wrote: > > > > Godzilla writes: > > > > > num = 255 > > > > > numlist = [num >> i & 1 for i in range(8)] > > > > > Thanks matimus! I will look into it... > > > > numlist = lookup_table[num] > > > > where lookup_table is a precomputed list of lists. > > > Ummm ... didn't the OP say he had 32-bit numbers??? > > List comprehension would be faster, lookup would be even faster but > would have to generate list or dictionary ahead of time > but this will work on any length int up 2 limit of int does not pad > with zeros on most significant end to word length. > > n=input() > l=[] > while(n>0): > l.append(str(n&1)); n=n>>1 > > I posted this herehttp://www.uselesspython.com/download.php?script_id=222 > a while back. Thanks all... I will have a look at it soon. Regarding to the 32-bit number, the lenght is variable but it is usually defined at design time... From percivall at gmail.com Wed Jul 11 21:17:25 2007 From: percivall at gmail.com (Simon Percivall) Date: Wed, 11 Jul 2007 18:17:25 -0700 Subject: socket programming related. In-Reply-To: <1184200528.163653.143670@m3g2000hsh.googlegroups.com> References: <1184200362.261465.125810@w3g2000hsg.googlegroups.com> <1184200528.163653.143670@m3g2000hsh.googlegroups.com> Message-ID: <1184203045.438733.209410@w3g2000hsg.googlegroups.com> On Jul 12, 2:35 am, hari.sir... at gmail.com wrote: > On Jul 11, 7:32 pm, hari.sir... at gmail.com wrote: > > > I have just started working in network programming using python. > > written code for socket connection between client and server. Client > > sent data to server for server processing (also server echoing back > > rcvd data to client). When there is ("if no data": break ) no data > > from client then the while loops break in server. The server program > > process recvd data and my requirement is to send back the *results* to > > client program for user sake. I did many trials but no use, as these > > socket calls are blocking, i could not make my req. > > I just need to add a line. The while loop in server breaks when the > sockObj.close() happens in client program indicating there is no data > from client. Well, you shouldn't do a close() on the client socket, you should do a shutdown(1). From msurel at comcast.net Thu Jul 26 09:42:26 2007 From: msurel at comcast.net (Mike) Date: Thu, 26 Jul 2007 06:42:26 -0700 Subject: first, second, etc line of text file In-Reply-To: References: <1185394350.032814.262990@d55g2000hsg.googlegroups.com> Message-ID: <1185457346.458799.55360@j4g2000prf.googlegroups.com> On Jul 26, 8:46 am, "Daniel Nogradi" wrote: > > > A very simple question: I currently use a cumbersome-looking way of > > > getting the first, second, etc. line of a text file: > > > > for i, line in enumerate( open( textfile ) ): > > > if i == 0: > > > print 'First line is: ' + line > > > elif i == 1: > > > print 'Second line is: ' + line > > > ....... > > > ....... > > > > I thought about f = open( textfile ) and then f[0], f[1], etc but that > > > throws a TypeError: 'file' object is unsubscriptable. > > > > Is there a simpler way? > > > If all you need is sequential access, you can use the next() method of > > the file object: > > > nextline = open(textfile).next > > print 'First line is: %r' % nextline() > > print 'Second line is: %r' % nextline() > > ... > > > For random access, the easiest way is to slurp all the file in a list > > using file.readlines(). > > Thanks! This looks the best, I only need the first couple of lines > sequentially so don't need to read in the whole file ever. if you only ever need the first few lines of a file, why not keep it simple and do something like this? mylines = open("c:\\myfile.txt","r").readlines()[:5] that will give you the first five lines of the file. Replace 5 with whatever number you need. next will work, too, obviously, but won't that use of next hold the file open until you are done with it? Or, more specifically, since you do not have a file object at all, won't you have to wait until the function goes out of scope to release the file? Would that be a problem? Or am I just being paranoid? From carsten at uniqsys.com Fri Jul 13 01:26:46 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 13 Jul 2007 01:26:46 -0400 Subject: Most efficient way to evaluate the contents of a variable. In-Reply-To: <46970180$0$13186$9b622d9e@news.freenet.de> References: <1184300936.115235.121980@g12g2000prg.googlegroups.com> <46970180$0$13186$9b622d9e@news.freenet.de> Message-ID: <20070713050435.M63070@uniqsys.com> On Fri, 13 Jul 2007 06:37:19 +0200, Stargaming wrote > bdude schrieb: > > Hey, I'm new to python and am looking for the most efficient way to > > see if the contents of a variable is equal to one of many options. > > > > Cheers, > > Bryce R > > > > if var in ('-h', '--hello', '-w', '--world'): > pass Unless the list of choices is trivially small, a set performs membership tests faster than a tuple: $ python -m timeit -s "s=('eggs','spam','parrot')" "'eggs' in s" 10000000 loops, best of 3: 0.177 usec per loop $ python -m timeit -s "s=('eggs','spam','parrot')" "'spam' in s" 1000000 loops, best of 3: 0.219 usec per loop $ python -m timeit -s "s=('eggs','spam','parrot')" "'parrot' in s" 1000000 loops, best of 3: 0.262 usec per loop $ python -m timeit -s "s=('eggs','spam','parrot')" "'python' in s" 1000000 loops, best of 3: 0.303 usec per loop $ python -m timeit -s "s=set(('eggs','spam','parrot'))" "'eggs' in s" 10000000 loops, best of 3: 0.192 usec per loop $ python -m timeit -s "s=set(('eggs','spam','parrot'))" "'spam' in s" 10000000 loops, best of 3: 0.192 usec per loop $ python -m timeit -s "s=set(('eggs','spam','parrot'))" "'parrot' in s" 10000000 loops, best of 3: 0.192 usec per loop $ python -m timeit -s "s=set(('eggs','spam','parrot'))" "'python' in s" 10000000 loops, best of 3: 0.189 usec per loop -- Carsten Haese http://informixdb.sourceforge.net From craig.howard at earthlink.net Tue Jul 17 20:05:14 2007 From: craig.howard at earthlink.net (Craig Howard) Date: Tue, 17 Jul 2007 20:05:14 -0400 Subject: Single-stepping through a python script Message-ID: >>Craig Howard schrieb: >> Hello All: >> >> Is is possible to compile a code object and single-step through its >> execution? >import pdb; pdb.set_trace() > >Look up the pdb module documentation. > >Diez Sorry, I didn't give enough detail. Is it possible to single-step through a code object without using pdb? (Pdb uses the console which is not what I want.) Craig From http Tue Jul 10 01:06:34 2007 From: http (Paul Rubin) Date: 09 Jul 2007 22:06:34 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <468c0827$0$22906$426a74cc@news.free.fr> <7x3b03lusa.fsf@ruckus.brouhaha.com> <468c18fc$0$26377$426a74cc@news.free.fr> <7xabu7e9ku.fsf@ruckus.brouhaha.com> <46925cdf$0$27972$426a34cc@news.free.fr> Message-ID: <7x7ip87spx.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > > If the assertion is wrong, the compiler signals an error. In > > that sense it's like a unit test; it makes sure the function does what > > the user expects. > > It still boils down to the same problem : possibly valid types are > rejected based on a declaration. I'm not sure what you mean. If the programmer intended for the function to compute an integer, then it's invalid for the function to return (say) a string, whether there is a static typecheck or not. The type signature just makes sure the function works as intended, at least as regards its return type. If you mean that the programmer might have valid reasons to return a mix of types dynamically and static languages get in the way of that, well sure that's true, though I suspect that polymorphism and algebraic types can handle most of these cases. > > However, that may be a self-fulfilling prophecy since maybe I'm > > cultivating a coding style that doesn't use the dynamism, > > Perhaps is this coding style not making the best use of Python's > features ? To me, it sounds like doing procedural programming in OCaml - > it's of course possible, but probably not the best way to use the language. This is in principle possible, though I feel like I'm coding more effectively since gravitating to this style. Anton van Straaten (a dynamic typing proponent) wrote of static checks (http://lambda-the-ultimate.org/node/2216#comment-31954): In most cases, the correctness proof itself is not the most important advantage of static checking of a program. Rather, it's the type discipline that must be followed in order to achieve that correctness proof. The final proof is like the certificate you get when you graduate from college: it's not that important by itself, but to have obtained it you must have done a lot of work, at least some of which is important and necessary. You can do the work without getting the certificate, but many people don't, and in the programming case they may pay a price for that in terms of programs with poor type discipline, which can have consequences for reasoning and the "ilities". I coded a fair amount of Lisp before starting with Python though, so even before, I tended to code Python in a Lisp-like style, ignoring Python's more dynamic features such as metaclasses. I'd also compare the situation with Forth, where functions can consume and insert arbitrary numbers of values to the stack, but programmers in practice maintain careful stack discipline (making sure to pop and push a constant number of values, and documenting the meaning of each one) in order to avoid going crazy. Just because the language offers you rope, doesn't mean you can't decline to hang yourself with it. Finally, this article about "gradual typing" (you can write your code dynamically and then later add static annotations resulting in type safety) might be of interest: http://lambda-the-ultimate.org/node/1707 From gentoodev at gmail.com Mon Jul 9 10:27:31 2007 From: gentoodev at gmail.com (Rob Cakebread) Date: Mon, 09 Jul 2007 07:27:31 -0700 Subject: Tool for finding external dependencies In-Reply-To: <1183990671.337753.106370@k79g2000hse.googlegroups.com> References: <1183945183.147231.120180@z28g2000prd.googlegroups.com> <1183990671.337753.106370@k79g2000hse.googlegroups.com> Message-ID: <1183991251.354349.326520@e16g2000pri.googlegroups.com> On Jul 9, 7:17 am, kyoso... at gmail.com wrote: > > Recently I ran into some debugging issues and the freeware app > "Dependency Walker" was suggested to me. I still haven't used it much > since I only got it last Friday, but it looks promising:http://www.dependencywalker.com > > Mike Thanks Mike, but I'm just trying to determine Python imports, like: $ pylint g_pypi [snip lots of other tests which take a lonnnnnng time] External dependencies --------------------- :: configobj (g_pypi.config) portage (g_pypi.enamer,g_pypi.portage_utils,g_pypi.cli) pkg_resources (g_pypi.cli,g_pypi.ebuild) yolk \-pypi (g_pypi.cli) \-setuptools_support (g_pypi.cli) \-yolklib (g_pypi.cli) gentoolkit (g_pypi.portage_utils) pygments (g_pypi.ebuild) \-lexers (g_pypi.ebuild) \-formatters (g_pypi.ebuild) Cheetah \-Template (g_pypi.ebuild) From i3dmaster at gmail.com Fri Jul 6 12:45:54 2007 From: i3dmaster at gmail.com (i3dmaster) Date: Fri, 6 Jul 2007 09:45:54 -0700 Subject: what is wrong with that r"\" In-Reply-To: <27kr83lv67n38fmirvs5vvh5f80cr27joi@4ax.com> References: <27kr83lv67n38fmirvs5vvh5f80cr27joi@4ax.com> Message-ID: <6F9991AD-6144-4BF1-A4F2-6668C293BBB6@gmail.com> Then you can use other chars as the delimiter, r at a@b@ or r!a!b!, etc... The import thing is so long as the interpreter doesn't get confused on the data and the delimiter. sed also allows for arbitrary delimiters too as long as you maintain the integrity of the original meaning... -Jim On Jul 6, 2007, at 5:20 AM, Tim Roberts wrote: > Matthieu TC wrote: > >> May I suggest giving the possibility to use any delimiter for a >> raw string? just like in Vi or ruby. >> >> Vi: >> %s_a_b_g is valid and so is %s/a/b/g >> >> Ruby: >> %q{dj'\ks'a\'"} or %q-dj'\ks'a\'"- >> >> So as long as your regex does not use all the valid characters, >> readability is maintained. > > But what about my program that wants to use r_a_b_ as an identifier? > -- > Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. > -- > http://mail.python.org/mailman/listinfo/python-list From kyosohma at gmail.com Wed Jul 25 12:00:18 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 25 Jul 2007 09:00:18 -0700 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <1185378418.100041.38560@w3g2000hsg.googlegroups.com> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> Message-ID: <1185379218.286977.124040@19g2000hsx.googlegroups.com> On Jul 25, 10:46 am, beginner wrote: > On Jul 25, 10:19 am, Stargaming wrote: > > > > > On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote: > > > Hi, > > > > I am wondering how do I 'flatten' a list or a tuple? For example, I'd > > > like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4]. > > > A recursive function, always yielding the first element of the list, > > could do the job. See the ASPN Python Cookbook for a few implementations.http://aspn.activestate.com/ASPN/search? > > query=flatten§ion=PYTHONCKBK&type=Subsection > > > > Another question is how do I pass a tuple or list of all the aurgements > > > of a function to the function. For example, I have all the arguments of > > > a function in a tuple a=(1,2,3). Then I want to pass each item in the > > > tuple to a function f so that I make a function call f(1,2,3). In perl > > > it is a given, but in python, I haven't figured out a way to do it. > > > (Maybe apply? but it is deprecated?) > > >>> def foo(a, b, c): print a, b, c > > ... > > >>> t = (1, 2, 3) > > >>> foo(*t) > > > 1 2 3 > > > Have a look at the official tutorial, 4.7.4http://www.python.org/doc/ > > current/tut/node6.html#SECTION006740000000000000000 > > > > Thanks, > > > cg > > > HTH, > > Stargaming > > Hi Stargaming, > > I know the * operator. However, a 'partial unpack' does not seem to > work. > > def g(): > return (1,2) > > def f(a,b,c): > return a+b+c > > f(*g(),10) will return an error. > > Do you know how to get that to work? > > Thanks, > cg As I mentioned, you can access the elements individually using square brackets. The following works: f(g()[0], g()[1], 10) But it's not clear. Unfortunately, I'm not seeing much else for tuple unpacking except the obvious: a,b=g() f(a,b,10) Mike From crcarleRemoveThis at BOGUSsandia.gov Fri Jul 13 14:05:21 2007 From: crcarleRemoveThis at BOGUSsandia.gov (Chris Carlen) Date: Fri, 13 Jul 2007 11:05:21 -0700 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: John Nagle wrote: > Chris Carlen wrote:[edit] >> Hence, being a hardware designer rather than a computer scientist, I >> am conditioned to think like a machine. I think this is the main >> reason why OOP has always repelled me. > > Why? When pointers were first explined to me, I went "Ok." And rather quickly ideas lit up in my head about what I could do with them. When I read what OOP is, that doesn't happen. All I think is "what's the point of this?" "What can this do for me that I can do already with the procedural way of thinking?" And if it can't do anything new, then why rearrange my thinking to a new terminology? It's results that matter, not the paradigm. > I've written extensively in C++, including hard real-time programming > in C++ under QNX for a DARPA Grand Challenge vehicle. Did the vehicle win? > I have an Atmel > AVR with a cable plugged into the JTAG port sitting on my desk right now. > Even that little thing can be programmed in C++. Yes. > You can sometimes get better performance in C++ than in C, because C++ > has "inline". Inline expansion happens before optimization, so you > can have abstractions that cost nothing. That's interesting. But why is this any different than using preprocessor macros in C? > > If it has state and functions, it probably should be an object. > The instances of the object can be static in C++; dynamic memory > allocation isn't required in C++, as it is in Python. Why? Why is OOP any better at explaining a state machine to a computer? I can write state machines all over the place in C, which tend to be the core of most of my embedded programs. I can write them with hardcoded logic if that seems like the easy thing to do any the probability of extensive changes is extremely low. They are extremely easy to read and to code. I have written a table-driven state machine with arbitrary-length input condition lists. The work was all in designing the data structures. The code to update the state machine was about 4 lines. Why would OOP be better? Different is not better. Popular is not better. What the academics say is not better. Less lines of code might be better, if the priority is ease of programming. Or, less machine execution time or memory usage might be better, if that is the priority. Until I can clearly understand why one or the other of those goals might better be realized for a given problem with OOP vs. procedures, I just don't get it. I will keep an open mind however, that until I work with it for some time there is still the possibility that I will have some light go on about OOP. So don't worry, I'm not rejecting your input. > Python is a relatively easy language, easier than C++, Java, > or even Perl. It's quite forgiving. The main implementation, > CPython, is about 60x slower than C, though, so if you're trying > to implement, say, a rapidly changing digital oscilloscope display, > the result may be sluggish. Yes, I certainly wouldn't consider Python for that. Thanks for your comments. -- Good day! ________________________________________ Christopher R. Carlen Principal Laser&Electronics Technologist Sandia National Laboratories CA USA crcarleRemoveThis at BOGUSsandia.gov NOTE, delete texts: "RemoveThis" and "BOGUS" from email address to reply. From samwyse at gmail.com Fri Jul 13 01:56:10 2007 From: samwyse at gmail.com (samwyse) Date: Fri, 13 Jul 2007 05:56:10 -0000 Subject: Assignments to __class_ broken in Python 2.5? In-Reply-To: <1184258925.321462.50270@k79g2000hse.googlegroups.com> References: <1183863713.876365.111820@57g2000hsv.googlegroups.com> <1184239885.828717.271410@r34g2000hsd.googlegroups.com> <1184258925.321462.50270@k79g2000hse.googlegroups.com> Message-ID: <1184306170.262648.289910@22g2000hsm.googlegroups.com> On Jul 12, 11:48 am, samwyse wrote: > On Jul 12, 6:31 am,samwyse wrote: > > > On Jul 8, 8:50 am, Christoph Zwerschke wrote: > > > > With Py 2.5 I get: > > > > new.__class__ = old.__class__ > > > TypeError: __class__ must be set to a class > > Hmmm, under Python 2.4.X, printing repr(old.__class__) gives me this: > > while under 2.5.X, I get this: > > > So, let's try sub-classing the type: > > def modify_message(old, f): > class Empty: pass > new = Empty() > print "old.__class__ =", repr(old.__class__) > print "Empty =", repr(Empty) > new.__class__ = Empty > > class Excpt(old.__class__): pass > print "Excpt =", repr(Excpt) > print "Excpt.__class__ =", repr(Excpt.__class__) > new.__class__ = Excpt > > new.__dict__ = old.__dict__.copy() > new.__str__ = f > return new > > Nope, that gives us the same message: > > old.__class__ = > Empty = > Excpt = > Excpt.__class__ = > Traceback (most recent call last): > [...] > TypeError: __class__ must be set to a class > > Excpt certainly appears to be a class. Does anyone smarter than me > know what's going on here? OK, in classobject.h, we find this: #define PyClass_Check(op) ((op)->ob_type == &PyClass_Type) That seems straightforward enough. And the relevant message appears in classobject.c here: static int instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v) [...] if (strcmp(sname, "__class__") == 0) { if (v == NULL || !PyClass_Check(v)) { PyErr_SetString(PyExc_TypeError, "__class__ must be set to a class"); return -1; } Back in our test code, we got these: > Empty = > Excpt = The first class (Empty) passes the PyClass_Check macro, the second one (Excpt) evidently fails. I'll need to dig deeper. Meanwhile, I still have to wonder why the code doesn't allow __class_ to be assigned a type instead of a class. Why can't we do this in the C code (assuming the appropriate PyType_Check macro): if (v == NULL || !(PyClass_Check(v) || PyType_Check(v))) { From gggg.iiiii at gmail.com Tue Jul 31 17:53:04 2007 From: gggg.iiiii at gmail.com (G) Date: Tue, 31 Jul 2007 17:53:04 -0400 Subject: With Statement Contexts and Context Managers In-Reply-To: <1185910527.3370.29.camel@dot.uniqsys.com> References: <4a7f84ac0707311157s5cdd770fw96acaed00785bc73@mail.gmail.com> <1185910527.3370.29.camel@dot.uniqsys.com> Message-ID: <4a7f84ac0707311453td0eb010l9d02978278d23baa@mail.gmail.com> Great thanks. On 7/31/07, Carsten Haese wrote: > > On Tue, 2007-07-31 at 14:57 -0400, G wrote: > > Hi, > > > > Could somebody please point me to a good resource to read about > > the contexts, context managers, and with_statement > > > > There's PEP 343 at http://www.python.org/dev/peps/pep-0343/. I don't > know if that fits your definition of "good," but it should at least get > you started. > > HTH, > > -- > Carsten Haese > http://informixdb.sourceforge.net > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vishalkanaujia at gmail.com Wed Jul 18 05:03:56 2007 From: vishalkanaujia at gmail.com (VISHAL KANAUJIA) Date: Wed, 18 Jul 2007 14:33:56 +0530 Subject: Compatibility of python2.5 with pytohn2.3 Message-ID: Hi all, I am new member of this post. I have a C application which uses Python(version 2.3) extensively with SWIG wrappers. I want to upgrade the Python to latest version2.5. Is there any compatibility issue between two versions? Does latest Python2.5 provide backward compatibility to previous Python (Version 2.3 in my case) constructs. Thanks, Vishal From wolf_tracks at invalid.com Sun Jul 15 10:46:55 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Sun, 15 Jul 2007 07:46:55 -0700 Subject: Python and Tkinter Primer/Tutorial? Message-ID: Is there a primer out there on these two items? I have the Python tutorial, but would like either a Tkinter tutorial/primer to supplement it, or a primer/tutorial that addresses both. Maybe there's even an O'Reilly book on both? -- Wayne Watson (Nevada City, CA) Web Page: From msoulier at gmail.com Mon Jul 16 21:34:22 2007 From: msoulier at gmail.com (msoulier) Date: Tue, 17 Jul 2007 01:34:22 -0000 Subject: ANN: Tftpy 0.4.3 Message-ID: <1184636062.516739.80090@o61g2000hsh.googlegroups.com> Copyright, Michael P. Soulier, 2006. About Release 0.4.3: ==================== Buxfix release for an issue with the server's detection of the end of the file during a download. About Release 0.4.2: ==================== Bugfix release for some small installation issues with earlier Python releases. About Release 0.4.1: ==================== Bugfix release to fix the installation path, with some restructuring into a tftpy package from the single module used previously. About Release 0.4: ================== This release adds a TftpServer class with a sample implementation in bin. The server uses a single thread with multiple handlers and a select() loop to handle multiple clients simultaneously. Only downloads are supported at this time. About Release 0.3: ================== This release fixes a major RFC 1350 compliance problem with the remote TID. About Release 0.2: ================== This release adds variable block sizes, and general option support, implementing RFCs 2347 and 2348. This is accessible in the TftpClient class via the options dict, or in the sample client via the --blocksize option. About Release 0.1: ================== This is an initial release in the spirit of "release early, release often". Currently the sample client works, supporting RFC 1350. The server is not yet implemented, and RFC 2347 and 2348 support (variable block sizes) is underway, planned for 0.2. About Tftpy: ============ Purpose: -------- Tftpy is a TFTP library for the Python programming language. It includes client and server classes, with sample implementations. Hooks are included for easy inclusion in a UI for populating progress indicators. It supports RFCs 1350, 2347 and 2348. Dependencies: ------------- This library was developed against Python 2.3. Trifles: -------- Project page: http://sourceforge.net/projects/tftpy/ License is the CNRI Python License. http://www.opensource.org/licenses/pythonpl.php See COPYING in this distribution. Limitations: ------------ - Server only supports downloads. - Client only supports downloads. - Only 'octet' mode is supported - The only option supported is blksize Author: ======= Michael P. Soulier From deets at nospam.web.de Fri Jul 6 11:54:56 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 06 Jul 2007 17:54:56 +0200 Subject: Expandable 2D Dictionaries? References: <1183736635.415927.208450@57g2000hsv.googlegroups.com> Message-ID: <5f76ugF3b6hheU1@mid.uni-berlin.de> Robert Dailey wrote: > Hi, > > I am interested in creating an expandable (dynamic) 2D dictionary. For > example: > > myvar["cat"]["paw"] = "Some String" > > The above example assumes "myvar" is declared. In order for this to > work, I have to know ahead of time the contents of the dictionary. For > the above to work, my declaration must look like: > > myvar = {"cat": {"paw":""} } > > I would like to not have to declare my dictionary like this, as it > does not allow it to be expandable. I'm very new to Python (I'm a > professional C++ programmer. Any comparisons to C++ would help me > understand concepts). > > Is there a way that when I index into my dictionary using an "unknown" > index (string), that python will dynamically add that key/value pair? Not really, unless you know that the first level of values are _always_ dicts. What you can do is to use myvar.setdefault('cat', {})['paw'] = "Some String" Diez From rcdailey at gmail.com Fri Jul 27 12:45:05 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 27 Jul 2007 16:45:05 -0000 Subject: 128 or 96 bit integer types? Message-ID: <1185554705.320673.78500@q75g2000hsh.googlegroups.com> Hi, Is there build-in or third party support for large integer types, such as 96 or 128 bits in size? I require such large sizes for precision issues (nanoseconds). Thanks. From nis at superlativ.dk Thu Jul 12 08:31:46 2007 From: nis at superlativ.dk (=?ISO-8859-15?Q?Nis_J=F8rgensen?=) Date: Thu, 12 Jul 2007 14:31:46 +0200 Subject: bool behavior in Python 3000? In-Reply-To: References: Message-ID: <46961f33$0$90263$14726298@news.sunsite.dk> Alan Isaac skrev: > Since it is seemingly ignored in most of the comments > on this thread, I just want to remind that PEP 285 > http://www.python.org/dev/peps/pep-0285/ > says this: > > In an ideal world, bool might be better implemented as a > separate integer type that knows how to perform mixed-mode > arithmetic. > > I mentioned Python 3000 since that is an opportunity for an ideal world. You forgot to quote this bit: 4) Should we strive to eliminate non-Boolean operations on bools in the future, through suitable warnings, so that for example True+1 would eventually (in Python 3000) be illegal? => No. There's a small but vocal minority that would prefer to see "textbook" bools that don't support arithmetic operations at all, but most reviewers agree with me that bools should always allow arithmetic operations. Nis From grante at visi.com Wed Jul 25 16:48:57 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 25 Jul 2007 20:48:57 -0000 Subject: first, second, etc line of text file References: <5f56302b0707251244p24080f1ct87a5f459cb175dae@mail.gmail.com> Message-ID: <13afdpp7a6t24c5@corp.supernews.com> On 2007-07-25, Jeff McNeil wrote: > Depending on the size of your file, you can just use > file.readlines. Note that file.readlines is going to read the > entire file into memory, so don't use it on your plain-text > version of War and Peace. I don't think that would actually be a problem for any recent machine. The Project Gutenberg version of W&P is 3.1MB of text in 67403 lines. I just did an f.readlines() on it and it was pretty much instantaneous, and the python interpreter instance that contains that list of 67403 lines is using a bit less than 8MB of RAM. An "empty" interpreter uses about 2.7MB. So, doing f.readlines() on War and Peace requires a little over 5MB of RAM -- not really much of a concern on any machine that's likely to be running Python. -- Grant Edwards grante Yow! Now I understand the at meaning of "THE MOD SQUAD"! visi.com From wildemar at freakmail.de Tue Jul 17 14:22:03 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Tue, 17 Jul 2007 20:22:03 +0200 Subject: a=0100; print a ; 64 how to reverse this? In-Reply-To: <469cb76f$0$7584$426a34cc@news.free.fr> References: <1184670575.205759.115360@i13g2000prf.googlegroups.com> <469cb76f$0$7584$426a34cc@news.free.fr> Message-ID: <469D08CB.2070700@freakmail.de> Bruno Desthuilliers wrote: > mosi a ?crit : > >> Problem: >> how to get binary from integer and vice versa? >> [snip] >> What`s the simplest way to do this? >> > > bruno at bruno:~$ 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. > >>> help(int) > Help on class int in module __builtin__: > > class int(object) > | int(x[, base]) -> integer > :D After reading the other two replies, this one made me burst with laughter. Thanks for that. /W From bj_666 at gmx.net Wed Jul 4 07:27:46 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Jul 2007 11:27:46 GMT Subject: what is wrong with that r"\" References: Message-ID: <5f1ehiF3a62csU1@mid.uni-berlin.de> On Wed, 04 Jul 2007 11:21:14 +0000, Neil Cerutti wrote: > If the escaped quotes didn't function in raw strings, I'd be > unable to construct (with a single notation) a regex that > included both kinds of quotes at once. > > re.compile(r"'\"") Where's the problem!? :: re.compile(r''''"''') Ah, I see -- readability is the problem. :-) Ciao, Marc 'BlackJack' Rintsch From kyosohma at gmail.com Tue Jul 31 15:12:48 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 31 Jul 2007 19:12:48 -0000 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: <1185909168.055341.90910@d30g2000prg.googlegroups.com> On Jul 31, 12:30 pm, 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 I'm not sure, but I don't think you need the "win" variable at all. I can get it to work as follows: from Tkinter import * from tkMessageBox import showinfo def reply(): showinfo(title='ciao', message='hello') Button(text='press me', command=reply).pack(fill=X) mainloop() Mike From nomail at noserve Thu Jul 26 15:38:31 2007 From: nomail at noserve (martyw) Date: Thu, 26 Jul 2007 21:38:31 +0200 Subject: removing items from a dictionary ? In-Reply-To: References: Message-ID: <46a8f836$0$28175$9a622dc7@news.kpnplanet.nl> Stef Mientki wrote: > hello, > > I want to remove some items from a dictionary, > so I would expect this should work: > > Nets = {} > ... fill the dictionary Nets > > for net in Nets: > if net.upper() in Eagle_Power_Nets : > del Nets [ net ] > > > But it gives me > Message File Name Line Position > Traceback > ? D:\data_to_test\JALsPy\Eagle_import.py 380 > RuntimeError: dictionary changed size during iteration > > > Now I can solve this problem in the following way > > power_nets = [] > for net in Nets: > if net.upper() in Eagle_Power_Nets : > power_nets.append ( net ) > > # remove power nets from netlist > for net in power_nets: > del Nets [ net ] > > > But I wonder if this is the best way to manipulate a dictionary, > because I've to do more "complex" operations on the dictionary, > like joining items, > I would like to have a better understanding of what can and what can't > be done. > > thanks, > Stef Mientki Remoing elements from a dict is done with del, try this; >>> d = {'a' : 1,'b' : 2} >>> del d['a'] >>> print d {'b': 2} >>> maybe you can post a working snippet to demonstrate your problem From nospam-abuse at ilyaz.org Tue Jul 10 16:59:56 2007 From: nospam-abuse at ilyaz.org (Ilya Zakharevich) Date: Tue, 10 Jul 2007 20:59:56 +0000 (UTC) Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <1183665370.643503.157060@m36g2000hse.googlegroups.com> <5fh0imF3cjte7U1@mid.individual.net> Message-ID: [A complimentary Cc of this posting was sent to greg ], who wrote in article <5fh0imF3cjte7U1 at mid.individual.net>: > Ilya Zakharevich wrote: > > In pedantic mode: negative timestamps make sense with Big Bang as the > > epoch as well. (AFAIU, the current way of thinking is that it was > > "just too hot" before the big bang, it is not that "there was > > nothing".) > > If Stephen Hawking is right, the shape of the universe > is such that there isn't any time "before" the big bang > at all. It's like asking what's north of the North Pole. I do not remember any statement like this - even from 70s... Could you provide a reference? There were conjectures about "initial singularity", but I do not recollect them related to SH. > Of course, this may have been replaced with some other > equally bizarre idea by now... Nothing as bizzare as the "initial singularity". There was a hot soup not very far from a phase transition point; stochastically, some micro-regions (bubbles) cool a little bit, and are subject to a phase transition; due to transition, the metric in them grows (inflation), so the "size" after transition [as seen from inside] is (hundreds? thousands? millions? - I do not remember) orders of magnitude larger than before transition - you get the universe-as-we-know-it as what sits inside a "visible horizon" in such a babble. Wiki for "inflation". > Another thought: If the cosmologists ever decide if > and when the Big Crunch is going to happen, we may be > able to figure out once and for all how many bits we > need in the timestamp. In the "hot soup", it is very hard to construct a watch. There may be even some quantum-mechanical restrictions on bit storage in so hot a matter (but I do not recollect seeing this). If so, then indeed, "nothing measurable" happens before and after inflation/collapse of the universe-as-we-know-it; so timestamp would be restricted to the interval between the bangs. Hope this helps, Ilya From paddy3118 at googlemail.com Sat Jul 28 04:23:45 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 28 Jul 2007 08:23:45 -0000 Subject: Comparing Dictionaries In-Reply-To: References: Message-ID: <1185611025.943782.162330@w3g2000hsg.googlegroups.com> Hi Kenneth, being new to Python i wondered if you at least considered Doctests as part of your testing solution. Other languages don't have Doctest. - Paddy. From larry.bates at websafe.com Mon Jul 23 15:28:04 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 23 Jul 2007 14:28:04 -0500 Subject: Confused with csv.reader copies In-Reply-To: <1185216342.833408.56690@m3g2000hsh.googlegroups.com> References: <1185216342.833408.56690@m3g2000hsh.googlegroups.com> Message-ID: Robert Dailey wrote: > First, take a look at my example code: > ----------------------------------------------------- > import csv > > def pass1( reader ): > print reader.next() > print reader.next() > > def pass2( reader ): > print reader.next() > print reader.next() > > reader = csv.reader( open( "C:/IT/Method/SpaceImpact/code/tools/ > ProfileViewer/performance_profile.csv", "rb" ) ) > > pass1( reader ) > pass2( reader ) > ----------------------------------------------------- > > The output is as follows: > ----------------------------------------------------- > ['0', 'root', '00:01:32.793591', '1'] > ['1', 'Engine::Tick', '00:00:25.886411', '1851'] > ['2', 'Sprite::Tick', '00:00:00.001495', '385'] > ['2', 'Entity::Tick', '00:00:00.001485', '45'] > ----------------------------------------------------- > > I expected the output to be this: > ----------------------------------------------------- > ['0', 'root', '00:01:32.793591', '1'] > ['1', 'Engine::Tick', '00:00:25.886411', '1851'] > ['0', 'root', '00:01:32.793591', '1'] > ['1', 'Engine::Tick', '00:00:25.886411', '1851'] > ----------------------------------------------------- > > My understanding is that objects are passed by reference, meaning > there is no hard copy of the data, however the copies passed to > functions do not affect the version passed in. In other words, when I > call "next" on the reference passed into each function, it should not > affect the variable that was originally passed in. > > I'm attempting to use recursion to build a TreeCtrl in wxPython using > this data, and I can't get it to work properly if the variable outside > of the function call ends up having its state (e.g., its "next" > pointer) modified by passing it into other functions. > > Any tips on getting this to work? I'm a native C++ programmer still > learning Python, so I apologize for any confusion. Thanks. > By reference means that mutable objects can be modified (in place) by the functions that they are passed into. This is a common mistake people make when they first get started. Normally lists seem to throw people first. I don't know how long the file is, but you probably should just read the entire file into memory and process it from there. -Larry From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 10 07:05:32 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 10 Jul 2007 13:05:32 +0200 Subject: How would I write this C code in Python? In-Reply-To: <5f7d2vF3b25tsU3@mid.uni-berlin.de> References: <1183743110.399675.180570@n60g2000hse.googlegroups.com> <5f7d2vF3b25tsU3@mid.uni-berlin.de> Message-ID: <469367e5$0$26831$426a74cc@news.free.fr> Marc 'BlackJack' Rintsch a ?crit : > On Fri, 06 Jul 2007 17:31:50 +0000, DeveloperX wrote: > >> I am trying to figure out how to rewrite the following chunk of code >> in Python: >> >> C source >> [code] >> typedef struct PF >> { >> int flags; >> long user; >> char*filename; >> unsigned char buffer[MAXBUFFERSIZE]; >> } PF; >> >> typedef BLOCK >> { >> PF * packdata; >> } BLOCK; >> >> BLOCK* blocks; >> [/code] >> >> My first idea was to create a class for PF and a class for BLOCK, but >> I got lost somewhere along the lines. :\ >> >> Python Attempt: Please note that since I can't type TABs online >> easily, I am using the @ character to represent TABs in the following >> Python code. >> [code] >> class PF: >> @def __init__(self): >> @@self.flags, self.user = 0, 0 >> @@self.filename = '' >> @@self.buffer = [] >> >> class BLOCK: >> @def __init__(self): >> @@self.packdata = [] >> >> blocks = [] >> [/code] >> >> Any Python Gurus out there that can help me? > > At a first glance it looks okay but unless we know what you are going to > do with these data structures it's hard to tell if it is really the best > "translation". > > `PF.buffer` might be better a string Mmm... We can't tell for sure since we have no use case, but I'm not sure that the OP wants an immutable object here. > or an `array.array`. or a StringIO. > And is `BLOCK` > really just a structure with *one* member? Looks a bit odd IMHO. +1 Unless you have behaviours attached to this type, you may as well just use lists. And while we're at it, Python's conventions are that ALL_UPPER names denotes (pseudo) constants. For types, the conventions is to use CantRememberIfItsCamelOrMixedCaseButYouShouldGetTheIdeaByNow. HTH From paul at boddie.org.uk Wed Jul 4 14:59:57 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Wed, 04 Jul 2007 11:59:57 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7x4pkkun56.fsf@ruckus.brouhaha.com> References: <5dveb4F360un0U1@mid.individual.net> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> Message-ID: <1183575597.272150.152200@w5g2000hsg.googlegroups.com> Paul Rubin wrote: > Bruno Desthuilliers writes: > > Because static type checks impose a lot of arbitrary restrictions, > > boilerplate code etc, which tends to make code more complicated than > > it needs to be, which is a good way of introducing bugs that wouldn't > > have existed without static type checks. > > Why do you say that? By metrics and anecdotal evidence, Haskell code > appears to be at least as compact as Python code. I think Bruno is referring to another class of languages here. However, it's interesting to consider the work that sometimes needs to go in to specify data structures in some languages - thinking of ML and friends, as opposed to Java and friends. The campaign for optional static typing in Python rapidly became bogged down in this matter, fearing that any resulting specification for type information might not be the right combination of flexible and powerful to fit in with the rest of the language, and that's how we really ended up with PEP 3107: make the semantics vague and pretend it has nothing to do with types, thus avoiding the issue completely. Paul From uymqlp502 at sneakemail.com Wed Jul 18 17:54:17 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Wed, 18 Jul 2007 14:54:17 -0700 Subject: type conversions for comparison operators Message-ID: <1184795657.465264.257970@d30g2000prg.googlegroups.com> I recently discovered a bug in one of my programs that surprised me because I thought Python's dynamic type checking would have caught it. Suppose I have a function that returns an integer, such as def numItems: return len(self.items) Now I want to do a test like this: if object.numItems() > 2: But suppose I mistakenly leave off the parentheses: if object.numItems > 2: I would have thought that Python would choke on this, but it doesn't. Apparently, Python converts the operands to a common type, but that seems risky to me. Is there a good reason for allowing a function to be compared to an integer? Thanks. From bj_666 at gmx.net Fri Jul 27 14:45:29 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jul 2007 18:45:29 GMT Subject: Removing certain tags from html files References: <1185558023.501016.90050@d30g2000prg.googlegroups.com> Message-ID: <5gusq9F3iotlrU2@mid.uni-berlin.de> On Fri, 27 Jul 2007 17:40:23 +0000, sebzzz wrote: > My question, since I'm quite new to python, is about what tool I > should use to remove the table, tr and td tags, but not what's > enclosed in it. I think BeautifulSoup isn't good for that because it > removes what's enclosed as well. Than take a hold on the content and add it to the parent. Somthing like this should work: from BeautifulSoup import BeautifulSoup 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) def main(): source = 'This is a Test' soup = BeautifulSoup(source) print soup remove(soup, 'b') print soup > Is re the good module for that? Basically, if I make an iteration that > scans the text and tries to match every occurrence of a given regular > expression, would it be a good idea? No regular expressions are not a very good idea. They get very complicated very quickly while often still miss some corner cases. Ciao, Marc 'BlackJack' Rintsch From grante at visi.com Mon Jul 16 15:23:05 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 16 Jul 2007 19:23:05 -0000 Subject: Binary blobs to jpeg References: <1184612270.455699.254560@r34g2000hsd.googlegroups.com> <1184612920.610854.226290@57g2000hsv.googlegroups.com> Message-ID: <139nhcpl4jk7he6@corp.supernews.com> On 2007-07-16, jayharvard1 at gmail.com wrote: >> Have you tried to open the file in "wb" mode? > > The data is coming from a record set selection from the Access > database. I guess I could write the data to a temp file and > open that file handle with the "wb" mode. But, no, I haven't > tried that. I think you missed the point. When you want to write the binary data to a file, you must open the destination file using "wb" mode. It's binary data, not text data, so you have to open the output file in binary mode. -- Grant Edwards grante Yow! Is my fallout shelter at termite proof? visi.com From josiah.carlson at sbcglobal.net Thu Jul 19 03:54:31 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Thu, 19 Jul 2007 07:54:31 GMT Subject: wxPython and threads In-Reply-To: <1184726489.112138.96350@z28g2000prd.googlegroups.com> References: <1184726489.112138.96350@z28g2000prd.googlegroups.com> Message-ID: Benjamin wrote: > I'm writing a search engine in Python with wxPython as the GUI. I have > the actual searching preformed on a different thread from Gui thread. > It sends it's results through a Queue to the results ListCtrl which > adds a new item. This works fine or small searches, but when the > results number in the hundreds, the GUI is frozen for the duration of > the search. I suspect that so many search results are coming in that > the GUI thread is too busy updating lists to respond to events. I've > tried buffer the results so there's 20 results before they're sent to > the GUI thread and buffer them so the results are sent every .1 > seconds. Nothing helps. Any advice would be great. Sending results one at a time to the GUI is going to be slow for any reasonably fast search engine (I've got a pure Python engine that does 50k results/second without breaking a sweat). Don't do that. Instead, have your search thread create a list, which it fills with items for some amount of time, *then* sends it off to the GUI thread (creating a new list that it then fills, etc.). While you *could* use a Queue, it is overkill for what you want to do (queues are really only useful when there is actual contention for a resource and you want to block when a resource is not available). Create a deque, and use append() and popleft(). To signal to the GUI thread that there are results available in your deque, you can use wx.CallAfter(), which will be run in the GUI thread when the event comes up. Alternatively, you can use a combination of wx.PostEvent() and wx.lib.newevent (see: http://wiki.wxpython.org/CustomEventClasses ) to pass the results, or even just signal that 'more results are available in the deque'. I would suggest merely signaling that more results are in the deque (using wx.PostEvent() or wx.CallAfter()), as there are no guarantees on the order of execution when events are posted (I have found that the event queue sometimes behaves like a stack). I would also suggest never polling any queue from the GUI thread. It's wasteful. Just have it respond to an event (either explicitly from wx.PostEvent() or implicitly with wx.CallAfter()). - Josiah From sisson.j at gmail.com Fri Jul 6 16:38:03 2007 From: sisson.j at gmail.com (J Sisson) Date: Fri, 6 Jul 2007 20:38:03 +0000 Subject: The best platform and editor for Python In-Reply-To: <138t9fhlcdq1nf8@corp.supernews.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183646799.400176.144570@k79g2000hse.googlegroups.com> <1183655933.475488.157270@m36g2000hse.googlegroups.com> <1183670009.035673.256680@w5g2000hsg.googlegroups.com> <1i0so61.10qnto712c7dhpN%aleax@mac.com> <138t9fhlcdq1nf8@corp.supernews.com> Message-ID: <4297a9020707061338r3e269a67ma94fdee282a18038@mail.gmail.com> On 7/6/07, Ed Jensen wrote: > > Alex Martelli wrote: > > Calling all vi/vim users (and we'll heartily appreciate the support of > > TextMate fans, BBEdit ones, etc, etc) -- we're at risk being defined out > > of existence, since we're neither happy with Emacs nor wanting anything > > like Visual Studio, and yet Kay claims that people in either category > > make up the whole (one half plus the other half) and so that WE DON'T > > EXIST!!! A ridiculous claim to be sure, but we'd better let Herr > > Schluehr know that in no uncertain terms... > > vi/vim/gvim user here... :) > -- > http://mail.python.org/mailman/listinfo/python-list > Reaganomics? 1/2 + 1/2 + 1/2 = 100%? Interesting concept... Oh, vi/vim user here, too =) -- Computers are like air conditioners... They quit working when you open Windows. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rcdailey at gmail.com Fri Jul 6 11:43:55 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 06 Jul 2007 15:43:55 -0000 Subject: Expandable 2D Dictionaries? Message-ID: <1183736635.415927.208450@57g2000hsv.googlegroups.com> Hi, I am interested in creating an expandable (dynamic) 2D dictionary. For example: myvar["cat"]["paw"] = "Some String" The above example assumes "myvar" is declared. In order for this to work, I have to know ahead of time the contents of the dictionary. For the above to work, my declaration must look like: myvar = {"cat": {"paw":""} } I would like to not have to declare my dictionary like this, as it does not allow it to be expandable. I'm very new to Python (I'm a professional C++ programmer. Any comparisons to C++ would help me understand concepts). Is there a way that when I index into my dictionary using an "unknown" index (string), that python will dynamically add that key/value pair? Thanks. From nospam.themindstorm at gmail.com Tue Jul 24 20:55:17 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Wed, 25 Jul 2007 00:55:17 +0000 (UTC) Subject: classmethod & staticmethod References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> <46a5b2ad$0$18903$426a74cc@news.free.fr> Message-ID: Neil Cerutti wrote in news:eRwpi.36813$G23.28496 @newsreading01.news.tds.net: > On 2007-07-25, Alex Popescu wrote: >> As a matter of style, how do you figure out that class_list is >> a class attribute and not an instance attribute? (I don't >> remember seeing anything in the PEP describing the coding >> style). > > Check out dir(MyClass) and dir(MyClass()) for some insight, if it > turns out that it matters. I must confess that I am a bit confused by this advise, as both are returning exactly the same thing. > Preferably, the user of a class > doesn't have to really think about it much. > I know that this would be prefered, but in case you are getting 3rd party code and you modify a class attribute without knowing it is a class attribute then you may get into trouble (indeed the real problem is with the designer of the 3rd party code, but still I think it is a valid concern). tia, ./alex -- .w( the_mindstorm )p. From hexamorph at gmx.net Tue Jul 31 16:45:09 2007 From: hexamorph at gmx.net (Hexamorph) Date: Tue, 31 Jul 2007 22:45:09 +0200 Subject: Iteration over strings In-Reply-To: <46AF9B2D.8040501@jayloden.com> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> <46AF7A49.3040804@jayloden.com> <46AF8046.7090702@gmx.net> <496954360707311307y7d503b8eybd72795c8e699104@mail.gmail.com> <46AF9B2D.8040501@jayloden.com> Message-ID: <46AF9F55.20105@gmx.net> Jay Loden schrieb: > > I have to agree with you WRT to the Python documentation, it does tend to be lacking and difficult to find things at times. In this case the two ways I can think of to look for something like this would have been: Hmm, I find the Python documentation just excellent. You are searching for a *string* related problem? Then just check the *string* class. Also try the dir() function, like dir(some_string_variable) If you come from a C++ background this should be familar to you. Check the appropriate class before trying some "procedural" way. Anyway, glad we could help :) From wojciech_mula at poczta.null.onet.pl.invalid Sun Jul 22 17:22:21 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?iso-8859-2?Q?Mu=B3a?=) Date: Sun, 22 Jul 2007 21:22:21 +0000 (UTC) Subject: custom plugin architecture: how to see parent namespace? References: <1185113192.049692.258310@k79g2000hse.googlegroups.com> Message-ID: escalation746 wrote: > def ViewValuable(): ^^^^^^^^^^^^ [...] > code = """ > Hello() > Plus() > Valuable() ^^^^^^^^ > """ These names don't match. I replaced Valuable() with proper name, and everything work fine. w. From davefowler at gmail.com Fri Jul 20 15:30:03 2007 From: davefowler at gmail.com (godavemon) Date: Fri, 20 Jul 2007 19:30:03 -0000 Subject: path error In-Reply-To: <1184957147.140331.74420@i38g2000prf.googlegroups.com> References: <1184956953.317214.69370@i38g2000prf.googlegroups.com> <1184957147.140331.74420@i38g2000prf.googlegroups.com> Message-ID: <1184959803.054756.162560@i13g2000prf.googlegroups.com> On Jul 20, 11:45 am, godavemon wrote: > On Jul 20, 11:42 am, godavemon wrote: > > > I'm on an intel macbook using OS X 10.4 and for some reason my path is > > being interpreted incorrectly. See the example: > > > dave at jared3-jared$ pwd > > /Users/dave/til/jared <----- dirname = jared > > dave at jared3-jared$ python > > ...>>> import os > > >>> os.path.abspath('') > > > '/Users/dave/til/Jared' <----- dirname = Jared > > > python is capitalizing my jared directory. It has worked for a long > > time but suddenly doesn't. I'm working on the project over SVN, could > > it be some kind of incompatibility with someone who submitted using > > windows or something? Any solutions for this? > > Also my python version is > > Python 2.4.4 (#1, Oct 18 2006, 10:34:39) > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > Type "help", "copyright", "credits" or "license" for more information. I deleted the directory and updated. It fixed the problem. Still an odd one, but not a problem anymore. From __peter__ at web.de Thu Jul 5 04:07:07 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Jul 2007 10:07:07 +0200 Subject: import mysteries References: Message-ID: David Abrahams wrote: > > on Wed Jul 04 2007, Peter Otten <__peter__-AT-web.de> wrote: > >>>> Explicitly passed, see >>>> >>>> >> http://genshi.edgewall.org/browser/trunk/genshi/filters/tests/transform.py >>> >>> IIRC I ran doctest on the file I cited, not the one you're pointing >>> at. Is there some new magic doctest feature I should know about? >> >> Had you looked at it > > Gimme a little credit, please! Of course I looked at it. Sorry. >> you'd seen that the file I pointed to is the driver >> script for running the doctests in the file you pointed to > > Yes, I saw that, but I don't know of any magic feature that causes the > driver script to get loaded when I invoke doctest directly on the file > I pointed to. Nor do I. >> -- unfortunately they have the same name. [...]/tests/transform.py >> does indeed inject a HTML object into the globals of >> [...]/filters/transform.py before it runs the tests. > > Yes, I saw that, but as I said... > > Anyway, maybe I just got confused and doctest-ed the driver script. > That certainly would explain everything. Compelling assumption because it does away with the mystery... Peter From nagle at animats.com Tue Jul 3 13:50:05 2007 From: nagle at animats.com (John Nagle) Date: Tue, 03 Jul 2007 17:50:05 GMT Subject: object references/memory access In-Reply-To: <1183263521.729853.22430@q75g2000hsh.googlegroups.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <7xps3c93b2.fsf@ruckus.brouhaha.com> <1183263521.729853.22430@q75g2000hsh.googlegroups.com> Message-ID: dlomsak wrote: > Paul Rubin wrote: > >>dlomsak writes: >> >>>knowledge of the topic to help. If the above are not possible but you >>>have a really good idea for zipping large amounts of data from one >>>program to another, I'd like to hear it. > Well, I was using the regular pickle at first but then I switched to > just using repr() / eval() because the resulting string doesn't have > all the extra 's1=' and all that so it cuts down on the amount of data > I have to send for large returns when you cut out all of that > formatting. The speed of the above method is pretty high even for > really large returns and it works fine for a list of dictionaries. OK, that's where the time is going. It's not the interprocess communication cost, it's the marshalling cost. "repr/eval" is not an efficient way to marshall. Try using "pack" and "unpack", if you control both ends of the connection. John Nagle From mail at microcorp.co.za Mon Jul 23 02:54:33 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 23 Jul 2007 08:54:33 +0200 Subject: Pickled objects over the network References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com><011401c7caa0$3e3e5900$03000080@hendrik> <012901c7cb60$5ba530c0$03000080@hendrik> <00c601c7cc38$d826ba00$03000080@hendrik> Message-ID: <00bd01c7ccf6$8fa62540$03000080@hendrik> "Steve Holden" wrote: > Yes. Why? - Hendrik From steve at holdenweb.com Tue Jul 17 16:26:04 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 17 Jul 2007 16:26:04 -0400 Subject: Can a low-level programmer learn OOP? In-Reply-To: <7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com> References: <7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com> Message-ID: Wolfgang Strobl wrote: > Steve Holden : > >> I'm happy you are proceeding with so little trouble. Without wishing to >> confuse you, however, I should point out that this aspect of Python has >> very little to do with its object-orientation. There was a language >> called Icon, for example, 20 years ago, that used similar semantics but >> wasn't at all object-oriented. > > Actually, there was a language called SNOBOL, 40 years ago, that used > similar semantics, developed by Griswold et al. Its object model was > remarkably similar to that of Python without classes. And it even had > dictionaries (called "tables") :-). > > For an explaination of the concept "variable" in SNOBOL see > > > SNOBOLs powerfull patterns still shine, compared to Pythons clumsy > regular expressions. I've used the language a lot in the past, first on > the mainframe (SPITBOL on System/360), later on the PC (Catspaws SNOBOL4 > &SPITBOL). When I switched to Python, it wasn't because of the > expressiveness of the language, but of the rich library ("batteries > included") and the IMO elegant syntax, i.e. blocks by identation. > > > > > Icon came later. Griswold developed Icon as a successor to SNOBOL, > constructing it around the concept of generators and co-expressions. I > didn't like it. > > I liked Icon quite a lot, despite having a large background in SNOBOL (my undergrad final-year project was porting the SPITBOL implementation to the DECSystem-10). I wrote email parsing software in Icon long before anyone was doing it in Python. It took a little bit more careful planning to get Icon pattern-matching structures right, but there was much more explicit control of backtracking. I only wish they'd grafted more OO concepts into it, then I might never have bothered with Python! Someone did do an OO system layered on top of it, but IIRC it was clumsy and rebarbative. 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 bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jul 23 04:25:16 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 23 Jul 2007 10:25:16 +0200 Subject: decorators tutorials In-Reply-To: <1185178383.499234.299850@z24g2000prh.googlegroups.com> References: <1185178383.499234.299850@z24g2000prh.googlegroups.com> Message-ID: <46a465ec$0$24899$426a74cc@news.free.fr> james_027 a ?crit : > Hi, > > I am learning python by learning django, and I stumble upon decorator > which is very cool, any beginners resources for python decorators, > although I can google it, I just want to get a good tutorial for this > topic. You should find answers on python.org, and searching this newsgroup. From http Thu Jul 26 14:56:45 2007 From: http (Paul Rubin) Date: 26 Jul 2007 11:56:45 -0700 Subject: Why PHP is so much more popular for web-development References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> <13ahh6kosqqeba1@corp.supernews.com> Message-ID: <7xlkd3m1si.fsf@ruckus.brouhaha.com> Jeffrey Froman writes: > Consider a PHP-based CMS that allows users to upload files. Because the > application runs as the webserver user, uploaded files, and the directory > where they reside, must be accessible and writable by that user. It is the > same user that any other hosting customer on that machine has access to. > Thus, any user on the shared host could write a quick CGI script that > accesses, adds, removes, or defaces your uploaded content. That sounds trivial to ameliorate (at least somewhat) by putting your uploads in a directory whose name is known only to you (let's say it's a random 20-letter string). The parent directory can be protected to not allow reading the subdirectory names. From jayharvard at gmail.com Tue Jul 17 08:54:57 2007 From: jayharvard at gmail.com (jayharvard at gmail.com) Date: Tue, 17 Jul 2007 12:54:57 -0000 Subject: Binary blobs to jpeg In-Reply-To: <1184630056.809650.34070@g4g2000hsf.googlegroups.com> References: <1184612270.455699.254560@r34g2000hsd.googlegroups.com> <1184612920.610854.226290@57g2000hsv.googlegroups.com> <139nhcpl4jk7he6@corp.supernews.com> <1184630056.809650.34070@g4g2000hsf.googlegroups.com> Message-ID: <1184676897.169960.94780@m37g2000prh.googlegroups.com> On Jul 16, 7:54 pm, jayharv... at gmail.com wrote: > On Jul 16, 3:23 pm, Grant Edwards wrote: > > > > > > > On 2007-07-16, jayharva... at gmail.com wrote: > > > >> Have you tried to open the file in "wb" mode? > > > > The data is coming from a record set selection from the Access > > > database. I guess I could write the data to a temp file and > > > open that file handle with the "wb" mode. But, no, I haven't > > > tried that. > > > I think you missed the point. > > > When you want to write the binary data to a file, you must open > > the destination file using "wb" mode. It's binary data, not > > text data, so you have to open the output file in binary mode. > > > -- > > Grant Edwards grante Yow! Is my fallout shelter > > at termite proof? > > visi.com > > I did miss the point. I will give that a shot. Thanks Carsten and Grant- Hide quoted text - > > - Show quoted text - This worked fantastically. Thanks! From brotherjenos at gmail.com Fri Jul 20 11:29:46 2007 From: brotherjenos at gmail.com (Walker Lindley) Date: Fri, 20 Jul 2007 08:29:46 -0700 Subject: Pickled objects over the network In-Reply-To: <011401c7caa0$3e3e5900$03000080@hendrik> References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com> <011401c7caa0$3e3e5900$03000080@hendrik> Message-ID: <9c8d48280707200829v7c14749em2e350da7eb63dd99@mail.gmail.com> It is feasible to an extent since loading each builtin object type is handled by a different function. However, as others have pointed out it makes more sense to use a more robust protocol than try to patch pickle. -Walker On 7/20/07, Hendrik van Rooyen wrote: > > Walker Lindley wrote: > > >Right, I could use Pyro, but I don't need RPC, I just wanted an easy way > to > send objects across the network. I'm sure >both Pyro and Yami can do that > and I > may end up using one of them. For the initial version pickle will work > because > we >have the networking issues figured out with it, just not the security > problem. So we may end up just sending strings back >and forth that will > let us > fill out an object's member variables on the other end. It's much less > cool, but > it seems like it'd >be more secure. > > > > This passing of a pickled structure is so handy for simple things like > lists of > parameters, and so on, that I wonder if it would not be worth while to > somehow > beef up the security of the pickle stuff. > > One heretical way I can think of would involve strict "typing" at the > receiving > end - if you expect say a dict, then you should somehow specify that > anything > else should fail... > > as dict my_received_dict = cpickle.loads(data_from_network) > > or, better without a new "as" keyword: > > my_received_dict=cpickle.loads(data_from_network,type=dict) > > Is this at all feasible? > > - Hendrik > > -- > http://mail.python.org/mailman/listinfo/python-list > -- 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: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 31 10:29:59 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 31 Jul 2007 16:29:59 +0200 Subject: get directory and file names In-Reply-To: <1185891786.452267.57120@57g2000hsv.googlegroups.com> References: <1185891786.452267.57120@57g2000hsv.googlegroups.com> Message-ID: <46af475f$0$23934$426a74cc@news.free.fr> Alchemist a ?crit : > I am working with Python 2.5 on Windows XP (SP2). > > How can I traverse a folder, loop through a list of files and get > their file name and extension in an elegant, pythonic way? http://docs.python.org/lib/module-os.path.html http://docs.python.org/lib/os-file-dir.html (=> os.walk) From bulliver at badcomputer.org Sat Jul 14 13:49:48 2007 From: bulliver at badcomputer.org (darren kirby) Date: Sat, 14 Jul 2007 11:49:48 -0600 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: <200707141149.48885.bulliver@badcomputer.org> quoth the Wayne Brehaut: > (I started with Royal McBee LGP 30 machine language (hex input) in > 1958, and their ACT IV assembler later! Then FORTRAN IV in 1965. By > 1967 I too was using (Burroughs) Algol-60, and 10 years later upgraded > to (DEC-10) Simula-67.) > > Going---going--- Mel? Is that you? http://www.pbm.com/~lindahl/mel.html -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 nospam.themindstorm at gmail.com Tue Jul 24 04:24:05 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Tue, 24 Jul 2007 08:24:05 +0000 (UTC) Subject: Subclassing int References: <4a7f84ac0707231803x7083a688kc91965a5d78e679@mail.gmail.com> Message-ID: G wrote in news:4a7f84ac0707231803x7083a688kc91965a5d78e679 at mail.gmail.com: > ------=_Part_187401_13883248.1185238999144 > Hi, > > I am trying to subclass int to allow a constructor to accept None. > I am > trying the following > > class INT(int): > def __init__(self, x): > if x is None: > return None > else: > int.__init__(x) > > b = INT(x=None) > > When i run the previous code i get the following error: > b = INT(x=None) > TypeError: int() argument must be a string or a number, not > 'NoneType'. > > Do you guys know why the if statement is not evaluated? > > Thanks for your help > Afaik __init__ must not return something. It is __new__ where you can do these kind of tricks. bests, ./alex -- .w( the_mindstorm )p. From escalation746 at yahoo.com Sun Jul 22 17:06:52 2007 From: escalation746 at yahoo.com (escalation746) Date: Sun, 22 Jul 2007 14:06:52 -0700 Subject: custom plugin architecture: how to see parent namespace? In-Reply-To: <1185133004.233815.268980@w3g2000hsg.googlegroups.com> References: <1185113192.049692.258310@k79g2000hse.googlegroups.com> <1185133004.233815.268980@w3g2000hsg.googlegroups.com> Message-ID: <1185138412.035209.171590@q75g2000hsh.googlegroups.com> faulkner wrote: > sys._getframe(1).f_locals Brilliant. That one's pretty well hidden and labeled "should be used for internal and specialized purposes only". Guess I'm officially special. :-) To implement this with minimal requirements on the author of the plugin, I created a function in master.py: def GetKey(): ns = sys._getframe(2).f_locals return ns['VALUABLE'] Now the plugin gets the useful info simply: import master print master.GetKey() Though it would be nice if this info could somehow be "injected" into the namespace of plugin.py without this, I can live with two lines. Thanks! -- robin From semanticist at gmail.com Mon Jul 16 22:03:16 2007 From: semanticist at gmail.com (Miles) Date: Mon, 16 Jul 2007 19:03:16 -0700 Subject: In a dynamic language, why % operator asks user for type info? In-Reply-To: <1184631007.920803.147790@j4g2000prf.googlegroups.com> References: <1184631007.920803.147790@j4g2000prf.googlegroups.com> Message-ID: <1184637796.380676.99100@57g2000hsv.googlegroups.com> On Jul 16, 8:10 pm, Karthik Gurusamy wrote: > Since % by definition is string formatting, the operator should be > able to infer how to convert each of the argument into strings. In addition to what Dan mentioned, you can use "%s" with any object to perform an automatic string conversion. >>> '%s %s %s %s' % ('Hello!', 3.14, 42+1j, object()) 'Hello! 3.14 (42+1j) ' -Miles From deets at nospam.web.de Mon Jul 9 10:28:15 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jul 2007 16:28:15 +0200 Subject: A clean way to program an interface References: <1183957402.819499.227350@o11g2000prd.googlegroups.com> <5feidnF3au460U1@mid.uni-berlin.de> <1183989399.366239.250850@g4g2000hsf.googlegroups.com> Message-ID: <5feuvvF3bcgoiU1@mid.uni-berlin.de> rh0dium wrote: > On Jul 9, 3:53 am, "Diez B. Roggisch" wrote: >> THROW IT AWAY!!!! >> >> Seriously. That's one of the most convoluted, incomprehensible pieces of >> python I've seen. Ever. >> >> All the sys._getframe()-stuff has to go. Really. There are about a dozen >> pieces of code worldwide that are allowed to have that in them. Maybe two >> dozen. >> >> And while I'm having difficulties grasping what you actually mean by " I >> represent each function as a class or should I keep the code >> I have below?", I've done my fair share of serial programming. And I >> would >> say that having one class that exposes different methods for commands is >> the way to go. >> >> But first - throw that code away. Fast. Faster. >> >> Diez > > Hi Diez, > > Totally understand your confusion with sys._getframe().f_code.co_name > - that was borne out of the fact that I was creating a method for each > serial function and it was repeating.. over and over.. > So I got tired > of changing the three items that differentiated each method so I > simplified it a bit. Perhaps too much. I can't say that it has become simpler... It would have been if you at least created a function for it. But even then, it's certainly the wrong way to go. > So can I ask you to show or > point me to a good interface example? I think we both can agree that > fundamentally this is pretty simple but I want to do it right and an > solid class example of interface programming would be nice. I don't understand what you mean by "interface programming". If you tell us how the serial protocol works, and what it accomplishes, one might come up with a clean solution. But that depends on the actual protocol. Diez From silfheed at gmail.com Wed Jul 25 04:23:25 2007 From: silfheed at gmail.com (Silfheed) Date: Wed, 25 Jul 2007 08:23:25 -0000 Subject: how to get next month string? In-Reply-To: <1185319554.711890.138180@z24g2000prh.googlegroups.com> References: <1185279342.863711.246700@d30g2000prg.googlegroups.com> <1185319554.711890.138180@z24g2000prh.googlegroups.com> Message-ID: <1185351805.611580.28380@j4g2000prf.googlegroups.com> Sounds like a job for dateutil (http://labix.org/python-dateutil). It's not a built in module (it's in the cheeseshop at least), but it looks like it pretty much does exactly what you want. If you really dont want to download anything, I suppose you could create something from datetime's timedeltas which do support arithmetic operations. From timr at probo.com Mon Jul 30 00:35:44 2007 From: timr at probo.com (Tim Roberts) Date: Mon, 30 Jul 2007 04:35:44 GMT Subject: 128 or 96 bit integer types? References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com> <1185562901.206212.52570@j4g2000prf.googlegroups.com> <1185607142.096574.209200@e16g2000pri.googlegroups.com> <37pma35qhpca41cvgjfrdkdoru27rgml9s@4ax.com> Message-ID: John DeRosa wrote: >On Sat, 28 Jul 2007 00:19:02 -0700, "mensanator at aol.com" > wrote: > >>For example, how many ways can you put 492 marbles into >>264 ordered bins such that each bin has at least 1 marble? >> >>The answer >> >>66189415264331559482776409694993032407028709677550 >>59629130019289014193777349831417543311612293951363 >>4124491233746912456893016976209252459301489030 > >You missed that blue one in the corner... He lost that one to a talented 12-year-old with a keen eye and a well-balanced steelie... -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bbxx789_05ss at yahoo.com Tue Jul 24 21:22:28 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 24 Jul 2007 18:22:28 -0700 Subject: printing unicode strings In-Reply-To: <1185317177.315543.187160@x40g2000prg.googlegroups.com> References: <1185310571.173514.240940@r34g2000hsd.googlegroups.com> <1185317177.315543.187160@x40g2000prg.googlegroups.com> Message-ID: <1185326548.061565.230410@k79g2000hse.googlegroups.com> Thanks. From wikicodia at gmail.com Fri Jul 27 09:14:36 2007 From: wikicodia at gmail.com (Wikicodia Admin) Date: Fri, 27 Jul 2007 13:14:36 -0000 Subject: Wikicodia - The code snippets wiki Message-ID: <1185542076.188208.70040@d55g2000hsg.googlegroups.com> Dears, Wikicodia is a wiki based project for sharing code snippets. We're collecting large number of code snippets for all code-based programming languages, scripts, shells and consoles. We wish you could help us. We're still BETA. Your suggestions, ideas and criticisms are very welcomed. We're waiting for you contributions. You can easily share and search our snippet using our Google Desktop Gadget. Share your Python snippets to help the world :) http://www.wikicodia.com Thanks Wikicodia Admin From JHoover at fbi.gov Thu Jul 26 00:11:54 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Thu, 26 Jul 2007 00:11:54 -0400 Subject: idiom for RE matching In-Reply-To: <87hcnrj2of.fsf@benfinney.id.au> References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> <1185157313.356112.159020@z24g2000prh.googlegroups.com> <2f6dnUlUxd2_7TjbnZ2dnUVZ_qy3nZ2d@comcast.com> <87hcnrj2of.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > > Not that I want to pick on you; I just don't want something wrong > labelled as "proper" to go unchallenged in the archives :-) Oh gawd :-P I swear I have it right in the actual file! heh. Copy and paste something that's compiled kids, copy and paste. From adonis at REMOVETHISearthlink.net Mon Jul 2 18:33:28 2007 From: adonis at REMOVETHISearthlink.net (Adonis Vargas) Date: Mon, 02 Jul 2007 22:33:28 GMT Subject: Correct abstraction for TK In-Reply-To: <1183412267.513714.183800@q75g2000hsh.googlegroups.com> References: <1183412267.513714.183800@q75g2000hsh.googlegroups.com> Message-ID: luke.hoersten at gmail.com wrote: > I'm looking for a good example of how to correctly abstract TK code > from the rest of my program. I want to just get some user info and > then get 4 values from the GUI. Right now I've written it OOP per the > examples on python.org but it doesn't seem to be meshing very well > with the rest of my project. > > Can anyone suggest some examples so that I can get more ideas? > > Thanks, > Luke > I would not consider this to be 'correct' as many have different philosophies on how to tackle certain projects. My way of doing programming with GUI is writing it in 'tiers' (using this word loosely). i.e. import Tkinter as tk class UsersInfo: pass class Events(UserInfo): pass class GUI(Events): pass This way your GUI class sends events to the Events class to act upon the UserInfo class. For the GUI class here all you do is code the actual display and the callbacks only. Then in the Events class you code the actions you want to happen when you interact the the GUI. Since the GUI class inherits the Events class, in the GUI class you would simply call a method found in the Events class when an event is triggered. Now the Events class which inherits the UserInfo class, you can start using the class to store/modify the user data you desire. Now your code is separated into more comprehensible, and easier to manage sections. In this example I am using inheritance, but if you prefer delegation, then that too can be done here. Also, by doing this it will simplify the moving to more robust graphic toolkits with little modification. Hope this helps. Adonis From mail at microcorp.co.za Fri Jul 13 02:37:00 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 13 Jul 2007 08:37:00 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net><46863ea7$0$970$426a34cc@news.free.fr><1i0ikru.1uccqtm1efnzn3N%aleax@mac.com><1i0n0tr.ve0o791347ugyN%aleax@mac.com><7xd4za1086.fsf@ruckus.brouhaha.com><5f0mhuF3b0stbU1@mid.individual.net><7xd4z837e2.fsf@ruckus.brouhaha.com><468b7426$0$9063$426a34cc@news.free.fr><7x4pkkun56.fsf@ruckus.brouhaha.com><1183575597.272150.152200@w5g2000hsg.googlegroups.com><7xzm2budfv.fsf@ruckus.brouhaha.com><7xir8vju1l.fsf@ruckus.brouhaha.com><7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: <004a01c7c518$380cd300$03000080@hendrik> "Donn Cave" wrote: >In its day, goto was of course very well loved. Does anybody know for sure if it is in fact possible to design a language completely free from conditional jumps? At the lower level, I don't think you can get away with conditional calls - hence the "jumps with dark glasses", continue and break. I don't think you can get that functionality in another way. Think of solving the problem of reading a text file to find the first occurrence of some given string - can it be done without either break or continue? (given that you have to stop when you have found it) I can't think of a way, even in assembler, to do this without using a conditional jump - but maybe my experience has poisoned my mind, as I see the humble if statement as a plethora of local jumps... - Hendrik From kyosohma at gmail.com Fri Jul 20 17:14:18 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 20 Jul 2007 21:14:18 -0000 Subject: Images in Tkinter In-Reply-To: <1184949437.876063.78860@w3g2000hsg.googlegroups.com> References: <1184949437.876063.78860@w3g2000hsg.googlegroups.com> Message-ID: <1184966058.083008.180520@g4g2000hsf.googlegroups.com> On Jul 20, 11:37 am, "Viewer T." wrote: > I wrote a class in which I have to use Tkinter images. When I create > an image object in the class and reference it with the image attribute > of label within the class, it does not dhow the image. It just shows a > blank label that conforms to the size of the image. My images is a GIF > image. > > My code takes the form: > class Login: > def __init__(self): > create image object and other things necessary for class > initialisation > self.make_widgets > def make_widgets(self): > Then I create my widgets > > Then, I instantiate the login class. > > I use Python 2.5. Does anyone have any idea why my imae does not > diplay itself? I have tried using the image before outside a class and > it works! Also, I tried creating the image object outside class but it > gives a runtime error saying it is too early to create an image > object. Please help! This might be the problem: http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm Mike From philr at aspexconsulting.co.nz Wed Jul 11 21:20:27 2007 From: philr at aspexconsulting.co.nz (Phil Runciman) Date: Thu, 12 Jul 2007 13:20:27 +1200 Subject: S2K DTS and Python In-Reply-To: <1184093190.699539.260600@22g2000hsm.googlegroups.com> References: <1184093190.699539.260600@22g2000hsm.googlegroups.com> Message-ID: -----Original Message----- From: stefaan [mailto:stefaan.himpe at gmail.com] Sent: Wednesday, 11 July 2007 6:47 a.m. To: python-list at python.org Subject: Re: S2K DTS and Python > > However, I now want to update some tables in MSAccess, and it occurred > > to me that because Sequel Server 2000 DTS can interface with scripting > > languages that maybe I could call my first Python program from within > > DTS and then update the tables using DTS. (I am learning DTS hence the > > idea). I have never heard about DTS, so I cannot advise you on that. But since you mentioned MsAccess, I want to mention that I have successfully used the DejaVu object relational mapper[1] to access MsAccess databases. Other ORMs like SqlObject and SqlAlchemy - to the best of my knowledge - do not support MsAccess out of the box (yet?). [1] http://projects.amor.org/docs/dejavu/1.5.0RC1/ Thanks Stefaan, I will remember DejaVu. It will be useful as I am in an MS shop. From james.harris.1 at googlemail.com Thu Jul 5 15:56:10 2007 From: james.harris.1 at googlemail.com (James Harris) Date: Thu, 05 Jul 2007 12:56:10 -0700 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <5f31fvF3asl6lU1@mid.individual.net> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <138jml0ldeucf32@corp.supernews.com> <1183576255.668414.256990@q69g2000hsb.googlegroups.com> <5f31fvF3asl6lU1@mid.individual.net> Message-ID: <1183665370.643503.157060@m36g2000hse.googlegroups.com> On 5 Jul, 02:53, greg wrote: > James Harris wrote: > > With that the time would range to +/- 9000 > > quintillion years (18 digits) > > Use the Big Bang as the epoch, and you won't have > to worry about negative timestamps. Good idea if only they didn't keep shifting the femtosecond on which it happened...... :-) From andreengels at gmail.com Thu Jul 12 10:24:23 2007 From: andreengels at gmail.com (Andre Engels) Date: Thu, 12 Jul 2007 16:24:23 +0200 Subject: web page text extractor In-Reply-To: <6faf39c90707120723t8f8188chb131779e66eaf971@mail.gmail.com> References: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> <6faf39c90707120723t8f8188chb131779e66eaf971@mail.gmail.com> Message-ID: <6faf39c90707120724t3fef472ci6e87105b021b1b2c@mail.gmail.com> 2007/7/12, Andre Engels : I forgot to include import urllib2, re here > def textonly(url): > # Get the HTML source on url and give only the main text > f = urllib2.urlopen(url) > text = f.read() > r = re.compile('\<[^\<\>]*\>') > newtext = r.sub('',text) > while newtext != text: > text = newtext > newtext = r.sub('',text) > return text -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From a.schmolck at gmail.com Wed Jul 11 00:28:17 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Wed, 11 Jul 2007 05:28:17 +0100 Subject: bool behavior in Python 3000? References: Message-ID: Steven D'Aprano writes: > I mean, really, does anyone *expect* True+True to give 2, or that 2**True > even works, without having learnt that Python bools are ints? I doubt it. Sure, why not? It's pretty damn useful. Ever heard of things like "indicator functions", "Iverson brackets" etc.? Mathematicians have long been using broken and cumbersome ad hoc notations to be able to do stuff like ``(x> true+true ans = 2 so certainly people coming from matlab to scipy *will* often expect True+True == 2. I'd claim that even if it weren't for backwards compatibility, python bools should behave exactly as they are -- for a language that assigns a truth value to instances of any type, this is the right behavior. 'as From no at no.no Fri Jul 13 08:05:29 2007 From: no at no.no (Daniel) Date: Fri, 13 Jul 2007 15:05:29 +0300 Subject: Getting values out of a CSV References: <1184295593.638409.22910@22g2000hsm.googlegroups.com> Message-ID: >> > Note that every time you see [x for x in ...] with no condition, you >> can >> > write list(...) instead - more clear, and faster. >> > >> > data = list(csv.reader(open('some.csv', 'rb'))) >> >> Faster? No. List Comprehensions are faster. > > kelvie at valour pdfps $ python -m timeit -c 'data = list(open("make.ps"))' > 100 loops, best of 3: 7.5 msec per loop > kelvie at valour pdfps $ python -m timeit -c 'data = [line for line in > open("make.ps")]' > 100 loops, best of 3: 9.2 msec per loop > > On my system just putting into a list is faster. I think this is > because you don't need to assign each line to the variable 'line' each > time in the former case. > > I, too, think it's faster to just use list() instead of 'line for line > in iterable', as it seems kind of redundant. > $ python -m timeit -c 'import csv; data = list(csv.reader(open("some.csv", "rb")))' 10000 loops, best of 3: 44 usec per loop $ python -m timeit -c 'import csv; data = [row for row in csv.reader(open("some.csv", "rb"))]' 10000 loops, best of 3: 37 usec per loop I don't know why there seems to be a differece, but I know that list comps are python are very heavily optimised. From sjmachin at lexicon.net Tue Jul 3 19:48:16 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 03 Jul 2007 16:48:16 -0700 Subject: Ask for a password with OptParse In-Reply-To: References: Message-ID: <1183506496.881575.51010@a26g2000pre.googlegroups.com> On Jul 4, 8:50 am, Mariano Mara wrote: > Hi everyone. > I'm building a script with optparse. One of the parameters will be a > password. > How can I code the optparse to accept/handle/format the password so that > the user does not have to write it in plain/visible text in the terminal? > > TIA, > Mariano. If you insist on those "requirements", you don't need to do anything special in the call to optparse. However you do need to (1) do some experimentation to determine the set of non-printing characters that can be entered at the command line and passed though to the application without being changed or "interpreted" by the shell(s) or Python or optparse (2) restrict the password-issuer so that passwords must be composed only from the so-determined set (3) buy some ear plugs to block out the screaming from the users ... Alternatively, change the requirements to something like: (1) check if there is an interactive console/tty [if not, abort] (2) use getpass.getpass to prompt for a password. From steve at holdenweb.com Wed Jul 4 13:38:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Jul 2007 13:38:17 -0400 Subject: ActivePython In-Reply-To: <468BD3C6.4000103@activestate.com> References: <5f0g54F396io7U1@mid.individual.net> <468BD3C6.4000103@activestate.com> Message-ID: Trent Mick wrote: > Frank Swarbrick wrote: [...] > Steve Holden wrote: > > ...the last time I looked the ActivePython distribution > > doesn't allow redistribution at all (i.e. it's not technically open > > source). > > Steve is correct that ActivePython isn't open source. It is free (as in > beer), meaning that it is completely free for you to download, install > and use on as many machines as you want. > Indeed, and a jolly good system it is, too. Saves you loads of time integrating things that are already fully integrated in ActivePython. > As to redistribution: Yes, it is technically correct that you cannot > fully redistribute ActivePython without our permission. However, > ActivePython's license expressly *does* allow you to use the "freezing" > utilities such as "py2exe" and "py2app" -- so you have no worries there. That's going to account for most people's uses for application distribution, I'd have thought, thanks for pointing that out. > For fully embedding Python in an application, in my experience [2] > you'll want to be building your own Python anyway. > > Yup. [...] > [2] Komodo embeds its own Python build for doing a lot of the core > logic. A custom Python build is generally necessary to avoid > cross-talking between Komodo's Python and other possible Pythons > on the system. 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 abigail at abigail.be Wed Jul 25 16:59:49 2007 From: abigail at abigail.be (Abigail) Date: 25 Jul 2007 20:59:49 GMT Subject: I am giving up perl because of assholes on clpm -- switching to Python References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> Message-ID: _ Martha_Jones at tx.net (Martha_Jones at tx.net) wrote on VLXXVI September MCMXCIII in : }} 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. Bullshit. Over 99.9% of the Perl users have never read a single article in comp.lang.perl.misc, and never will. }} 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!!! No longer reading a newsgroup because you don't like the way people act in the group is one thing (and a sensible thing as well), but your action is like switching from coffee to tea because you don't like the people in rec.food.drink.coffee. Abigail -- perl -wle 'print "Prime" if (0 x shift) !~ m 0^\0?$|^(\0\0+?)\1+$0' From steve at holdenweb.com Sun Jul 8 08:49:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 08 Jul 2007 08:49:26 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xir8vju1l.fsf@ruckus.brouhaha.com> References: <5dveb4F360un0U1@mid.individual.net> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steve Holden writes: >>> Python even leaks the index variable of list comprehensions (I've >>> mostly stopped using them because of this), though that's a >>> recognized wart and is due to be fixed. >>> >> Wow, you really take non-pollution of the namespace seriously. I agree >> it's a wart, but it's one I have happily worked around since day one. > > Well, the obvious workaround is just say "list()" > instead of [] so that's what I do. I think I'll start calling you Captain Sensible. But you are right, it does avoid that extra little potential for errors. 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 george.sakkis at gmail.com Fri Jul 20 11:29:07 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Fri, 20 Jul 2007 15:29:07 -0000 Subject: class C: vs class C(object): In-Reply-To: <46a082ed$0$431$426a74cc@news.free.fr> References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> <469f1557$0$26759$426a74cc@news.free.fr> <46a082ed$0$431$426a74cc@news.free.fr> Message-ID: <1184945347.195877.319000@n60g2000hse.googlegroups.com> On Jul 20, 5:40 am, Bruno Desthuilliers wrote: > Aahz a ?crit : > > > In article <469f1557$0$26759$426a7... at news.free.fr>, > > Bruno Desthuilliers wrote: > >> To make a long story short: Python 2.2 introduced a new object model > >> which is more coherent and more powerful than the original one. The old > >> one was kept so far for compatibility reasons, but there's absolutely no > >> reason to use it no more since "new-style" classes can do anything > >> "Classic" classes did and much more. IOW, don't even bother with > >> old-style classes. > > > And I'll make my usual knee-jerk response disagreeing with this. For > > more info, search groups.google.com. > > And you'll still make it harder for newcomers to understand why a lot of > things don't work correctly with their classes. How helpful... > > Aahz, the object model switch happened *years* ago, and it's quite clear > that old style classes have been kept so far for compatibility reasons > only. It's obvious that one doesn't gain *anything* - except compat with > years-old pre-2.2 versions of Python - using old-style classes. So *why* > on earth are you still *advocating* the use of old style classes ?????? FWIW, I am not advocating old style classes and I rarely (if ever) use them in new code, but I occasionally miss the following feature, which by the way disproves the assertion that "new-style classes can do anything Classic classes did": class Classic: pass class NewStyle(object):pass for o in Classic(),NewStyle(): o.__str__ = lambda: 'Special method overriding works on instances!' print '%s object: %s' % (o.__class__.__name__, o) George From vedrandekovic at v-programs.com Thu Jul 5 04:08:58 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Thu, 05 Jul 2007 01:08:58 -0700 Subject: Problem with building extension in Python Message-ID: <1183622938.086813.18950@k79g2000hse.googlegroups.com> Hi, I have already install Microsoft visual studio .NET 2003 and MinGw, when I try to build a extension: python my_extension_setup.py build ( or install ) , I get an error: LINK : fatal error LNK1141: failure during build of exports file error: command '"C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\link.exe"' failed with exit status 1141.What shoud I do??? If you now anything useful, please contact me!! Thanks!!!!!!!!!! From walterbyrd at iname.com Thu Jul 26 08:42:06 2007 From: walterbyrd at iname.com (walterbyrd) Date: Thu, 26 Jul 2007 05:42:06 -0700 Subject: Why PHP is so much more popular for web-development In-Reply-To: <46a7b908$0$32130$426a34cc@news.free.fr> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> <46a7b908$0$32130$426a34cc@news.free.fr> Message-ID: <1185453726.559470.122480@x40g2000prg.googlegroups.com> On Jul 22, 12:17 am, Bruno Desthuilliers wrote: > Either you are a casual user with 101 web > development skills trying to set up your personal home page But this, sort of, brings me back to my original point. Nobody starts out being advanced. There are substantial differences in cost, and deployment, between PHP and Python. It is much easier to get started with PHP. And once somebody has started with PHP, that person is likely to stay with PHP. Most PHP developers do not see a compelling reason to start all over again with Python. BTW: I have a certain amount of respect for PHP, and PHP developers. PHP5 is a big step forward over PHP4. And, there have been substantial web projects completed with PHP - probably more so than with Python. From nospam.themindstorm at gmail.com Tue Jul 24 17:35:58 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Tue, 24 Jul 2007 21:35:58 +0000 (UTC) Subject: classmethod & staticmethod References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> <46a5b2ad$0$18903$426a74cc@news.free.fr> Message-ID: Neil Cerutti wrote in news:slrnfaccgl.1gk.horpner at FIAD06.norwich.edu: > On 2007-07-24, Alex Popescu wrote: >> Bruno Desthuilliers >> wrote in news:46a5b2ad$0$18903$426a74cc at news.free.fr: >> > > [snip...] > >> >> class MyClass(object): >> class_list = ['a', 'b'] >> >> def instance_method(self): >> print "instance_method with class list %s" % class_list > > There's no implicit self or class for Python identifiers. > > The name class_list must be quailified: self.class_list or > MyClass.class_list. > After more investigation I have figured this out by myself, but thanks for the details. Now I am wondering if in the above case there is a prefered way: MyClass.class_list or self.__class__.class_list? (IMO the 2nd is more safe in terms of refactorings). ./alex -- .w( the_mindstorm )p. From steve at holdenweb.com Fri Jul 20 10:14:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Jul 2007 10:14:48 -0400 Subject: Pickled objects over the network In-Reply-To: <011401c7caa0$3e3e5900$03000080@hendrik> References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com> <011401c7caa0$3e3e5900$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > Walker Lindley wrote: > >> Right, I could use Pyro, but I don't need RPC, I just wanted an easy way to > send objects across the network. I'm sure >both Pyro and Yami can do that and I > may end up using one of them. For the initial version pickle will work because > we >have the networking issues figured out with it, just not the security > problem. So we may end up just sending strings back >and forth that will let us > fill out an object's member variables on the other end. It's much less cool, but > it seems like it'd >be more secure. > > This passing of a pickled structure is so handy for simple things like lists of > parameters, and so on, that I wonder if it would not be worth while to somehow > beef up the security of the pickle stuff. > Hmm, I suspect I detect the sounds of the square wheel being reinvented. 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 roy at panix.com Wed Jul 25 10:37:00 2007 From: roy at panix.com (Roy Smith) Date: Wed, 25 Jul 2007 10:37:00 -0400 Subject: How to tell when a socket is closed on the other end? References: <1185371863.622473.205010@19g2000hsx.googlegroups.com> Message-ID: In article <1185371863.622473.205010 at 19g2000hsx.googlegroups.com>, billiejoex wrote: > Hi there. > I'm setting up test suite for a project of mine. > >From test suite, acting as a client, I'd like to know, in certain > situations, if the socket is closed on the other end or not. > I noticed that I can "detect" such state if a call to socket.read() > returns 0 but it seems a little poor to me. :-\ > Is there a reliable way to test such socket 'state'? This isn't really a Python question, it's a Berkeley Socket API question. You don't say, but I assume you're talking about a TCP (i.e. SOCKSTREAM) connection? The answer is you can use the select() system call to detect "exceptional conditions" on a socket. Python's select module provides this functionality, but to understand how to use it, you need to study the underlying API. On the other hand, socket.read() returning 0 works too. What do you find "poor" about that? What do you want to know about the connection being closed that you don't find out by getting 0 back from read()? From thomas.bugzilla at gmx.net Wed Jul 18 06:37:09 2007 From: thomas.bugzilla at gmx.net (Thomas) Date: Wed, 18 Jul 2007 12:37:09 +0200 Subject: XL-RPC Recipe In-Reply-To: References: Message-ID: Ah, sorry, found the answer myself (not that I wasn't looking for it for days...): I was aware that the recipe is online at ActiveState's site (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81549), but I didn't read all of the comments carefully: KAMOSAWA Masao wrote on 2006/04/29 that the use of dotted functions is disabled by default in the server (from Python 2.4 onwards). But it can be enabled with: server.register_instance(StringFunctions(), allow_dotted_names = True) =Thomas From gagsl-py2 at yahoo.com.ar Mon Jul 16 05:22:18 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jul 2007 06:22:18 -0300 Subject: Access Object From 2 Applications or Fix Scheduler References: <015201c7c71a$2be05df0$83a119d0$@rawlins@thinkbluemedia.co.uk> <00a501c7c776$900ba8a0$03000080@hendrik> <21109.4720209532$1184576770@news.gmane.org> Message-ID: En Mon, 16 Jul 2007 06:04:07 -0300, Robert Rawlins - Think Blue escribi?: > Now we may be able to avoid this if there is some type of file watcher > function available in python, my second application could then just watch > the XML file and as soon as a new one is available parse it itself. Is > that > something you've heard of? See this (the first solution works on any platform; others are Windows specific) or try Google with those keywords. -- Gabriel Genellina From stefan.behnel-n05pAM at web.de Sat Jul 28 00:44:06 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 28 Jul 2007 06:44:06 +0200 Subject: Removing certain tags from html files In-Reply-To: <1185558023.501016.90050@d30g2000prg.googlegroups.com> References: <1185558023.501016.90050@d30g2000prg.googlegroups.com> Message-ID: <46AAC996.1090109@web.de> sebzzz at gmail.com wrote: > I'm doing a little script with the help of the BeautifulSoup HTML > parser and uTidyLib (HTML Tidy warper for python). > > Essentially what it does is fetch all the html files in a given > directory (and it's subdirectories) clean the code with Tidy (removes > deprecated tags, change the output to be xhtml) and than BeautifulSoup > removes a couple of things that I don't want in the files (Because I'm > stripping the files to bare bone, just keeping layout information). > > Finally, I want to remove all trace of layout tables (because the new > layout will be in css for positioning). Now, there is tables to layout > things on the page and tables to represent tabular data, but I think > it would be too hard to make a script that finds out the difference. > > My question, since I'm quite new to python, is about what tool I > should use to remove the table, tr and td tags, but not what's > enclosed in it. I think BeautifulSoup isn't good for that because it > removes what's enclosed as well. Use lxml.html. Honestly, you can't have HTML cleanup simpler than that. It's not released yet (lxml is, but lxml.html is just close), but you can build it from an SVN branch: http://codespeak.net/svn/lxml/branch/html/ Looks like you're on Linux, so that's a simple run of setup.py. Then, use the dedicated "clean" module for your job. See the "Cleaning up HTML" section in the docs for some examples: http://codespeak.net/svn/lxml/branch/html/doc/lxmlhtml.txt and the docstring of the Cleaner class to see all the available options: http://codespeak.net/svn/lxml/branch/html/src/lxml/html/clean.py In case you still prefer BeautifulSoup for parsing (just in case you're not dealing with HTML-like pages, but just with real tag soup), you can also use the ElementSoup parser: http://codespeak.net/svn/lxml/branch/html/src/lxml/html/ElementSoup.py but lxml is generally quite good in dealing with broken HTML already. Have fun, Stefan From bbxx789_05ss at yahoo.com Tue Jul 31 03:13:53 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 31 Jul 2007 00:13:53 -0700 Subject: Pysqlite storing file as blob example In-Reply-To: <1185841540.275571.161640@g4g2000hsf.googlegroups.com> References: <1185841540.275571.161640@g4g2000hsf.googlegroups.com> Message-ID: <1185866033.407894.237840@r34g2000hsd.googlegroups.com> On Jul 30, 6:25 pm, rustyhow... at gmail.com wrote: > I'm trying to store binary data in a sqlite database and call into the > db using pysqlite 3. > What I've got so far is this: > > import sqlite > con = sqlite.connect(DB_PATH) > cur = con.cursor() > query = """create table t1( > ID INTEGER PRIMARY KEY, > data BLOB );""" > cur.execute(query) > con.commit() > b = buffer('/path/to/binary/file') buffer() ? >From the docs: ---- There are several built-in functions that are no longer essential to learn, know or use in modern Python programming. They have been kept here to maintain backwards compatibility with programs written for older versions of Python. ... buffer(object[, offset[, size]]) ---- From qilong.ren at gmail.com Fri Jul 13 18:57:31 2007 From: qilong.ren at gmail.com (Qilong Ren) Date: Fri, 13 Jul 2007 15:57:31 -0700 Subject: pyMPI installation Message-ID: <1d3e50f20707131557s7febef07l3592f09ca6b31e1@mail.gmail.com> Hi, All, I tried to install pyMPI on a linux machine with python2.5 and mpich installed. But always failed. Anyone who has succeeded with the installation? What do I need when doing the configuration? Thanks! Qilong -------------- next part -------------- An HTML attachment was scrubbed... URL: From bparkis at gmail.com Wed Jul 11 19:37:25 2007 From: bparkis at gmail.com (bparkis at gmail.com) Date: Wed, 11 Jul 2007 16:37:25 -0700 Subject: testing scapy installation Message-ID: <1184197045.325418.48930@q75g2000hsh.googlegroups.com> I have an installation of scapy on OS X (via macports) and I am trying to determine if it was successful or not. Nothing I do on the network seems to work completely, but on the other hand the installation didn't seem to have run into any trouble so I want to be sure. What test can I do to determine beyond a doubt whether this was a successful installation? I tried pscan.py, which was taken from http://packetstorm.linuxsecurity.com/papers/general/blackmagic.txt bmacbook:~/python bart$ sudo python ./pscan.py 192.168.1.0/24 WARNING: Mac address to reach 192.168.1.0 not found WARNING: Mac address to reach 192.168.1.2 not found WARNING: more Mac address to reach 192.168.1.3 not found and it goes on like that, for 192.168.1.4 and so on. It keep printing error messages even after I ctrl-c the process, I have to close the terminal for it to (apparently) stop. This doesn't look that good, BUT, it does not print a warning when it gets to the ip address of some computer on my local network (such as 192.168.1.1), so maybe something is working. So is there some test I can do that conclusively would show scapy to be working or not working? From kar1107 at gmail.com Mon Jul 2 16:16:51 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Mon, 02 Jul 2007 13:16:51 -0700 Subject: object references/memory access In-Reply-To: <1183318690.661279.256900@n2g2000hse.googlegroups.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> Message-ID: <1183407411.397142.304790@e16g2000pri.googlegroups.com> On Jul 1, 12:38 pm, dlomsak wrote: > Thanks for the responses folks. I'm starting to think that there is > merely an inefficiency in how I'm using the sockets. The expensive > part of the program is definitely the socket transfer because I timed > each part of the routine individually. For a small return, the whole > search and return takes a fraction of a second. For a large return (in > this case 21,000 records - 8.3 MB) is taking 18 seconds. 15 of those > seconds are spent sending the serialized results from the server to > the client. I did a little bit of a blind experiment and doubled the > bytes on the client's socket.recv line. This improved the rate of > transfer each time. The original rate when I was accepting 1024 bytes > per recv took 47 seconds to send the 8.3 MB result. By doubling this > size several times, I reduced the time to 18 seconds until doubling it > further produced diminishing results. I was always under the > impression that keeping the send and recv byte sizes around 1024 is a > good idea and I'm sure that jacking those rates up is a lousy way to > mitigate the transfer. It is also interesting to note that increasing > the bytes sent per socket.send on the server side had no visible > effect. Again, that was just a curious experiment. > > What bothers me is that I am sure sending data over the local loopback > address should be blazing fast. 8.3 MB should be a breeze because I've > transferred files over AIM to people connected to the same router as > me and was able to send hundreds of megabytes in less than a two or > three seconds. With that said, I feel like something about how I'm > send/recv-ing the data is causing lots of overhead and that I can > avoid reading the memory directly if I can speed that up. > > I guess now I'd like to know what are good practices in general to get > better results with sockets on the same local machine. I'm only > instantiating two sockets total right now - one client and one server, > and the transfer is taking 15 seconds for only 8.3MB. If you guys have > some good suggestions on how to better utilize sockets to transfer > data at the speeds I know I should be able to achieve on a local > machine, let me know what you do. At present, I find that using > sockets in python requires very few steps so I'm not sure where I > could really improve at this point. > I have found the stop-and-go between two processes on the same machine leads to very poor throughput. By stop-and-go, I mean the producer and consumer are constantly getting on and off of the CPU since the pipe gets full (or empty for consumer). Note that a producer can't run at its top speed as the scheduler will pull it out since it's output pipe got filled up. When you increased the underlying buffer, you mitigated a bit this shuffling. And hence saw a slight increase in performance. My guess that you can transfer across machines at real high speed, is because there are no process swapping as producer and consumer run on different CPUs (machines, actually). Since the two processes are on the same machine, try using a temporary file for IPC. This is not as efficient as real shared memory -- but it does avoid the IPC stop-n-go. The producer can generate the multi-mega byte file at one go and inform the consumer. The file-systems have gone thru' decades of performance tuning that this job is done really efficiently. Thanks, Karthik > Thanks for the replies so far, I really appreciate you guys > considering my situation and helping out. From gagsl-py2 at yahoo.com.ar Tue Jul 10 19:55:38 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Jul 2007 20:55:38 -0300 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: (Absolutely off topic!) En Mon, 09 Jul 2007 15:50:58 -0300, Steve Holden escribi?: > Brunel, of course, being an original, built his system with a wider > inter-rail gap, and passengers commented on the smoother ride they got. > But standardization wars aren't new, and IKB lost that one. And later the Great Western Railway got the most beautiful locomotives of all times! I don't know the current status, but some years ago here in Argentina around 40% of the railroad system were using "wide gauge" = 1676mm, wider than standard but not as wide as the original GWR. Now most of the passenger lines are defunct and cargo lines trend to use narrow gauge = 1000mm so the proportion may be much smaller now. -- Gabriel Genellina From nick at craig-wood.com Mon Jul 9 04:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 09 Jul 2007 03:30:06 -0500 Subject: "Empty" text References: <469147b8$1@griseus.its.uu.se> <5fd1aeF3berb8U1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Sun, 08 Jul 2007 22:23:20 +0200, Jan Danielsson wrote: > > > The problem is that this generates the following code: > > > > > > Description > > > > > > > > I understand the opitmization ElementTree is performing; but it seems > > there are cases when it is not the proper thing to do. Is it possible to > > force ElementTree to output the XHTML code I need it to? > > Then either Firefox is broken or you don't declare your XHTML properly and > Firefox thinks it's HTML. I suspect the former - we noticed exactly the same thing (can't remember which tags we were having problems with), using the declaration :- I haven't tested this again recently though. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From carsten at uniqsys.com Tue Jul 24 09:16:13 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 24 Jul 2007 09:16:13 -0400 Subject: how to get next month string? In-Reply-To: <1185279342.863711.246700@d30g2000prg.googlegroups.com> References: <1185279342.863711.246700@d30g2000prg.googlegroups.com> Message-ID: <1185282973.3370.6.camel@dot.uniqsys.com> On Tue, 2007-07-24 at 05:15 -0700, John Machin wrote: > On Jul 24, 8:31 pm, "Yinghe Chen" wrote: > > Hi, > > Could someone help on how to use python to output the next month string like > > this? > > > > "AUG07", suppose now is July 2007. > > > > I think also need to consider Dec 07 case, it is supposed to output as > > below: > > "JAN07". > > > > datetime module seems not supporting the arithmatic operations, any hints? > > > > Thanks in advance, > > > > Yinghe Chen > > >>> import datetime > >>> def nextmo(d): > ... mo = d.month > ... yr = d.year > ... mo += 1 > ... if mo > 12: > ... mo = 1 > ... yr += 1 > ... return datetime.date(yr, mo, 1).strftime('%b%y').upper() A more concise variant: >>> import datetime >>> def nextmo(d): ... mo = d.month ... yr = d.year ... nm = datetime.date(yr,mo,1)+datetime.timedelta(days=31) ... return nm.strftime('%b%y').upper() Going 31 days from the first of any month will always get us into the next month. The resulting day of the month will vary, but we're throwing that away with strftime. -- Carsten Haese http://informixdb.sourceforge.net From duncan.booth at invalid.invalid Tue Jul 17 03:27:57 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jul 2007 07:27:57 GMT Subject: The ** operator ambiguous? References: <1184607614.904143.219330@w3g2000hsg.googlegroups.com> <1184628499.822335.256630@d55g2000hsg.googlegroups.com> Message-ID: Paul Boddie wrote: > However, this ambiguous usage of * and ** is one thing I don't recall > appearing on any of the "Python warts" lists It is true that the same punctuation character is used in more than one context, but that is also true for many other punctuation characters. There is no ambiguity. From stargaming at gmail.com Mon Jul 30 13:34:45 2007 From: stargaming at gmail.com (Stargaming) Date: 30 Jul 2007 17:34:45 GMT Subject: Bug? exec converts '\n' to newline in docstrings!? References: Message-ID: <46ae2135$0$24925$9b622d9e@news.freenet.de> On Mon, 30 Jul 2007 11:00:14 -0500, Edward K Ream wrote: >> The problem is because you are trying to represent a Python > program as a Python string literal, and doing it incorrectly. > > Yes, that is exactly the problem. Thanks to all who replied. Changing > changing '\n' to '\\n' fixed the problem. Raw strings (r'this \n will stay') might help, too. See http:// docs.python.org/ref/strings.html#l2h-14 From steve at holdenweb.com Wed Jul 25 14:19:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Jul 2007 14:19:25 -0400 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185385374.866372.198520@x35g2000prf.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> Message-ID: <46A7942D.4030904@holdenweb.com> walterbyrd wrote: > "Once you start down the Dark path, forever will it dominate your > desiny. Consume you, it will." > - Yoda > > I'm fairly new to web-development, and I'm trying out different > technologies. Some people wonder why PHP is so popular, when the > language is flawed in so many ways. To me, it's obvious: it's because > it's much easier to get started with PHP, and once somebody gets > started with a particular language, that person is likely to stay with > that language. > > Before you can even get started with Python web-development, you have > to understand this entire alphabit soup of: CGI, FASTCGI, MOD_PYTHON, > FLUP, WSGI, PASTE, etc. For me, configuring fastcgi has been the most > difficult part of getting django to work. PHP developers don't have to > bother with anything like that. With PHP, you just throw some code in > the middle of your html file. > > Also, PHP, and PHP frameworks, are supported everywhere. If you going > to use a PHP MVC framework, like codeignitor, you would have a hard > time finding a hoster that didn't support it - all you need is php4 > and mysql. Dollar-hosting, for $10 a year, should work just fine with > codeignitor. With codeignitor, just copy your files to whatever host, > and that's it, you're done. > > By contrast, the most popular Python frameworks have sky-high system > requirements. Take a look at the requirements and/or recomendations > for popular Python frameworks like Django, TurboGears, or CherryPy: > Apache 2.0, mod_python (latest version), fastcgi (at least), command > line access, PostgreSQL. And a lot of low-cost hosters don't support > Python at all. > > Don't get me wrong: I am not saying that PHP is better than Python for > web-development. But, I sometimes think that Python could learn a few > things from PHP. > > All JMHO, of course. > Indeed. The reason that PHP is so popular with so many people is that the core language meets most of the simpler requirements for web sites. Most people putting together a site are perfectly happy with something along the lines of PHPNuke. When someone starts to push the limits of PHP they either continue to push until they get where they want to be (producing an ugly or ill-maintained bunch of code along the way) or they choose a more appropriate tool. The latter behavior is typical of programmers. The former is typical of typical users. There are many people producing web sites who I wouldn't let within yards of any of my code. but it's some kind of tribute to PHP that it manages to satisfy so many of them. This doesn't mean that grafting PHP features into Python mindlessly will improve the language. The Python approach is a scalpel, which can easily cut your fingers off. The PHP approach is a shovel, which will do for many everyday tasks. 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 users.sourceforge.net Wed Jul 25 23:33:58 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Thu, 26 Jul 2007 09:03:58 +0530 Subject: Singleton in Python Cookbook In-Reply-To: References: Message-ID: <20070726033358.GC5131@gmail.com> * Alex Popescu [2007-07-25 21:30:14]: > TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of type That's hardly helpful. All I can think about is, SingleSpam is a class and you have to defined the Class in your program, or it could be something else also. > (I haven't presented the original code as I am not sure about copyrights). > If there is an online version of the code, please point to us that. Or you can ask the author of the book directly. -- O.R.Senthil Kumaran http://uthcode.sarovar.org From kyosohma at gmail.com Thu Jul 19 11:51:49 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 19 Jul 2007 15:51:49 -0000 Subject: wxPython, searching, and threads In-Reply-To: <1184789708.351825.224110@x35g2000prf.googlegroups.com> References: <1184789708.351825.224110@x35g2000prf.googlegroups.com> Message-ID: <1184860309.970982.148880@r34g2000hsd.googlegroups.com> On Jul 18, 3:15 pm, Benjamin wrote: > Hello! I am writing a search engine with wxPython as the GUI. As the > search thread returns items, it adds them to a Queue which is picked > up by the main GUI thread calling itself recursively with > wx.CallAfter. These are then added to a ListCtrl. This works fine for > small searches, but with larger and longer searchs the GUI is clogged > and won't respond. I suspect (I may be wrong) that there are so many > results being sent to the ListCtrl that the event loop doesn't have > time to respond to events. I've tried buffering the results before > sending them to the GIU, but that doesn't help at all. Please advise. I think what you need to look at is http://wiki.wxpython.org/LongRunningTasks That's what the people on the wxPython list usually recommend when doing what you're doing. I've used the techniques there and they work great! Mike From no at spam.com Fri Jul 27 17:50:38 2007 From: no at spam.com (Farshid Lashkari) Date: Fri, 27 Jul 2007 14:50:38 -0700 Subject: Another C API Question In-Reply-To: <1185571136.628131.168260@z24g2000prh.googlegroups.com> References: <1185498383.333248.225360@19g2000hsx.googlegroups.com> <1185545488.751250.200270@z24g2000prh.googlegroups.com> <1185571136.628131.168260@z24g2000prh.googlegroups.com> Message-ID: beginner wrote: > I did and it did not seem to work. I ended up doing the following. > Verbose, isn't it? > If I do d=PyFloat_AsDouble(oDiscount); in the third "if", I get an > error. Maybe I missed something obvious. That's strange. I just tried the following code: fprintf(stdout,"True = %lf\n",PyFloat_AsDouble(Py_True)); fprintf(stdout,"False = %lf\n",PyFloat_AsDouble(Py_False)); fprintf(stdout,"5 = %lf\n",PyFloat_AsDouble(PyInt_FromLong(5))); And it printed the following: True = 1.000000 False = 0.000000 5 = 5.000000 What version of Python are you using? From huliang25 at yahoo.com Mon Jul 9 11:26:02 2007 From: huliang25 at yahoo.com (Beethon) Date: Mon, 09 Jul 2007 15:26:02 -0000 Subject: no python install Message-ID: <1183994762.455062.170190@j4g2000prf.googlegroups.com> my computer has no puthon installed i downloaded some sofware that are shiped with .py files please explain how the programs become workable ? thanks From peiyu_chao at yahoo.com.tw Tue Jul 31 07:41:42 2007 From: peiyu_chao at yahoo.com.tw (Pei-Yu CHAO) Date: Tue, 31 Jul 2007 19:41:42 +0800 (CST) Subject: Plotting Images Message-ID: <508774.60673.qm@web72009.mail.tp2.yahoo.com> Hi ALL: I have only been switched from matlab to python few months ago. I having trouble of plotting images from a matrix size of 8x10000 (unfortunately that is the size of my data.....) for example, x = rand(8,10000) inshow(x) I have tried to use matplotlib function imshow(), but all i get is a long thin line (unable to see the color display and the my matrix information). i think imshow() has the same problem in matlab, but i think there is a alternative in matlab, imagesc(). I did search on web about plt.imagesc().....but when i try to run the example code, python just tell me cannot find module plt. >>>from scipy import plt ImportError: cannot import name plt I have installed scipy, wxpython2.6....and it still seem not to work! is there some alternitive? or what have i done wrong? Thank you Pei ____________________________________________________________________________________ ?????????????????????? Yahoo!?????????? http://tw.mobile.yahoo.com/texts/mail.php From jldunn2000 at googlemail.com Tue Jul 10 11:25:15 2007 From: jldunn2000 at googlemail.com (loial) Date: Tue, 10 Jul 2007 15:25:15 -0000 Subject: How to check if file is in use? Message-ID: <1184081115.465263.215830@q75g2000hsh.googlegroups.com> Is there anyway in pythn to check whether a file is being used/written to by another process, e.g like the fuser command? From thomas at jollans.com Thu Jul 5 14:30:10 2007 From: thomas at jollans.com (Thomas Jollans) Date: Thu, 5 Jul 2007 20:30:10 +0200 Subject: Where is the syntax for the dict() constructor ?! In-Reply-To: <468D362C.2@gmail.com> References: <468D1D9D.6060002@gmail.com> <468D362C.2@gmail.com> Message-ID: <200707052030.15139.thomas@jollans.com> On Thursday 05 July 2007, Captain Poutine wrote: > Peter Otten wrote: > > Neil Cerutti wrote: > >> On 2007-07-05, Captain Poutine wrote: > >>> I'm simply trying to read a CSV into a dictionary. > >>> > >>> (if it matters, it's ZIP codes and time zones, i.e., > >>> 35983,CT > >>> 39161,CT > >>> 47240,EST > >>> > >>> > >>> > >>> Apparently the way to do this is: > >>> > >>> import csv > >>> > >>> dictZipZones = {} > >>> > >>> reader = csv.reader(open("some.csv", "rb")) > >>> for row in reader: > >>> # Add the row to the dictionary > >> > >> In addition to Chris's answer, the csv module can read and write > >> dictionaries directly. Look up csv.DictReader and csv.DictWriter. > > > > DictReader gives one dict per row, with field names as keys. The OP is > > more likely to want > > > > dict(csv.reader(open("some.csv", "rb"))) > > > > which produces a dict that maps ZIP codes to time zones. > > > > Peter > > Thanks Peter, that basically works, even if I don't understand it. > > What does "rb" mean? (read binary?) > Why are the keys turned into strings (they are not quoted in the .csv > file)? "rb" is read, in binary mode. On DOS and derivatives this prevents intentional file corruption when reading. (for ASCII files, omitting the b might be desirable...) Think of csv.reader as a fancy variant of the following: (fancy in that it supports things like non-comma separators and comma escaping) def CSVReader(file): for line in file: yield line.split(',') -- 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 ndbecker2 at gmail.com Sun Jul 8 13:59:32 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Sun, 08 Jul 2007 13:59:32 -0400 Subject: python extra Message-ID: Just a little python humor: http://www.amazon.com/Vitamin-Shoppe-Python-Extra-tablets/dp/B00012NJAK/ref=sr_1_14/103-7715091-4822251?ie=UTF8&s=hpc&qid=1183917462&sr=1-14 From the.mindstorm.mailinglist at gmail.com Mon Jul 16 19:13:19 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Mon, 16 Jul 2007 16:13:19 -0700 Subject: how to find available classes in a file ? In-Reply-To: <2e302$469bf38f$d443bb3a$30036@news.speedlinq.nl> References: <2e302$469bf38f$d443bb3a$30036@news.speedlinq.nl> Message-ID: <1184627599.597658.267380@g4g2000hsf.googlegroups.com> On Jul 17, 1:44 am, Stef Mientki wrote: > I want to have a (dynamically) list of all classes defined in a py-file. > Is there a way of getting this list, without manually parsing the file ? > > thanks, > Stef Mientki I have written something that does something like this, but I am not sure it is the pythonic way. Bascially I am loading the module and then using dir() on the module object I am looking for attribute of the type classobj (for old style classes) and type type (for new style classes). I also heard of the inspect module, but I haven't checked it yet. bests, ./alex -- .w( the_mindstorm )p. From kyosohma at gmail.com Thu Jul 12 21:05:23 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 13 Jul 2007 01:05:23 -0000 Subject: wx.App console window [Windows] In-Reply-To: <1184280929.137401.50620@o61g2000hsh.googlegroups.com> References: <1184273064.350399.152490@o61g2000hsh.googlegroups.com> <1184279332.640059.120140@k79g2000hse.googlegroups.com> <1184280929.137401.50620@o61g2000hsh.googlegroups.com> Message-ID: <1184288723.799773.8110@n2g2000hse.googlegroups.com> On Jul 12, 5:55 pm, siw... at gmail.com wrote: > On 13 Lip, 00:28, kyoso... at gmail.com wrote: > > > > > On Jul 12, 3:44 pm, siw... at gmail.com wrote: > > > > Hi All, > > > > I'm looking for a way to hide console window created by wx.App class. > > > > examplary code below: > > > > import wx > > > > class Gui(wx.App): > > > def __init__(self, *pargs, **kwargs): > > > wx.App.__init__(self, *pargs, **kwargs) > > > > if __name__ == "__main__": > > > app = Gui() > > > app.MainLoop() > > > > produces a blank console window (than dies). > > > > What shall I do to make wx.App run without raising console window? > > > > thanks in advance > > > Save the file as a *.pyw. And I would recommend adding the following 2 > > lines to your __init__ : > > > > > > frame = wx.Frame(None, wx.ID_ANY, title='My Title') > > frame.Show() > > > > > > Maybe even stick in a panel object for that matter. > > > Mike > > Thank you Mike, *.pyw made the first part of the trick just perfectly. > Thanks to your answer I was able to ask google proper question > concerning second part. Below (for possible future readers) I attach > solution I found: > > People looking for possibility of running wx.App no console version > after py2exe compilation: > in setup script change 'console = ['foo.py']' for 'windows = ['foo.py'] I like the GUI interface to py2exe that I found here: http://xoomer.alice.it/infinity77/eng/GUI2Exe.html Quite handy. Mike From tn.pablo at gmail.com Mon Jul 2 10:27:35 2007 From: tn.pablo at gmail.com (ptn) Date: Mon, 02 Jul 2007 07:27:35 -0700 Subject: Probably simple syntax error In-Reply-To: <1183367775.360977.201520@m37g2000prh.googlegroups.com> References: <1183351228.878746.233430@o61g2000hsh.googlegroups.com> <1183367775.360977.201520@m37g2000prh.googlegroups.com> Message-ID: <1183386455.746792.154610@q69g2000hsb.googlegroups.com> > > Problem 6: big_randomized_int can only have values in 0, 1, ..., 98, > 99. So small_randomized_int will have the value 0, always. > > Perhaps you meant: > small_randomised_float = big_randomized_int / 100.0 > > > small_randomized_int = Round(small_randomized_int, 2) > > # Round that value to 2 decimal places > PASCAL --> PYTHON 5 div 2 --> 5/2 5 mod 2 --> 5 % 2 5/2 --> 5/2. (Notice the little dot at the end) From kay.schluehr at gmx.net Thu Jul 5 11:06:24 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 05 Jul 2007 08:06:24 -0700 Subject: The best platform and editor for Python In-Reply-To: <1183644537.859604.27790@w5g2000hsg.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183644537.859604.27790@w5g2000hsg.googlegroups.com> Message-ID: <1183647984.671847.134610@r34g2000hsd.googlegroups.com> On Jul 5, 4:08 pm, Nicola Musatti wrote: > On Jul 5, 1:23 pm, Gregor Horvath wrote: > [...] > > > That's a property of open source projects. > > Features nobody really needs are not implemented. > > No, no, you got it all wrong. It's in *commercial* projects that > features nobody really needs are not implemented. Profit is > fundamental in convincing you that you really need the features. > > On the other hand open source projects tend to lack features nobody > enjoys implementing. OSS projects have the healthy tendency to die silently. No one has yet counted all the corpses. Someone has mentioned Eclipse before and it somehow indicates that the strongest distinction between an OSS project and a commercial one is the property of being OSS. Kay > Cheers, > Nicola Musatti > > P.S. Maybe I should add a ;-) This is a full ;-) thread. So it would be a bit redundant to mention it - just like this meta-comment. From diener896092_no_spam_here at bellsouth.net Sat Jul 7 15:25:50 2007 From: diener896092_no_spam_here at bellsouth.net (Edward Diener) Date: Sat, 07 Jul 2007 15:25:50 -0400 Subject: Getting the home directory in Python and a bug in os.path.expanduser In-Reply-To: <5aQji.1085$m%.196@newssvr17.news.prodigy.net> References: <5aQji.1085$m%.196@newssvr17.news.prodigy.net> Message-ID: <_MRji.11911$K9.9459@bignews6.bellsouth.net> Josiah Carlson wrote: > Edward Diener wrote: >> What is the generic operating system way of getting the home directory ? >> >> I am guessing it is os.path.expanduser("~"). Is there a better way or >> an alternate way ? >> >> If it is as I surmise, the aforementioned expanduser("~") of os.path >> seems incorrect to me under Windows. The document says: >> >> "On Windows, only "~" is supported; it is replaced by the environment >> variable HOME or by a combination of HOMEDRIVE and HOMEPATH." >> >> But HOME is never the home directory for Windows, only the combination >> of HOMEDRIVE and HOMEPATH is valid, which is always set. If MSYS is >> installed under Windows, where HOME must be set to the MSYS home >> directory for a given user in order to emulate Linux/Unix, attempting >> to use os.path.expanduser("~") will incorrectly return the MSYS home >> directory for a given user rather than the Windows home directory for >> the logged in user. So I think the os.path.expanduser("~") works >> incorrectly in this case and needs to be fixed, else you are telling >> users never to use MSYS under Windows. > > Some people have "sane" values for HOME on Windows. And some people use Linux/Unix emulation software on Windows where HOME has nothing to do with the Windows home directory, but everything to do with the emulation's notion of a "home" directory. In fact Microsoft may well have anticipated this by automatically generating HOMEDRIVE and HOMEPATH based on the user's home directory when he logs on. > That's the only > reason why it was included in expanduser(). The current trunk version > of ntpath offers HOME, USERPROFILE or HOMEDRIVE+HOMEPATH, as well as the > expansion of ~/extra/stuff . There is no problem checking the other values but on Windows HOMEDRIVE+HOMEPATH should always be first, USERPROFILE should be second if either HOMEDRIVE or HOMEPATH does not exist ( which is extremely unlikely), and finally HOME should only be used if the others fail. I will even go for USERPROFILE coming before the check for HOMEDRIVE and HOMEPATH, although I think it is wrong because the notion of a "home" directory on Windows may not stay tied to a user profile ( in fact they may be already different on Vista, which I do not have, for all I know ). But at least USERPROFILE is generated by Windows, like HOMEDRIVE and HOMEPARTH. Using HOME as the first option on Windows is definitely wrong, especially for the reason I pointed out, that Linux/Unix emulation systems on Windows have the user set HOME to the emulation's "home" directory, and that is definitely not the Windows "home" directory. HOME is of course perfectly viable in the Linux/Unix world. Probably most reliable on Windows is a Windows API function, if it exists, for getting the home directory, as opposed to using environment variables, but I can not find any Windows API for it at present. > > If you would like to get rid of Python's support of HOME, please post a > bug report or feature request on the sourceforge tracker. I realized I could post a bug report after I posted my OP, so I subsequently posted a bug report on the sourceforge tracker. I do not need a new feature, but only to have the current feature, which is expanduser, work correctly on Windows. It is currently a serious problem for Window's users, who have Linux/Unix emulation software on their syetem, running a Python script which correctly uses expanduser to get the Windows home directory and ends up with the wrong location. Thank you for responding. I hope Python will fix this problem. From godzillaismad at gmail.com Thu Jul 12 20:01:01 2007 From: godzillaismad at gmail.com (Godzilla) Date: Thu, 12 Jul 2007 17:01:01 -0700 Subject: Fastest way to convert a byte of integer into a list In-Reply-To: <1184284461.506663.75500@g12g2000prg.googlegroups.com> References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> <1184284461.506663.75500@g12g2000prg.googlegroups.com> Message-ID: <1184284861.695430.99300@e9g2000prf.googlegroups.com> On Jul 13, 9:54 am, Matimus wrote: > On Jul 12, 3:34 pm, Godzilla wrote: > > > Hello, > > > I'm trying to find a way to convert an integer (8-bits long for > > starters) and converting them to a list, e.g.: > > > num = 255 > > numList = [1,1,1,1,1,1,1,1] > > > with the first element of the list being the least significant, so > > that i can keep appending to that list without having to worry about > > the size of the integer. I need to do this because some of the > > function call can return a 2 lots of 32-bit numbers. I have to find a > > way to transport this in a list... or is there a better way? > > num = 255 > numlist = [num >> i & 1 for i in range(8)] Thanks matimus! I will look into it... From http Wed Jul 11 21:49:16 2007 From: http (Paul Rubin) Date: 11 Jul 2007 18:49:16 -0700 Subject: bool behavior in Python 3000? References: <5ficp9F3cram2U2@mid.individual.net> <469472f4$0$1293$9b622d9e@news.freenet.de> Message-ID: <7xtzsaqtlv.fsf@ruckus.brouhaha.com> Steve Holden writes: > > | I think that the assignability to the names 'True' and 'False' is > > | incorrect, or at the very least subject to all sorts of odd results. > > It is necessary for 2.x to not break older code. I believe they > > will somehow be reserved, like None, in 3.0. > > > But of course None was assignable until (?) 2.3 and then became > formally constant, so it was no longer possible to assign to it or > even shadow it in a local namespace. So much for that kind of backward > compatibility! None was present in the language for a long time before 2.3 though, and any code that actually assigned to it was asking for trouble. True and False didn't exist til recently and it was common for programs to define them. From jan.vorwerk at cretin.fr Mon Jul 2 15:05:15 2007 From: jan.vorwerk at cretin.fr (Jan Vorwerk) Date: Mon, 02 Jul 2007 21:05:15 +0200 Subject: sort pygtk gtktreeview column containing dates In-Reply-To: <1182954522.086112.9750@g4g2000hsf.googlegroups.com> References: <1182954522.086112.9750@g4g2000hsf.googlegroups.com> Message-ID: <46894c6c$0$1616$426a34cc@news.free.fr> Hi, I did something similar already in wxPython, but not yet in PyGTK. Therefore I cannot provide the actual solution... Since noone answered, I will still give you a hint : http://www.pygtk.org/pygtk2tutorial/sec-TreeModelInterface.html See 14.2.9. Sorting TreeModel Rows and set_sort_func(sort_column_id, sort_func, user_data=None) Good luck! Jan psaroudakis a ?crit , le 27.06.2007 16:28: > Hello... I have been trying to sort a gtktreelist column that contains > dates in the following format: > > eg: 01-Jan-1993 > 12-Dec-1992 etc > > i don't seem to be able to find any other solution than using dates in > the format "YYYY-MM-DD" which is something i am trying to avoid.. > > Is there something very trivial that I am missing/overlooking? any > suggestions? > > Thanks, > > Nik > > Disclaimer: I am very new to Python and Pygtk > From exarkun at divmod.com Tue Jul 3 09:55:29 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 3 Jul 2007 09:55:29 -0400 Subject: Python IRC bot using Twisted In-Reply-To: <1183470274.113508.308370@n60g2000hse.googlegroups.com> Message-ID: <20070703135529.4947.1994867323.divmod.quotient.6400@ohm> On Tue, 03 Jul 2007 13:44:34 -0000, ddtm wrote: >On 3 , 16:01, Jean-Paul Calderone wrote: > [snip] > >Thank you very much! It's a very useful information. One more >question: can I cancel the DelayedCall using its ID (it is returned >from callLater(...)) from another function? In example bot there are >two functions: >def joined(self, channel): > ... >def privmsg(self, user, channel, msg): > ... >For example, I add callLater(...) to joined(...) function and I'd like >to cancel this in privmsg(...) function. What should I do? > Yep. The object callLater returns has a `cancel' method (some others, too) which will prevent the function from being called at the scheduled time. Jean-Paul From harlinseritt at yahoo.com Wed Jul 25 06:38:48 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: Wed, 25 Jul 2007 03:38:48 -0700 Subject: How to create a single executable of a Python program In-Reply-To: <1185358795.401588.61580@b79g2000hse.googlegroups.com> References: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> <1185358795.401588.61580@b79g2000hse.googlegroups.com> Message-ID: <1185359928.577135.37930@d55g2000hsg.googlegroups.com> On Jul 25, 6:19 am, Graeme Glass wrote: > On Jul 25, 8:34 am, NicolasG wrote: > > > Dear fellows, > > > I'm trying to create a executable file using py2exe . Unfortunately > > along with the python executable file it also creates some other files > > that are needed in order to the executable be able to run in a system > > that doesn't have Python installed. Can some one guide me on how can I > > merge all this files created by py2exe in a single exe file ? If I > > have a python program that uses an image file I don't want this image > > file to be exposed in the folder but only to be accessible through the > > program flow.. > > > Regards, > > Nicolas. > > Have you taken a look at cx_Freeze? (http://python.net/crew/atuining/ > cx_Freeze/)http://www.velocityreviews.com/forums/t354325-singlefile-executables.... If you're using py2exe (I'm assuming Win32 platform here), you can do this but you'll have to read the documentation on how to include the library.zip file into the exe. Also there are different levels where the .exe file will include the .pyd files. Unfortunately though, you will likely encounter errors doing it the more you try to "condense". If you can solve this problem, heck tell the guys at py2exe ;-) they have been trying to solve this issue for some time now. If you're doing it with Linux/Unix, cx_freeze is the only way i know to get this done and even then it may have the same limitations. If you're trying to hide/proprietize code, you may want to use pyobfuscate. Good Luck Harlin Seritt From kay.schluehr at gmx.net Mon Jul 16 18:06:05 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 16 Jul 2007 15:06:05 -0700 Subject: Python-URL! - weekly Python news and links (Jul 16) In-Reply-To: References: Message-ID: <1184623565.893149.254600@22g2000hsm.googlegroups.com> Gabriel Genellina schrieb: > QOTW: "That's a property of open source projects. Features nobody really > needs are not implemented." - Gregor Horvath It's a good QOTW but social romantic nonsense nevertheless. Not sure if it's important enough to be mentioned in weekly Python news but Europython 2007 actually happened and took place in Vilnius. Kay From gagsl-py2 at yahoo.com.ar Tue Jul 10 22:47:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Jul 2007 23:47:36 -0300 Subject: storing pickles in sql data base References: <592087469.jZQWuvoN0q@teancum> Message-ID: En Tue, 10 Jul 2007 20:32:01 -0300, David Bear escribi?: > I need to store pickled objects in postgresql. I reading through the > pickle > docs it says to always open a file in binary mode because you can't be > sure > if the pickled data is binary or text. So I have 2 question. Can I set > the > pickle to be text -- and then store it in a 'text' type field in my sql > table, or should what sql type should I save the pickle as? I'd use a binary datatype (raw, blob, binary, whatever postgres calls it). Text columns might be converted or reencoded in some way, binary data should never be modified in any way. -- Gabriel Genellina From zyzhu2000 at gmail.com Tue Jul 31 13:57:03 2007 From: zyzhu2000 at gmail.com (beginner) Date: Tue, 31 Jul 2007 17:57:03 -0000 Subject: standalone process to interact with the web In-Reply-To: References: <1185899130.331170.151980@e16g2000pri.googlegroups.com> Message-ID: <1185904623.754078.198910@e9g2000prf.googlegroups.com> Hi Steve, On Jul 31, 11:42 am, Steve Holden 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 - > > http://wwwsearch.sourceforge.net/mechanize/ > > With mechanize and its partner ClientForm you can rule the web world ;-) > > 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 ------------- 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. From jon+usenet at unequivocal.co.uk Fri Jul 27 06:33:18 2007 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 27 Jul 2007 10:33:18 GMT Subject: Why PHP is so much more popular for web-development References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> <13ahh6kosqqeba1@corp.supernews.com> <7xlkd3m1si.fsf@ruckus.brouhaha.com> Message-ID: On 2007-07-26, Steve Holden wrote: >> That sounds trivial to ameliorate (at least somewhat) by putting your >> uploads in a directory whose name is known only to you (let's say it's >> a random 20-letter string). The parent directory can be protected to >> not allow reading the subdirectory names. > > But you have to admit that's "security by obscurity". Um, no? From samwyse at gmail.com Thu Jul 12 07:39:31 2007 From: samwyse at gmail.com (samwyse) Date: Thu, 12 Jul 2007 11:39:31 -0000 Subject: Rats! vararg assignments don't work In-Reply-To: <33t*jU1Lr@news.chiark.greenend.org.uk> References: <33t*jU1Lr@news.chiark.greenend.org.uk> Message-ID: <1184240371.649114.216150@k79g2000hse.googlegroups.com> On May 30, 7:29 am, Sion Arrowsmith wrote: > samwyse wrote: > >>samwysewrote: > >>>I thought that I'd try this: > >>> first, *rest = arglist > >>>Needless to say, it didn't work. > > [ ... ] > >My use-case is (roughtly) this: > > first, *rest = f.readline().split() > > return dispatch_table{first}(*rest) > > first, rest = f.readline().split(None, 1) > return dispatch_table{first}(*rest.split()) Hey, I like that! Thanks! From JHoover at fbi.gov Wed Jul 25 18:49:18 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Wed, 25 Jul 2007 18:49:18 -0400 Subject: idiom for RE matching In-Reply-To: References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> <1185157313.356112.159020@z24g2000prh.googlegroups.com> <2f6dnUlUxd2_7TjbnZ2dnUVZ_qy3nZ2d@comcast.com> Message-ID: Miles wrote: > On 7/24/07, Gordon Airporte wrote: >> I did already find that it speeds things up to pre-test a line like >> >> if 'bets' or 'calls' or 'raises' in line: >> run the appropriate re's > > Be careful: unless this is just pseudocode, this Python doesn't do > what you think it does; it always runs the regular expressions, so any > speed-up is imaginary. Yes, that's pseudo code even though I didn't really mean it that way when I typed it. The actual code uses the proper 'if foo in line or if bar in line:' form. From emin.shopper at gmail.com Wed Jul 18 17:42:47 2007 From: emin.shopper at gmail.com (Emin.shopper Martinian.shopper) Date: Wed, 18 Jul 2007 17:42:47 -0400 Subject: How do you debug when a unittest.TestCase fails? In-Reply-To: <20070718210454.4947.853567445.divmod.quotient.13123@ohm> References: <32e43bb70707181340u7e4b545bp1f025c941b40134e@mail.gmail.com> <20070718210454.4947.853567445.divmod.quotient.13123@ohm> Message-ID: <32e43bb70707181442h56f471b3we818ad9a403d4733@mail.gmail.com> Thanks for the reply, but neither of those work for me. I don't seem to have the "trial" program installed. Where do you get it? Also, when I use the try/catch block, I get the following error: Traceback (most recent call last): File "_test.py", line 10, in pdb.pm() File "c:\python25\lib\pdb.py", line 1148, in pm post_mortem(sys.last_traceback) AttributeError: 'module' object has no attribute 'last_traceback' On 7/18/07, Jean-Paul Calderone wrote: > > On Wed, 18 Jul 2007 16:40:46 -0400, "Emin.shopper Martinian.shopper" < > emin.shopper at gmail.com> wrote: > >Dear Experts, > > > >How do you use pdb to debug when a TestCase object from the unittest > module > >fails? Basically, I'd like to run my unit tests and invoke pdb.pm when > >something fails. > > > >I tried the following with now success: > > > >Imagine that I have a module _test.py that looks like the following: > > > >----------------------- > >import unittest > >class MyTest(unittest.TestCase): > > def testIt(self): > > raise Exception('boom') > >if __name__ == '__main__': > > unittest.main() > >----------------------- > > > >If I do > >>>>import _test; _test.unittest() > > > >no tests get run. > > > >If I try > >>>>import _test; t = _test.MyTest() > > > >I get > > > >Traceback (most recent call last): > > File "", line 1, in > > File "c:\python25\lib\unittest.py", line 209, in __init__ > > (self.__class__, methodName) > >ValueError: no such test method in : runTest > > > >If I try > >>>>import _test; t = _test.MyTest(methodName='testIt'); t.run() > > > >nothing happens. > > I use `trial -b ', which automatically enables a bunch of nice > debugging functionality. ;) However, you can try this, if you're not > interested in using a highly featureful test runner: > > try: > unittest.main() > except: > import pdb > pdb.pm() > > This will "post-mortem" the exception, a commonly useful debugging > technique. > > Jean-Paul > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From garrickp at gmail.com Thu Jul 5 14:17:58 2007 From: garrickp at gmail.com (Falcolas) Date: Thu, 05 Jul 2007 11:17:58 -0700 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <9uRhi.17027$xk5.14289@edtnps82> Message-ID: <1183659478.231468.229590@57g2000hsv.googlegroups.com> On Jul 5, 10:30 am, "Chris Mellon" wrote: > > I don't think anyone has suggested that. Let me be clear about *my* > position: When you need to ensure that a file has been closed by a > certain time, you need to be explicit about it. When you don't care, > just that it will be closed "soonish" then relying on normal object > lifetime calls is sufficient. This is true regardless of whether > object lifetimes are handled via refcount or via "true" garbage > collection. Relying on the specific semantics of refcounting to give > certain lifetimes is a logic error. > > For example: > > f = some_file() #maybe it's the file store for a database implementation > f.write('a bunch of stuff') > del f > #insert code that assumes f is closed. > > This is the sort of code that I warn against writing. > > f = some_file() > with f: > f.write("a bunch of stuff") > #insert code that assumes f is closed, but correctly this time > > is better. This has raised a few questions in my mind. So, here's my newbie question based off this. Is this: f = open(xyz) f.write("wheee") f.close() # Assume file is closed properly. as "safe" as your code: f = some_file() with f: f.write("a bunch of stuff") #insert code that assumes f is closed, but correctly this time Thanks! G From carsten at uniqsys.com Tue Jul 31 17:07:52 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 31 Jul 2007 17:07:52 -0400 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: <1185916072.3370.32.camel@dot.uniqsys.com> On Tue, 2007-07-31 at 22:30 +0200, Helmut Jarausch wrote: > Hi, > > 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') >>> import shlex >>> shlex.split('abc "xy z" "1 2 3" "a \\" x"') ['abc', 'xy z', '1 2 3', 'a " x'] I hope that's elegant enough ;) -- Carsten Haese http://informixdb.sourceforge.net From bignose+hates-spam at benfinney.id.au Tue Jul 31 23:27:42 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 01 Aug 2007 13:27:42 +1000 Subject: Extending Python by Adding Keywords & Data types References: <1185913739.879602.212950@w3g2000hsg.googlegroups.com> Message-ID: <87vec0c4sx.fsf@benfinney.id.au> Maximus Decimus writes: > II want to add some more KEYWORDS Adding keywords can only be done by changing the parser for the Python compiler. You can download the source for your preferred implementation of Python (e.g. CPython) and change it there. But likely that's not the best approach. Can you tell us what problem you are trying to solve, and why you think adding keywords to the language is desirable? > and DATATYPES into the python script apart from the existing ones. Adding datatypes is done by defining classes. Please work through the tutorial (as a series of exercises to perform and understand) in order to get a better grounding in these and other basic topics of Python. -- \ "Smoking cures weight problems. Eventually." -- Steven Wright | `\ | _o__) | Ben Finney From martin at v.loewis.de Fri Jul 20 02:36:26 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 20 Jul 2007 08:36:26 +0200 Subject: Interpreting os.lstat() In-Reply-To: References: <1184806559.224636.266500@e9g2000prf.googlegroups.com> Message-ID: <46a057e8$0$19051$9b622d9e@news.freenet.de> > (a) Running 'stat' is *not the same* as a system call. Why do you say that? It is *exactly* the same, at least on a POSIX system (on Windows, there is no stat, so the implementation has to map that to several system calls). Regards, Martin From ladynikon at gmail.com Mon Jul 23 13:03:01 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Mon, 23 Jul 2007 13:03:01 -0400 Subject: Where do they tech Python officialy ? In-Reply-To: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> Message-ID: <59f9c5160707231003y68e9e5fbs1c21800f12890fad@mail.gmail.com> My school does damn near all of the main ones.. BUT python .. lame.. On 7/23/07, NicolasG wrote: > Hi, > > I want to be a professional python programmer, unfortunately I'm > working on technical support and don't have the time/patience to start > making projects my self. I tried to apply to some Python positions but > 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.. > > I'm planning to save some money and attend a course in any of the > universities that teach hard core Python. > > Does some one have any suggestions on which University to attend ? > Alternatives solutions are welcome.. > > Regards, > Nicolas G. > > -- > http://mail.python.org/mailman/listinfo/python-list > From arkanes at gmail.com Thu Jul 5 12:30:48 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 5 Jul 2007 11:30:48 -0500 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <9uRhi.17027$xk5.14289@edtnps82> Message-ID: <4866bea60707050930v49af0c0es57f5b43abd9df8a2@mail.gmail.com> On 7/2/07, Douglas Alan wrote: > Lenard Lindstrom writes: > > If they are simply a performance tweak then it's not an issue *. I > > was just concerned that the calls were necessary to keep resources > > from being exhausted. > > Well, if you catch an exception and don't return quickly, you have to > consider not only the possibility that there could be some open files > left in the traceback, but also that there could be a large and now > useless data structures stored in the traceback. > > Some people here have been arguing that all code should use "with" to > ensure that the files are closed. But this still wouldn't solve the > problem of the large data structures being left around for an > arbitrary amount of time. > I don't think anyone has suggested that. Let me be clear about *my* position: When you need to ensure that a file has been closed by a certain time, you need to be explicit about it. When you don't care, just that it will be closed "soonish" then relying on normal object lifetime calls is sufficient. This is true regardless of whether object lifetimes are handled via refcount or via "true" garbage collection. Relying on the specific semantics of refcounting to give certain lifetimes is a logic error. For example: f = some_file() #maybe it's the file store for a database implementation f.write('a bunch of stuff') del f #insert code that assumes f is closed. This is the sort of code that I warn against writing. f = some_file() with f: f.write("a bunch of stuff") #insert code that assumes f is closed, but correctly this time is better. On the other hand, f = some_file() f.write("a bunch of stuff") #insert code that doesn't care about the state of f is also fine. It *remains* fine no matter what kind of object lifetime policy we have. The very worst case is that the file will never be closed. However, this is exactly the sort of guarantee that GC can't make, just as it can't ensure that you won't run out of memory. That's a general case argument about refcounting semantics vs GC semantics, and there are benefits and disadvantages to both sides. What I am arguing against are explicit assumptions based on implicit behaviors. Those are always fragile, and doubly so when the implicit behavior isn't guaranteed (and, in fact, is explicitly *not* guaranteed, as with refcounting semantics). From bj_666 at gmx.net Thu Jul 5 15:56:08 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 5 Jul 2007 19:56:08 GMT Subject: Callback scoping References: <1183662847.449011.26560@o61g2000hsh.googlegroups.com> Message-ID: <5f50mnF3ai3k1U2@mid.uni-berlin.de> On Thu, 05 Jul 2007 19:14:07 +0000, Dan wrote: > So, I think I understand what python's scoping is doing in the > following situation: >>>> x = [ lambda: ind for ind in range(10) ] > > [?] > > But, I'm wondering what is the easiest (and/or most pythonic) way to > get the behavior I want? (If you haven't guessed, I want a list of (no > parameter) functions, each of which returns its index in the list.) Default arguments are evaluated when the function is defined: In [15]: x = [lambda x=i: x for i in xrange(10)] In [16]: x[0]() Out[16]: 0 In [17]: x[5]() Out[17]: 5 Ciao, Marc 'BlackJack' Rintsch From deets at nospam.web.de Wed Jul 11 09:15:58 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 11 Jul 2007 15:15:58 +0200 Subject: stripping the first byte from a binary file References: <1184063032.195000.25880@i13g2000prf.googlegroups.com> <1184115964.912526.273780@e16g2000pri.googlegroups.com> <1184148168.639675.85900@a26g2000pre.googlegroups.com> <4694B01A.30107@web.de> <1184153416.798767.163740@d55g2000hsg.googlegroups.com> Message-ID: <5fk3geF3b8794U1@mid.uni-berlin.de> > > Forgive my newbie ignorance, but I am wondering why the other method > would not work? I mean it may not be very safe, > but I guess it may perform a lot better, than having to read the whole > file just to cut out the first byte. Because seeking is not moving? Shifting data bytewise isn't something that is supported by the underlying OS filesystems, and thus not supported. But replacing bytes with others is. Which seek is for. Diez From steve at holdenweb.com Thu Jul 5 08:51:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Jul 2007 08:51:22 -0400 Subject: WXPYTHON push button call a frame In-Reply-To: <1183626149.036739.281070@w5g2000hsg.googlegroups.com> References: <1183626149.036739.281070@w5g2000hsg.googlegroups.com> Message-ID: Marcpp wrote: > Hi I need to call a widget from a button in WXPYTHON. I've tried to > this from a function like this, but when push the button, the program > opens a window and do error. > Any idea? > Well, one *really* good idea would be to copy the error message and paste it into your message. The readers of this list have amazing psychic powers, but you can always help improve the answer quality by providing relevant information. > ..... > def DialogRRHH(self,event): > prog = wx.PySimpleApp(0) > wx.InitAllImageHandlers() > DialogRRHH = MTRRHH(None, -1, "") > prog.SetTopWindow(DialogRRHH) > DialogRRHH.Show() > prog.MainLoop() > > class MTRRHH(wx.Frame): > ....... > if __name__ == "__main__": > app = wx.PySimpleApp(0) > wx.InitAllImageHandlers() > tasques = tasques(None, -1, "") > app.SetTopWindow(tasques) > tasques.Show() > app.MainLoop() > Unfortunately your code extracts don't tell us what's going wrong, only how the program is constructed. While that *is* useful information, by itself it only paints half the picture. 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 rw at smsnet.pl Wed Jul 11 10:38:05 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 11 Jul 2007 07:38:05 -0700 Subject: bool behavior in Python 3000? In-Reply-To: <5fk6ajF3cu82eU1@mid.uni-berlin.de> References: <7xodijdd8r.fsf@ruckus.brouhaha.com> <1184139458.063988.63510@w3g2000hsg.googlegroups.com> <5fk6ajF3cu82eU1@mid.uni-berlin.de> Message-ID: <1184164685.748138.45850@57g2000hsv.googlegroups.com> Marc 'BlackJack' Rintsch wrote: > On Wed, 11 Jul 2007 00:37:38 -0700, Rob Wolfe wrote: > > > Steven D'Aprano wrote: > > > >> From a purely functional perspective, bools are unnecessary in Python. I > >> think of True and False as syntactic sugar. But they shouldn't be > >> syntactic sugar for 1 and 0 any more than they should be syntactic sugar > >> for {"x": "foo"} and {}. > > > > But `bools` are usefull in some contexts. Consider this: > > > >>>> 1 == 1 > > True > >>>> cmp(1, 1) > > 0 > >>>> 1 == 2 > > False > >>>> cmp(1, 2) > > -1 > > > > At first look you can see that `cmp` does not return boolean value > > what not for all newbies is so obvious. > > Sorry I fail to see your point!? What has ``==`` to do with `cmp()` here? > The return of `cmp()` is an integer that cannot and should not be seen as > boolean value. Before `bool` appeared it looked like this: >>> 1 == 1 1 >>> cmp(2, 1) 1 Wich result is boolean value? Rob From gagsl-py2 at yahoo.com.ar Mon Jul 16 14:20:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jul 2007 15:20:09 -0300 Subject: shutil.copyfile problem for GIS data References: <14A2A120D369B6469BB154B2D2DC34D20855B29C@EXCHVS01.ad.sfwmd.gov> Message-ID: En Mon, 16 Jul 2007 14:47:30 -0300, Ahmed, Shakir escribi?: > 2. But problem is that I can't copy over if the same updated > personal geodatabase to the working location, if users uses that same > geodatabase through CITRIX - ArcGIS ( user does not have permission to > edit the data) If you get an "Access denied" (or "File is in use by another process") error, I'm afraid there is nothing you can do from Python. Tell the users to close the application that holds the file open and try again. > import shutil > import os > > src = "c:\mydata\test\mygeo.mdb" > dst = "v:\updated\data\mygeo.mdb" Here you have another problem: \t inside a string means the TAB character. You have to escape all backslashes or use a raw string: that is, either use "c:\\mydata\\test\\mygeo.mdb" or r"c:\mydata\test\mygeo.mdb" -- Gabriel Genellina From aleax at mac.com Tue Jul 10 00:59:03 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 9 Jul 2007 21:59:03 -0700 Subject: catching empty strings (I guess that's what they are) References: <5fev6bF3bcgoiU2@mid.uni-berlin.de> Message-ID: <1i107l5.1pcrn6j2wdj04N%aleax@mac.com> Diez B. Roggisch wrote: ... > for uf in user_files: > uf = uf.strip().lower() > if uf: > file_skip_list.append(uf) This is fine; however, another reasonable alternative is: if not uf.isspace(): file_skip_list.append(uf.strip().lower()) I prefer yours (it's simpler IMHO), but if I was doing a code review I would accept either of these. Alex From rcdailey at gmail.com Thu Jul 12 17:14:37 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Thu, 12 Jul 2007 21:14:37 -0000 Subject: How to create new files? Message-ID: <1184274877.612434.26870@k79g2000hse.googlegroups.com> Hi, I'm trying to create a Python equivalent of the C++ "ifstream" class, with slight behavior changes. Basically, I want to have a "filestream" object that will allow you to overload the '<<' and '>>' operators to stream out and stream in data, respectively. So far this is what I have: class filestream: def __init__( self, filename ): self.m_file = open( filename, "rwb" ) # def __del__( self ): # self.m_file.close() def __lshift__( self, data ): self.m_file.write( data ) def __rshift__( self, data ): self.m_file.read( data ) So far, I've found that unlike with the C++ version of fopen(), the Python 'open()' call does not create the file for you when opened using the mode 'w'. I get an exception saying that the file doesn't exist. I expected it would create the file for me. Is there a way to make open() create the file if it doesn't exist, or perhaps there's another function I can use to create the file? I read the python docs, I wasn't able to find a solution. Also, you might notice that my "self.m_file.read()" function is wrong, according to the python docs at least. read() takes the number of bytes to read, however I was not able to find a C++ equivalent of "sizeof()" in Python. If I wanted to read in a 1 byte, 2 byte, or 4 byte value from data into python I have no idea how I would do this. Any help is greatly appreciated. Thanks. From exarkun at divmod.com Tue Jul 3 08:01:22 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 3 Jul 2007 08:01:22 -0400 Subject: Python IRC bot using Twisted In-Reply-To: <1183456019.764920.6820@q75g2000hsh.googlegroups.com> Message-ID: <20070703120122.4947.2130827029.divmod.quotient.6378@ohm> On Tue, 03 Jul 2007 09:46:59 -0000, ddtm wrote: >I'm using an example of IRC bot (_ttp://twistedmatrix.com/projects/ >words/documentation/examples/ircLogBot.py) to create my own bot. But I >have a problem. I'm trying to make my bot send messages periodically. >But I can't find a way of adding Timer or something similar to my code >so that it could work. Could somebody modify an example to make IRC >bot send anything to chat every 20 seconds? > >P.S. Timer should not lock the main program (I think it should work in >other thread or so) >P.P.S. Could somebody write a code of delay between messages too? In >pseudocode it looks like this: > sleep(20) > sendMessage(channel,'lopata') >This delay should be non-locking too. >P.P.P.S. Sorry for my bad English (and for a noob question too) > You can use reactor.callLater to schedule a one-time event to happen at some future point: reactor.callLater(20, sendMessage, channel, 'lopata') There is also a utility class, twisted.internet.task.LoopingCall, which you can use to schedule an event to occur repeatedly at some interval: call = LoopingCall(sendMessage, channel, 'lopata') loopDeferred = call.start(20) You can read more about these APIs in the scheduling howto: http://twistedmatrix.com/projects/core/documentation/howto/time.html Or you can refer to the generated API documentation: http://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IReactorTime.html http://twistedmatrix.com/documents/current/api/twisted.internet.task.LoopingCall.html Hope this helps, Jean-Paul From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 24 06:57:54 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 24 Jul 2007 12:57:54 +0200 Subject: classmethod & staticmethod In-Reply-To: <1185273890.838047.125800@e16g2000pri.googlegroups.com> References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> <46a5b2ad$0$18903$426a74cc@news.free.fr> <1185273890.838047.125800@e16g2000pri.googlegroups.com> Message-ID: <46a5db2c$0$25660$426a74cc@news.free.fr> james_027 a ?crit : > hi, > >> The 'real' use is (are) the one(s) you'll find. FWIW, I use >> staticmethods for helper functions that don't need access to the class >> or instance but are too specific to a class to be of any use as plain >> functions. Which is not a very frequent case. Classmethods are more >> usefull - mostly as alternate constructors or utility methods for an >> alternate constructor, but there are other possible uses (sorry, I have >> no concrete example at hand). > > You mean like the example from Marc Marc's example is typically an alternate constructor. This is indeed one of the most obvious use case of classmethod, but what I meant is that there are others cases where classmethods can help. From grflanagan at yahoo.co.uk Fri Jul 6 10:13:00 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Fri, 06 Jul 2007 07:13:00 -0700 Subject: Re-raising exceptions with modified message In-Reply-To: References: Message-ID: <1183731180.023370.240820@c77g2000hse.googlegroups.com> On Jul 6, 12:18 am, Christoph Zwerschke wrote: > Sorry for the soliloquy, but what I am really using is the following so > that the re-raised excpetion has the same type: > > def PoliteException(e): > class PoliteException(e.__class__): > def __init__(self, e): > self._e = e > def __getattr__(self, name): > return getattr(self._e, name) > def __str__(self): > if isinstance(self._e, PoliteException): > return str(self._e) > else: > return '\n%s: %s, I am sorry!' % ( > self._e.__class__.__name__, str(self._e)) > return PoliteException(e) > > try: > unicode('\xe4') > except Exception, e: > raise PoliteException(e) Would a decorator work here? class PoliteException(Exception): def __init__(self, e): self._e = e def __getattr__(self, name): return getattr(self._e, name) def __str__(self): return '\n%s: %s, I am sorry!' % ( self._e.__class__.__name__, str(self._e)) def politefail(fn): def wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except Exception, e: raise PoliteException(e) return wrapper @politefail def funktion(): unicode('\xe4') funktion() @politefail def raise_exception(err, *args): raise err(*args) def funktion(): if 1 != 2: raise_exception(ArithmeticError, '1 is not equal to 2.') print funktion() From http Mon Jul 9 11:40:09 2007 From: http (Paul Rubin) Date: 09 Jul 2007 08:40:09 -0700 Subject: What is the most efficient way to test for False in a list? References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <7x7ipajvst.fsf@ruckus.brouhaha.com> <5fejp2F3cp3igU1@mid.individual.net> <5feju0F3c7pd1U1@mid.uni-berlin.de> <5ff2ruF3cpan3U1@mid.individual.net> Message-ID: <7xk5t9egbq.fsf@ruckus.brouhaha.com> Bjoern Schliessmann writes: > > You are mistaken. all take an iterable and returns if each value > > of it is true. > > That's an identity test for True, not for False (the latter was > requested). Thus, I'm not mistaken. No, "true" is not the same thing as "True". From jayharvard1 at gmail.com Mon Jul 16 15:08:40 2007 From: jayharvard1 at gmail.com (jayharvard1 at gmail.com) Date: Mon, 16 Jul 2007 12:08:40 -0700 Subject: Binary blobs to jpeg In-Reply-To: References: <1184612270.455699.254560@r34g2000hsd.googlegroups.com> Message-ID: <1184612920.610854.226290@57g2000hsv.googlegroups.com> > Have you tried to open the file in "wb" mode? > > HTH, > > -- > Carsten Haesehttp://informixdb.sourceforge.net The data is coming from a record set selection from the Access database. I guess I could write the data to a temp file and open that file handle with the "wb" mode. But, no, I haven't tried that. jeh From tdelaney at avaya.com Mon Jul 2 01:04:02 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 2 Jul 2007 13:04:02 +0800 Subject: Probably simple syntax error In-Reply-To: <1183351228.878746.233430@o61g2000hsh.googlegroups.com> Message-ID: Dustin MacDonald wrote: > [code] > randomizing_counter = 0 > # Put the loop counter for the randomizing to zero. > until_val = 36 > # Set the "until val" to 36. We'll compare them to make sure we're not > at the end of our wordlist_both. > > while randomizing_counter < until_val: > big_randomized_int = RandRange(0,100) > # Make a random value and store it. > small_randomized_int = big_randomized_int / 100 > # Divide that random value and store it in a different variable. > small_randomized_int = Round(small_randomized_int, 2) > # Round that value to 2 decimal places > **weights_array(randomizing_counter) = small_randomized_int > # Assign the first randomized value to our first word to be weighted. > randomizing_counter = randomizing_counter + 1 > # Up the counter and repeat. > [/code] > > The starred line is the one getting the error message: "SyntaxError: > can't assign to function call" You should always copy and paste the exception you receive (including the stack trace). Anyway, read the exception *carefully*. It says "can't assign to function *call*". In the line: weights_array(randomizing_counter) = small_randomized_int "weights_array(randomizing_counter)" is a function call. My guess is that you think you're trying to modify an element of "weights_array" (your code doesn't show us what weights_array is, but I'm guessing it's actually a list), but parentheses are not the syntax for element access (subscripting) in Python. You should read the python tutorial: http://docs.python.org/tut/tut.html especially the sections on lists: http://docs.python.org/tut/node5.html#SECTION005140000000000000000 and functions: http://docs.python.org/tut/node6.html#SECTION006600000000000000000 Cheers, Tim Delaney From dlomsak at gmail.com Sun Jul 1 15:38:10 2007 From: dlomsak at gmail.com (dlomsak) Date: Sun, 01 Jul 2007 12:38:10 -0700 Subject: object references/memory access In-Reply-To: <7xfy48f486.fsf@ruckus.brouhaha.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> Message-ID: <1183318690.661279.256900@n2g2000hse.googlegroups.com> Thanks for the responses folks. I'm starting to think that there is merely an inefficiency in how I'm using the sockets. The expensive part of the program is definitely the socket transfer because I timed each part of the routine individually. For a small return, the whole search and return takes a fraction of a second. For a large return (in this case 21,000 records - 8.3 MB) is taking 18 seconds. 15 of those seconds are spent sending the serialized results from the server to the client. I did a little bit of a blind experiment and doubled the bytes on the client's socket.recv line. This improved the rate of transfer each time. The original rate when I was accepting 1024 bytes per recv took 47 seconds to send the 8.3 MB result. By doubling this size several times, I reduced the time to 18 seconds until doubling it further produced diminishing results. I was always under the impression that keeping the send and recv byte sizes around 1024 is a good idea and I'm sure that jacking those rates up is a lousy way to mitigate the transfer. It is also interesting to note that increasing the bytes sent per socket.send on the server side had no visible effect. Again, that was just a curious experiment. What bothers me is that I am sure sending data over the local loopback address should be blazing fast. 8.3 MB should be a breeze because I've transferred files over AIM to people connected to the same router as me and was able to send hundreds of megabytes in less than a two or three seconds. With that said, I feel like something about how I'm send/recv-ing the data is causing lots of overhead and that I can avoid reading the memory directly if I can speed that up. I guess now I'd like to know what are good practices in general to get better results with sockets on the same local machine. I'm only instantiating two sockets total right now - one client and one server, and the transfer is taking 15 seconds for only 8.3MB. If you guys have some good suggestions on how to better utilize sockets to transfer data at the speeds I know I should be able to achieve on a local machine, let me know what you do. At present, I find that using sockets in python requires very few steps so I'm not sure where I could really improve at this point. Thanks for the replies so far, I really appreciate you guys considering my situation and helping out. From nytrokiss at gmail.com Fri Jul 20 17:40:46 2007 From: nytrokiss at gmail.com (James Matthews) Date: Fri, 20 Jul 2007 14:40:46 -0700 Subject: Python Flagged as a Virus by AVG Message-ID: <8a6b8e350707201440s66ee9286k2009e2b92f5393ff@mail.gmail.com> I was reading a Microsoft news group and came across this post Got this during a scan of my computer: infected: object C:\hp\bin\python-2.2.3.exe:\comparisons.html result: trojan horse PHP/MPack.B status: infected embedded object inefected: object C:\hp\bin\python-2.2.3.exe What can/should I do about this? Thanks for your help. then there is another post I got the same thing with my free AVG, but it was not moved to virus valut. Have no idea what to do. Any help is appreciated!!! Mine says Comparisons.HTML PHP/MPACKB Python-2.2.1.exe then finnaly I just read on the AVG forum, many folks have gotten this threat today, it is a false positive. To clear it, update your virus definitions and then run another scan. The new update is suppose to fix it. I did an update, then another scan, and it finally came back clean. Seems it isn't going in people's virus vaults. Hope this helps........:-) -- http://www.goldwatches.com/watches.asp?Brand=14 http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From memracom at yahoo.com Sun Jul 22 15:50:14 2007 From: memracom at yahoo.com (memracom at yahoo.com) Date: Sun, 22 Jul 2007 12:50:14 -0700 Subject: Compiling PythonD using DJGPP In-Reply-To: <46a38c61$0$16279$88260bb3@free.teranews.com> References: <46a38c61$0$16279$88260bb3@free.teranews.com> Message-ID: <1185133814.929590.311110@q75g2000hsh.googlegroups.com> On 22 Jul, 18:29, "John Simeon" wrote: > Hi there. I had an old computer at my disposal and decided to put it to use > by setting up a nostalgia project with DOS and Windows for Workgroups 3.11. > 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 This sounds like you are running into problems with C library memory models on DOS. I.e. LARGE, MEDIUM, SMALL, TINY. Different memory models use different pointer lengths and presumably, this might result in the wrong bit being interpreted as a sign bit. However, before you dig into that, try turning off the optimizations ( -O3 ) because this can be the cause of wierd errors. If this does work, turn on optimization one level at a time to see how far you can go. And if this leads nowhere, then you probably are dealing with a DOS or DJGPP specific issue. Ask people who work with DJGPP for advice. Good Luck, --Michael Dillon From jmoy.matecon at gmail.com Sun Jul 8 01:03:04 2007 From: jmoy.matecon at gmail.com (Jyotirmoy Bhattacharya) Date: Sun, 08 Jul 2007 05:03:04 -0000 Subject: Timing a python program run In-Reply-To: <1183836101.040882.56080@i38g2000prf.googlegroups.com> References: <1183836101.040882.56080@i38g2000prf.googlegroups.com> Message-ID: <1183870984.711065.268120@c77g2000hse.googlegroups.com> On Jul 8, 12:21 am, David wrote: > Hi, > > In matlab, I'd calculate the time for a script named test.m to run > with: > > >> tic, run, toc > > Is there some way to do this in python on a mac os x from the terminal > window? Or whatever? The timeit module may be of use: http://docs.python.org/lib/module-timeit.html From len-l at telus.net Mon Jul 2 20:08:40 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Tue, 03 Jul 2007 00:08:40 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <9uRhi.17027$xk5.14289@edtnps82> Message-ID: Douglas Alan wrote: > Lenard Lindstrom writes: > >>>> Explicitly clear the exception? With sys.exc_clear? > >>> Yes. Is there a problem with that? > >> As long as nothing tries to re-raise the exception I doubt it breaks >> anything: >> >> >>> import sys >> >>> try: >> raise StandardError("Hello") >> except StandardError: >> sys.exc_clear() >> raise >> >> >> Traceback (most recent call last): >> File "", line 5, in >> raise >> TypeError: exceptions must be classes, instances, or strings >> (deprecated), not NoneType > > I guess I don't really see that as a problem. Exceptions should > normally only be re-raised where they are caught. If a piece of code > has decided to handle an exception, and considers it dealt with, there > is no reason for it not to clear the exception, and good reason for it > to do so. It is only a problem if refactoring the code could mean the exception is re-raised instead of handled at that point. Should the call to exc_clear be overlooked then the newly added raise will not work. > Also, any caught exception is automatically cleared when > the catching procedure returns anyway, so it's not like Python has > ever considered a caught exception to be precious information that > ought to be preserved long past the point where it is handled. > That's the point. Python takes care of clearing the traceback. Calls to exc_clear are rarely seen. If they are simply a performance tweak then it's not an issue *. I was just concerned that the calls were necessary to keep resources from being exhausted. >> But it is like calling the garbage collector. You are tuning the >> program to ensure some resource isn't exhausted. > > I'm not sure I see the analogy: Calling the GC can be expensive, > clearing an exception is not. The exception is going to be cleared > anyway when the procedure returns, the GC wouldn't likely be. > The intent of a high level language is to free the programmer from such concerns as memory management. So a call to the GC is out-of-place in a production program. Anyone encountering such a call would wonder what is so critical about that particular point in the execution. So encountering an exc_clear would make me wonder why it is so important to free that traceback. I would hope the comments would explain it. > It's much more like explicitly assigning None to a variable that > contains a large data structure when you no longer need the contents > of the variable. Doing this sort of thing can be a wise thing to do > in certain situations. > I just delete the name myself. But this is different. Removing a name from the namespace, or setting it to None, prevents an accidental access later. A caught traceback is invisible. >> It relies on implementation specific behavior to be provably >> reliable*. > > As Python is not a formally standardized language, and one typically > relies on the fact that CPython itself is ported to just about every > platform known to Man, I don't find this to be a particular worry. > But some things will make it into ISO Python. Registered exit handlers will be called at program termination. A context manager's __exit__ method will be called when leaving a with statement. But garbage collection will be "implementation-defined" **. >> If this is indeed the most obvious way to do things in your >> particular use case then Python, and many other languages, is >> missing something. If the particular problem is isolated, >> formalized, and general solution found, then a PEP can be >> submitted. If accepted, this would ensure future and cross-platform >> compatibility. > > Well, I think that the refcounting semantics of CPython are useful, > and allow one to often write simpler, easier-to-read and maintain > code. Just as long as you have weighed the benefits against a future move to a JIT-accelerated, continuation supporting PyPy interpreter that might not use reference counting. > I think that Jython and IronPython, etc., should adopt these > semantics, but I imagine they might not for performance reasons. I > don't generally use Python for it's speediness, however, but rather > for it's pleasant syntax and semantics and large, effective library. > Yet improved performance appeared to be a priority in Python 2.4 development, and Python's speed continues to be a concern. * I see in section 26.1 of the Python 2.5 /Python Library Reference/ as regards exc_clear: "This function can also be used to try to free resources and trigger object finalization, though no guarantee is made as to what objects will be freed, if any." So using exc_clear is not so much frowned upon as questioned. ** A term that crops up a lot in the C standard /ISO/IEC 9899:1999 (E)/. :-) -- Lenard Lindstrom From samper.d at gmail.com Sat Jul 21 12:50:09 2007 From: samper.d at gmail.com (Dave Sampson) Date: Sat, 21 Jul 2007 09:50:09 -0700 Subject: Python Subprocess module In-Reply-To: <1184519671.315474.132910@m37g2000prh.googlegroups.com> References: <1184519671.315474.132910@m37g2000prh.googlegroups.com> Message-ID: <1185036609.385471.96890@m3g2000hsh.googlegroups.com> Thanks for your response. It;s good to see you're promtoing Pexpect. I was actualy wokring on a project at work that could have used Pexpect to automate the creation of maps by tieing togethr a bunch of processes through SSH and Pexpect looked like the money shot. however it was enough of a battle to bring Python into the game since it is government that bringing CYGWIN was a battle not worth fighting. Which is unfortunate because I think Pexpect was exactly what we needed in that case > > You need Pexpect. > > There is nothing you can do about this when using a pipe. > This is because stdio will change the type of buffering when sending > stdout and stderr to a pipe. From the client side there is no way you > can change the buffer mode (you CAN change the mode, but it only > changes > it on YOUR side of the pipe -- not your child application's side). I obviously lack skills and understanding in many aspects of programming. After all I'm a geographer / recreologist not a comp-sci professional. I understand the CONCEPT of pipes but don't know how to use or implement.. the bigest things I ever do is something like dmesg | grep wlan0 Where | is my pipe... but that is the extent of my knowledge and skill. Pexpect may very well be the option I need, and having a project that supports the module is great. I am curous what is stopping Pexpect from becoming cross platform. Above, a user suggested implementing send keys in windows. Why not include that as an try/except in Pexpect instead of my wrapper? That way it can benifit many more people? Cheers From jeethu at jeethurao.com Tue Jul 24 01:51:21 2007 From: jeethu at jeethurao.com (Jeethu Rao) Date: Tue, 24 Jul 2007 11:21:21 +0530 Subject: Confused with csv.reader copies In-Reply-To: <1185216342.833408.56690@m3g2000hsh.googlegroups.com> References: <1185216342.833408.56690@m3g2000hsh.googlegroups.com> Message-ID: <46A59359.3060103@jeethurao.com> Robert Dailey wrote: > First, take a look at my example code: > ----------------------------------------------------- > import csv > > def pass1( reader ): > print reader.next() > print reader.next() > > def pass2( reader ): > print reader.next() > print reader.next() > > reader = csv.reader( open( "C:/IT/Method/SpaceImpact/code/tools/ > ProfileViewer/performance_profile.csv", "rb" ) ) > > pass1( reader ) > pass2( reader ) > ----------------------------------------------------- > Like Gabriel suggested, using itertools.tee should do the trick. ----------------------------------------------------- import csv from itertools import tee def pass1( reader ): print reader.next() print reader.next() def pass2( reader ): print reader.next() print reader.next() reader1,reader2 = tee( csv.reader( open( "C:/IT/Method/SpaceImpact/code/tools/ ProfileViewer/performance_profile.csv", "rb" ) ) ) pass1( reader1 ) pass2( reader2 ) ----------------------------------------------------- ~ Jeethu From p at ulmcnett.com Thu Jul 12 18:07:02 2007 From: p at ulmcnett.com (Paul McNett) Date: Thu, 12 Jul 2007 15:07:02 -0700 Subject: New guy help with setup In-Reply-To: <1184277359.397821.265290@m3g2000hsh.googlegroups.com> References: <1184275051.504507.116080@57g2000hsv.googlegroups.com> <1184275783.250640.327630@g4g2000hsf.googlegroups.com> <1184277359.397821.265290@m3g2000hsh.googlegroups.com> Message-ID: <4696A606.7070707@ulmcnett.com> meg99 wrote: > On Jul 12, 4:35 pm, Paul McNett wrote: >> meg99 wrote: >>> On Jul 12, 4:24 pm, Paul McNett wrote: >>>> meg99 wrote: >>>>> I just downloaded 2.5 and read the readme file. It says "Before you >>>>> can build Python, you must first confiigure it....Start by running the >>>>> script "./configure". >>>>> I can't find "./configure" >>>>> I am running Windows XP SP2 >>>> You downloaded the wrong file. You want the Windows Installer:http://python.org/ftp/python/2.5.1/python-2.5.1.msi >>> My applogies - I did download and install 2.5.1 >> In that case, open up your command window (Start|Run "cmd" ). >> >> Type 'python' at the c:\ prompt. >> >> Or, Start|All Programs|Python 2.5|IDLE > I opened the command window and typed 'python' > got 'not recognized as a command' Add c:\python25 to your Windows system path. > went to the python25 folder and typed 'python' > got the >>> prompt Good! Python is installed and working normally. > typed './configure' > got 'no Python documentation found for './configure' You don't need to ./configure. That's for when you are going to compile Python from source code into a binary, which you don't need to do because you installed a precompiled binary for Windows. -- pkm ~ http://paulmcnett.com From kar1107 at gmail.com Mon Jul 16 20:33:53 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Mon, 16 Jul 2007 17:33:53 -0700 Subject: In a dynamic language, why % operator asks user for type info? In-Reply-To: <1184631512.329438.90050@i13g2000prf.googlegroups.com> References: <1184631007.920803.147790@j4g2000prf.googlegroups.com> <1184631512.329438.90050@i13g2000prf.googlegroups.com> Message-ID: <1184632433.980754.189240@d30g2000prg.googlegroups.com> On Jul 16, 5:18 pm, Dan Bishop wrote: > On Jul 16, 7:10 pm, Karthik Gurusamy wrote:> Hi, > > > The string format operator, %, provides a functionality similar to the > > snprintf function in C. In C, the function does not know the type of > > each of the argument and hence relies on the embedded % > > specifier to guide itself while retrieving args. > > > In python, the language already provides ways to know the type of an > > object. > > > So in > > > output = '%d foo %d bar" % (foo_count, bar_count), > > why we need to use %d? > > In order to distinguish between, for example: > > > > >>> '%c' % 42 > '*' > >>> '%d' % 42 > '42' > >>> '%e' % 42 > '4.200000e+01' > >>> '%f' % 42 > '42.000000' > >>> '%g' % 42 > '42' > >>> '%i' % 42 > '42' > >>> '%o' % 42 > '52' > >>> '%r' % 42 > '42' > >>> '%s' % 42 > '42' Thanks. The above surprised me as I didn't expect that %s will accept 42. Looks like the implicit conversion doesn't work the other way. >>> '%s' % 42 '42' >>> '%d' % '42' Traceback (most recent call last): File "", line 1, in TypeError: int argument required >>> Looks like %s can be used even when I'm sending non-strings. >>> '%s foo %s bar' % (25, 25.34) '25 foo 25.34 bar' >>> So %s seems to serve the multi-type placeholder. Karthik > >>> '%u' % 42 > '42' > >>> '%x' % 42 > > '2a' From bignose+hates-spam at benfinney.id.au Sun Jul 22 23:09:15 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 23 Jul 2007 13:09:15 +1000 Subject: split on NO-BREAK SPACE References: <20070722193732.4947.752757075.divmod.quotient.14354@ohm> Message-ID: <87bqe3lstg.fsf@benfinney.id.au> Steve Holden writes: > Well, if you're going to start answering questions with FACTS, how > can questioners reply on their prejudices to guide them any more? You clearly underestimate the capacity for such people to choose only the particular facts that support those prejudices. -- \ "Are you pondering what I'm pondering?" "I think so, Brain, but | `\ I don't think Kay Ballard's in the union." -- _Pinky and The | _o__) Brain_ | Ben Finney From philr at aspexconsulting.co.nz Wed Jul 11 16:41:53 2007 From: philr at aspexconsulting.co.nz (Phil Runciman) Date: Thu, 12 Jul 2007 08:41:53 +1200 Subject: S2K DTS and Python In-Reply-To: <46933BFD.2040606@timgolden.me.uk> References: <46933BFD.2040606@timgolden.me.uk> Message-ID: -----Original Message----- From: Tim Golden [mailto:mail at timgolden.me.uk] Sent: Tuesday, 10 July 2007 7:58 p.m. Cc: python-list at python.org Subject: Re: S2K DTS and Python Phil Runciman wrote: > I am a Python newbie so please be gentle on me. Tim Golden replied: Welcome to Python. > I have created a program that takes text files within a directory and it > successfully parses the information from them to create 3 CSV files. Tim Golden replied: Good so far. > However, I now want to update some tables in MSAccess, and it occurred > to me that because Sequel Server 2000 DTS can interface with scripting > languages that maybe I could call my first Python program from within > DTS and then update the tables using DTS. (I am learning DTS hence the > idea). Tim Golden replied: Unless you *really* wanted to learn DTS (and I don't find it that useful myself) then simply do this through Python... and have some fun at the same time :) > My questions are: > > Has anyone used Python within DTS? Tim Golden replied: Haven't, but I wouldn't even try. Unless I were constrained by some kind of contractual binding, I wouldn't even *start* using DTS if I could use Python. I find it far too opaque. Thanks for your welcome Tim. I share your views and would much prefer to develop my Python expertise. :) However, I am tasked with learning DTS. It is OK, but really lacks conceptual clarity. IMHO I think it is a bit of a kludge, but better than nothing. It does get rid of a lot of donkey-work even if its diagrams are more of an aide-de-memoir than anything else. > Am I off the wall trying such a thing? No, but I think it's easier to use the csv module, pyodbc [1] and either code the SQL directly, which is what I tend to do, or use one of the several SQL-ORM-style wrappers around: SQLObject[2], sqlalchemy[3] and its friend Elixir[4], or the newly-advertised Storm[5] from Canonical. Feel free to post back with questions or progress. TJG [1] http://pyodbc.sf.net [2] http://www.sqlobject.org/ [3] http://sqlalchemy.org [4] http://elixir.ematia.de/ [5] https://storm.canonical.com/ From nospam.themindstorm at gmail.com Thu Jul 26 08:14:16 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Thu, 26 Jul 2007 12:14:16 +0000 (UTC) Subject: Singleton in Python Cookbook References: Message-ID: Steve Holden wrote in news:f8989p$qhn$1 at sea.gmane.org: > Alex Popescu wrote: >> Alex Popescu wrote in >> news:Xns9979172DC38F1themindstorm at 80.91.229.5: >> >>> "Diez B. Roggisch" wrote in >>> news:5gq00tF3fm71gU1 at mid.uni-berlin.de: >>> > > [snip...] > > If, that is, "work" means "Raise an AttributeError due to the missing > spam() method". This appears to fix that problem: > Hmmm... just try your correction with the original cookbook code and tell me if it works ;-). As you'll notice that was not the problem I was asking about (but yes that is yet another problem with the code in the book). bests, ./alex -- .w( the_mindstorm )p. From attn.steven.kuo at gmail.com Wed Jul 11 16:09:42 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Wed, 11 Jul 2007 20:09:42 -0000 Subject: lists and dictionaries In-Reply-To: References: Message-ID: <1184184582.330491.326600@e9g2000prf.googlegroups.com> On Jul 11, 12:08 pm, Ladislav Andel wrote: > Hi, > I have a list of dictionaries. > e.g. > [{'index': 0, 'transport': 'udp', 'service_domain': 'dp0.example.com'}, > {'index': 1, 'transport': 'udp', 'service_domain': 'dp1.example.com'}, > {'index': 0, 'transport': 'tcp', 'service_domain': 'dp0.example.com'}, > {'index': 1, 'transport': 'tcp', 'service_domain': 'dp1.example.com'}] > > how could I make a new list of dictionaries which would look like: > [{'transports': ['udp','tcp'], 'service_domain': 'dp0.example.com'}, > {'transports': ['udp','tcp'], 'service_domain': 'dp1.example.com'}] You provide scant information for this task. For example, is the new list ordered or unordered? Can the list corresponding to the 'transports' key contain duplicates? Regardless, here's an example: li = [ {'index': 0, 'transport': 'udp', 'service_domain': 'dp0.example.com'}, {'index': 1, 'transport': 'udp', 'service_domain': 'dp1.example.com'}, {'index': 0, 'transport': 'tcp', 'service_domain': 'dp0.example.com'}, {'index': 1, 'transport': 'tcp', 'service_domain': 'dp1.example.com'}] group_by_service_domain = dict() for d in li: sd = d['service_domain'] nested_d = group_by_service_domain.setdefault(sd, {'service_domain': sd, 'transports': set()}) nested_d['transports'].add(d['transport']) new_li = [dict(transports=list(d['transports']), service_domain=d['service_domain']) for d in group_by_service_domain.values()] print new_li -- Hope this helps, Steven From stugots at qwest.net Mon Jul 16 13:10:07 2007 From: stugots at qwest.net (John DeRosa) Date: Mon, 16 Jul 2007 10:10:07 -0700 Subject: Pass by reference or by value? References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> <1184385535.558451.306630@22g2000hsm.googlegroups.com> Message-ID: On 15 Jul 2007 16:07:43 -0700, aahz at pythoncraft.com (Aahz) wrote: >[posted and e-mailed] > >[top-posting because I want to make only a one-line response] > >Please stick this on a web-page somewhere -- it makes an excellent >counterpoint to > >http://starship.python.net/crew/mwh/hacks/objectthink.html >http://effbot.org/zone/python-objects.htm Eh... That's more than one line. :-) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jul 12 16:35:21 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 12 Jul 2007 22:35:21 +0200 Subject: bool behavior in Python 3000? References: <5ficp9F3cram2U2@mid.individual.net> Message-ID: <5fnhk9F3dkobnU2@mid.individual.net> Steven D'Aprano wrote: > It seems to me that you deliberately misunderstood him. I know for sure I didn't. > Why else would you type-cast the integers 2 and 1 to bools to > supposedly demonstrate that there's nothing wrong with operations > between bools returning ints? Kindly excuse me bothering You. Bj?rn -- BOFH excuse #419: Repeated reboots of the system failed to solve problem From zyzhu2000 at gmail.com Tue Jul 31 12:25:30 2007 From: zyzhu2000 at gmail.com (beginner) Date: Tue, 31 Jul 2007 16:25:30 -0000 Subject: standalone process to interact with the web Message-ID: <1185899130.331170.151980@e16g2000pri.googlegroups.com> 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 From python-url at phaseit.net Mon Jul 23 09:57:04 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 23 Jul 2007 13:57:04 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jul 23) Message-ID: QOTW: "It's a good QOTW but social romantic nonsense nevertheless." - Kay Schluehr http://groups.google.com/group/comp.lang.python/browse_thread/thread/6348bfbb69642a4a/ "If it [the QOTW] were predictable, wouldn't it be boring?" - Peter Otten An analysis of random.shuffle behavior and how large lists can be handled without losing permutations: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6c2c574c2142b601/ String interpolation uses %d,%f,%s as format specifiers, not to declare the type of expected values: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ab65ec5be19d4d5f The importance of using the right encoding when dealing with filenames coming from multiple systems: http://comments.gmane.org/gmane.comp.python.general/531291 Several problems (not just being unsafe) using pickled objects across a network: http://comments.gmane.org/gmane.comp.python.general/531309 defaultdict, dict.setdefault and other alternatives to handle missing keys in a dictionary, with some microbenchmarkings: http://search.gmane.org/?query=Pythonic%20way%20for%20missing%20dict%20keys&group=gmane.comp.python.general&sort=date Old-style vs. new-style classes revisited: http://comments.gmane.org/gmane.comp.python.general/531464 Among the many riches on the Wiki for which we can give thanks are the notes (photos, ...) David Boddie has aggregated from EuroPython2007: http://wiki.python.org/moin/EuroPython2007 Sometimes one wants to know the class and method names currently executing, and that appears to be tricky: http://groups.google.com/group/comp.lang.python/msg/9ac405eeab899ee8 ======================================================================== 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. 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 bj_666 at gmx.net Fri Jul 13 09:18:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Jul 2007 13:18:38 GMT Subject: Getting values out of a CSV References: <1184295593.638409.22910@22g2000hsm.googlegroups.com> Message-ID: <5fpcdeF3dm8bpU2@mid.uni-berlin.de> On Fri, 13 Jul 2007 15:05:29 +0300, Daniel wrote: >>> > Note that every time you see [x for x in ...] with no condition, you >>> can >>> > write list(...) instead - more clear, and faster. >>> > >>> > data = list(csv.reader(open('some.csv', 'rb'))) >>> >>> Faster? No. List Comprehensions are faster. >> >> kelvie at valour pdfps $ python -m timeit -c 'data = list(open("make.ps"))' >> 100 loops, best of 3: 7.5 msec per loop >> kelvie at valour pdfps $ python -m timeit -c 'data = [line for line in >> open("make.ps")]' >> 100 loops, best of 3: 9.2 msec per loop >> >> On my system just putting into a list is faster. I think this is >> because you don't need to assign each line to the variable 'line' each >> time in the former case. >> >> I, too, think it's faster to just use list() instead of 'line for line >> in iterable', as it seems kind of redundant. >> > > $ python -m timeit -c 'import csv; data = list(csv.reader(open("some.csv", > "rb")))' > 10000 loops, best of 3: 44 usec per loop > $ python -m timeit -c 'import csv; data = [row for row in > csv.reader(open("some.csv", "rb"))]' > 10000 loops, best of 3: 37 usec per loop > > I don't know why there seems to be a differece, but I know that list comps > are python are very heavily optimised. Does the machine use power saving features like SpeedStep or something similar, i.e. runs the processor always with 100% speed or is it dynamically stepped if there's load on the processor? Do both tests read the data always from cache or has the very first loop had to fetch the CSV file from disk? $ python -m timeit -n 1000 -c 'import csv; data = [row for row in csv.reader(open("test.csv", "rb"))]' 1000 loops, best of 3: 1.27 msec per loop $ python -m timeit -n 1000 -c 'import csv; data = list(csv.reader(open("test.csv", "rb")))' 1000 loops, best of 3: 1.25 msec per loop Ciao, Marc 'BlackJack' Rintsch From the.mindstorm.mailinglist at gmail.com Sun Jul 15 03:56:31 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Sun, 15 Jul 2007 00:56:31 -0700 Subject: Trying to choose between python and java In-Reply-To: <464ac405$0$2136$426a74cc@news.free.fr> References: <1179250163.596672.321480@o5g2000hsb.googlegroups.com> <464a190c$0$19570$426a34cc@news.free.fr> <1179263947.704564.77650@n59g2000hsh.googlegroups.com> <464ac405$0$2136$426a74cc@news.free.fr> Message-ID: <1184486191.434361.77000@g4g2000hsf.googlegroups.com> I read in this thread lots of different (hopefully personal) opinions on the question of Java vs Python, so I thought I will post mines too (with the amendment that I am a Java guy, spending there more than 10 years). I don't think you can do a performance comparison upfront (without having it completely flawed :-) ). There are lots of important aspects that you need to take into consideration while doing such a comparison (startup time, gc configurability and performance, many many others), and I think the only one that is fair is the one your would get for your specific type of app. And the same applies for the speed of development/maintenance/etc. As with any other programming language: it has its own strong points and weak points. This applies to both Java and Python. And I don't think anybody on this list will be able to tell you upfront which one is a better fit for your app (at least not if they don't have an idea about your environment, your existing pl knowledge, your app, etc.). bests, ./alex -- .w( the_mindstorm )p. From rustompmody at gmail.com Tue Jul 10 14:50:10 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 11 Jul 2007 00:20:10 +0530 Subject: xml yml and dependency hell In-Reply-To: <4693D100.1000209@web.de> References: <4693D100.1000209@web.de> Message-ID: On 7/11/07, Stefan Behnel wrote: > Rustom Mody wrote: > > So is it likely that yaml will make it to the standard python library > > at some point?? > > That's up to the maintainers of PyYAML. If they want to get it in, there will > be ways to get there. If they do not want to - unlikely, unless someone else > takes up the work. But it's definitely easier if the authors decide to put it in. Is this a general comment or specific to yaml? I mean can anyone add anything they please to the python standard library? From ccpsceo at gmail.com Fri Jul 6 13:31:50 2007 From: ccpsceo at gmail.com (DeveloperX) Date: Fri, 06 Jul 2007 17:31:50 -0000 Subject: How would I write this C code in Python? Message-ID: <1183743110.399675.180570@n60g2000hse.googlegroups.com> I am trying to figure out how to rewrite the following chunk of code in Python: C source [code] typedef struct PF { int flags; long user; char*filename; unsigned char buffer[MAXBUFFERSIZE]; } PF; typedef BLOCK { PF * packdata; } BLOCK; BLOCK* blocks; [/code] My first idea was to create a class for PF and a class for BLOCK, but I got lost somewhere along the lines. :\ Python Attempt: Please note that since I can't type TABs online easily, I am using the @ character to represent TABs in the following Python code. [code] class PF: @def __init__(self): @@self.flags, self.user = 0, 0 @@self.filename = '' @@self.buffer = [] class BLOCK: @def __init__(self): @@self.packdata = [] blocks = [] [/code] Any Python Gurus out there that can help me? From semanticist at gmail.com Sun Jul 22 13:21:32 2007 From: semanticist at gmail.com (Miles) Date: Sun, 22 Jul 2007 13:21:32 -0400 Subject: Lazy "for line in f" ? In-Reply-To: <1185120650.412694.314280@o61g2000hsh.googlegroups.com> References: <1185120650.412694.314280@o61g2000hsh.googlegroups.com> Message-ID: On 7/22/07, Alexandre Ferrieux wrote: > The Tutorial says about the "for line in f" idiom that it is "space- > efficient". > Short of further explanation, I interpret this as "doesn't read the > whole file before spitting out lines". > In other words, I would say "lazy". Which would be a Good Thing, a > much nicer idiom than the usual while loop calling readline()... > > But when I use it on the standard input, be it the tty or a pipe, it > seems to wait for EOF before yielding the first line. It doesn't read the entire file, but it does use internal buffering for performance. On my system, it waits until it gets about 8K of input before it yields anything. If you need each line as it's entered at a terminal, you're back to the while/readline (or raw_input) loop. -Miles From http Sun Jul 22 13:04:14 2007 From: http (Paul Rubin) Date: 22 Jul 2007 10:04:14 -0700 Subject: Advice on sending images to clients over network References: <1185095666.627415.108450@w3g2000hsg.googlegroups.com> Message-ID: <7xlkd8mktt.fsf@ruckus.brouhaha.com> Frank Millman writes: > Any suggestions will be much appreciated. Why on earth don't you write the whole thing as a web app instead of a special protocol? Then just use normal html tags to put images into the relevant pages. From hniksic at xemacs.org Mon Jul 16 10:55:53 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 16 Jul 2007 16:55:53 +0200 Subject: Implementaion of random.shuffle References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> Message-ID: <87d4ys9z46.fsf@mulj.homelinux.net> Steve Holden writes: > So it would appear that the developers chose the Knuth algorithm > (with a slight variation) for *their* implementation. Now you have > to ask yourself whether your surmise is genuinely correct (in which > case the documentation may contain a bug) or whether the > documentation is indeed correct and you are in error. That is a good question. The random module uses the Mersenne twister, which has a repetition period of 2**19937. The number of n-sized permutations of a list with n elements is n!, while each shuffle requires n calls to the PRNG. This means that to be able to generate all permutations, the PRNG must have a period of at least n! * n. In the case of MT, it means that, regarding the period, you are safe for lists with around 2079 elements. shuffle's documentation may have been written before the random module was converted to use the MT. 2**19937 being a really huge number, it's impossible to exhaust the Mersenne twister by running it in sequence. However, there is also the question of the spread of the first shuffle. Ideally we'd want any shuffle, including the first one, to be able to produce any of the n! permutations. To achieve that, the initial state of the PRNG must be able to support at least n! different outcomes, which means that the PRNG must be seeded by at least log2(n!) bits of randomness from an outside source. For reference, Linux's /dev/random stops blocking when 64 bits of randomness are available from the entropy pool, which means that, in the worst case, shuffling more than 20 elements cannot represent all permutations in the first shuffle! From nogradi at gmail.com Tue Jul 10 04:53:48 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 10 Jul 2007 10:53:48 +0200 Subject: standalone executables In-Reply-To: <450843.98906.qm@web54503.mail.re2.yahoo.com> References: <450843.98906.qm@web54503.mail.re2.yahoo.com> Message-ID: <5f56302b0707100153n41af8228mbbc0a415a5e45981@mail.gmail.com> > I need a reference to get all the programs which used to package Python > programs into standalone executables files. > Would you help me? windows: http://www.py2exe.org/ mac: http://cheeseshop.python.org/pypi/py2app/ linux: http://wiki.python.org/moin/Freeze linux/windows: http://python.net/crew/atuining/cx_Freeze/ HTH. From nagle at animats.com Fri Jul 13 00:02:38 2007 From: nagle at animats.com (John Nagle) Date: Fri, 13 Jul 2007 04:02:38 GMT Subject: Problem with Python's "robots.txt" file parser in module robotparser In-Reply-To: References: <0T7li.5316$rL1.2716@newssvr19.news.prodigy.net> Message-ID: Nikita the Spider wrote: > In article , > John Nagle wrote: > > >>Nikita the Spider wrote: >> >> >>>Hi John, >>>Are you sure you're not confusing your sites? The robots.txt file at >>>www.ibm.com contains the double slashed path. The robots.txt file at >>>ibm.com is different and contains this which would explain why you >>>think all URLs are denied: >>>User-agent: * >>>Disallow: / >>> >> >> Ah, that's it. The problem is that "ibm.com" redirects to >>"http://www.ibm.com", but but "ibm.com/robots.txt" does not >>redirect. For comparison, try "microsoft.com/robots.txt", >>which does redirect. > > > Strange thing for them to do, isn't it? Especially with two such > different robots.txt files. I asked over at Webmaster World, and over there, they recommend against using redirects on robots.txt files, because they questioned whether all of the major search engines understand that. Does a redirect for "foo.com/robots.txt" mean that the robots.txt file applies to the domain being redirected from, or the domain being redirected to? John Nagle From leons.petrazickis at gmail.com Thu Jul 26 11:39:21 2007 From: leons.petrazickis at gmail.com (Leo Petr) Date: Thu, 26 Jul 2007 15:39:21 -0000 Subject: From D In-Reply-To: <46a6086d$0$8399$9b622d9e@news.freenet.de> References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> Message-ID: <1185464361.542540.258800@19g2000hsx.googlegroups.com> On Jul 24, 10:10 am, Stargaming wrote: > On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote: > > There are various things I like about the D language that I think Python > > too may enjoy. Here are few bits (mostly syntactical ones): > > > 1) (we have discussed part of this in the past) You can put underscores > > inside number literals, like 1_000_000, the compiler doesn't enforce the > > position of such underscores, so you can also put them like this: > > 1_00_000. You can put them in literals of decimals, binary, hex, etc. I > > think it's quite useful, because when in Python code I have a line like: > > for i in xrange(1000000): > > I need some time to count the zeros, because the lower levels of my > > visual systems can't count/group them quickly (perceptually). While in a > > syntax like: > > for i in xrange(1_000_000): > > my eyes help me group them at once. > > Sounds like a good thing to be but the arbitrary positioning doesnt make > any sense. Additionally, I'd suggest 10**n in such cases (eg. 10**6). > http://blogs.msdn.com/oldnewthing/archive/2006/04/17/577483.aspx Digits are grouped in 2s in India and in 4s in China and Japan. Regards, Leons Petrazickis http://lpetr.org/blog/ From bsnider at bmi.osu.edu Tue Jul 17 15:12:02 2007 From: bsnider at bmi.osu.edu (Ben Snider) Date: Tue, 17 Jul 2007 15:12:02 -0400 Subject: Pexpect, SSH, and CVS Message-ID: <24048DC1F8522C44B83040006BCC8FC34195CB@troy.bmi.ohio-state.edu> Hello all, So I'm setting up a script that runs when CVS wants to connect to an ext type server by setting CVS_RSH to my script so I can log in with a password. IE CVS_RSH=/etc/projects/blah.py. Which runs when I type say "cvs -d:ext:user at server:/cvsroot co module". I need this because of the way cruise control works and the fact that the cvs server the projects are hosted on are password protected. I cannot install keys nor can I create a passwordless user or any thing other than commit and checkout. So I know my script needs to wrap SSH and when cvs calls it, it runs "blah.py -l user host 'cvs server'" and then pipes stdio to pass commands to 'cvs server'. I can log in and I can send and receive commands through stdio which I am passing through an ugly bit of code like the following, but with some select.select() statements so it doesn't block: ### child = pexpect.spawn(cmd...., maxread=1) ... while (1): input = child.readline() sys.stdout.write(input) if (ouput == 'ok\r\n'): break output = sys.stdin.readline() sys.stderr.write("Sending to child: "+output) child.send(output) #### Also a separate test file test.txt ### Root /cvsroot history ### Basically, I can call the script alone like "cat text.txt | ./blah.py -l user host 'cvs server'" and it works as expected. But when CVS calls it through "cvs history" using the CVS_RSH variable it just hangs right after the child gets, or doesn't get, the "Root /cvsroot" request. All that gets output is some debugging and hangs right after I see "Sending to child: Root /cvsroot". I know it's authenticating, I know cvs server starts on the server and I can pipe commands to it as a standalone script, I just don't know what is different when CVS calls blah.py as opposed to me calling it. I'm also wondering if there's an easier way to do this somehow, I have played with os.dup2() and child.interact() to no avail. Thanks, Ben Snider. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ask at me Fri Jul 20 09:15:39 2007 From: ask at me (alf) Date: Fri, 20 Jul 2007 08:15:39 -0500 Subject: subprocess (spawned by os.system) inherits open TCP/UDP/IP port In-Reply-To: References: Message-ID: Jean-Paul Calderone wrote: > > You can avoid this, if you like. Set FD_CLOEXEC on the socket after you > open it, before you call os.system: > > old = fcntl.fcntl(s.fileno(), fcntl.F_GETFD) > fcntl.fcntl(s.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC) > thx for responding (I was about to send the question to twisted mailing list too ;-). still would like to find out why it is happening (now FD_CLOEXEC narrowed may yahooing/googling searches). While realize that file descriptors are shared by forked processes it is still weird why the port moves to the child process once parent gets killed. what it the parent got multiple subprocesses. Plus it is kind of unintuitive os.system does not protect from such behavoir which is for me more an equivalent of like issuing a ne wcommand/ starting a process from the shell. Thx, -- alf From danb_83 at yahoo.com Fri Jul 27 00:13:00 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Thu, 26 Jul 2007 21:13:00 -0700 Subject: automatic type conversion for comparison operators In-Reply-To: <1185498287.179638.20390@w3g2000hsg.googlegroups.com> References: <1185492177.836716.312390@q75g2000hsh.googlegroups.com> <1185492507.670637.294310@o61g2000hsh.googlegroups.com> <1185498287.179638.20390@w3g2000hsg.googlegroups.com> Message-ID: <1185509580.936175.70860@z28g2000prd.googlegroups.com> On Jul 26, 8:04 pm, Russ wrote: > Dan Bishop wrote: > > BTW, are you a former Pascal programmer? > > No. Why do you ask? [The code snippet I wrote was made up to get a > point across. I > did not actually use that function name in my code.] I just have a hypothesis that former Pascal/Basic programmers are much more likely than C/C++/Java programmers to forget the () on a function call. Nothing to do with the (Java-like) function name. From stuart.tett at gmail.com Wed Jul 4 22:18:51 2007 From: stuart.tett at gmail.com (Stuart) Date: Thu, 05 Jul 2007 02:18:51 -0000 Subject: PyRun_String using my module in a def Message-ID: <1183601931.930115.132400@n2g2000hse.googlegroups.com> I've written my own python modules with the C API, called dlfl. I've now embedded a python interpreter into my Qt application. I am able to execute multiline/singleline blocks and it has no problems remembering definitions from one execute to the next. The problem arises when i try and use a dlfl method inside a def block. For example def x( ): print faces(0) faces is a method in dlfl. If I were to just type "print faces(0)" it would execute fine. However, this way when I type "x()", it just says "global name 'faces' is not defined" If I define x without any of my dlfl methods it works fine: def x(): y = 2 print y+2 x() # 4 Here are the relevant parts of my code: PyObject *main = PyImport_AddModule("__main__"); PyObject *dlfl = PyImport_AddModule("dlfl"); PyObject* main_dict = PyModule_GetDict( main ); PyObject* dlfl_dict = PyModule_GetDict( dlfl ); PyObject *rstring = PyRun_String( cmd, Py_file_input, main_dict, dlfl_dict ); rstring returns NULL and then PyErr_Fetch( &object, &data, &traceback ); gets the traceback string as I mentioned above. Hopefully, there is just a simple solution. Thanks :) From horpner at yahoo.com Thu Jul 19 08:05:14 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 19 Jul 2007 12:05:14 GMT Subject: Implementaion of random.shuffle References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> <87d4ys9z46.fsf@mulj.homelinux.net> <1184787155.773575.303080@d30g2000prg.googlegroups.com> Message-ID: <_rIni.36676$G23.16140@newsreading01.news.tds.net> On 2007-07-19, Steven D'Aprano wrote: > On Wed, 18 Jul 2007 19:32:35 +0000, George Sakkis wrote: > >> On Jul 16, 10:51 pm, Steven D'Aprano >> wrote: >>> On Mon, 16 Jul 2007 16:55:53 +0200, Hrvoje Niksic wrote: >>> > 2**19937 being a really huge number, it's impossible to exhaust the >>> > Mersenne twister by running it in sequence. >>> >>> "Impossible"? >>> >>> Surely this will do it: >>> >>> for n in xrange(2**19937 + 1): >>> random.random() >>> >>> Admittedly, if each call to random() took a picosecond, it would still >>> take 1e5982 centuries to run through the lot. You might want to go make a >>> coffee or something while you're waiting... >> >> Wow, can you make a coffee in.. 57ms ? > > [snip demonstration of xrange raising an exception] > > Of course! Can't you? > > And if I use a microwave oven, the coffee is made so quickly > that I actually go backwards in time... But what happens if you use a microwave oven? ... What the!?!? -- Neil Cerutti From rkmr.em at gmail.com Tue Jul 10 12:13:54 2007 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Tue, 10 Jul 2007 09:13:54 -0700 Subject: serializing datetime object Message-ID: Hi I want to serialize datetime.datetime.now() object . I could convert it to string but how do I get a datetime object back from the string? Any suggestions? thanks mark -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Fri Jul 20 09:26:20 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 20 Jul 2007 15:26:20 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <468565a0$0$3686$426a74cc@news.free.fr> <7xvecumrte.fsf@ruckus.brouhaha.com> <1i13w96.kyyobph71qxrN%aleax@mac.com> <7xwsx63we6.fsf@ruckus.brouhaha.com> <878x9llv5x.fsf@benfinney.id.au> <5fovr8F3eglkfU1@mid.uni-berlin.de> <7x1wf8kc6l.fsf@ruckus.brouhaha.com> <5gb5u1F3fip9cU1@mid.uni-berlin.de> <7xr6n3pjhi.fsf@ruckus.brouhaha.com> Message-ID: <5gbrfsF3djtr2U1@mid.uni-berlin.de> Paul Rubin wrote: > "Diez B. Roggisch" writes: >> What does that buy you - where is "I'm crashed becaus I ran out of >> memory trying to evade the seventh mig" better than "sorry, you will >> be shot down because I'm not capable of processing more enemie >> fighters - but hey, at least I'm still here to tell you!" > > Come on, this is real-time embedded software, not some Visual Basic > app running in Windows. The internal table sizes etc. are chosen > based on the amount of physical memory available, which has tended to > be pretty small until maybe fairly recently. Since when did we restrict ourselves to such an environment? I was under the impression that this thread is about the merits and capabilities of static type-checking? Besides, even if I accept these constraints - I still think the question is valid: what goof is a proof if it essentially proofs that the code is severely limited? After all, memory-allocation _might_ create a crash depending on the actual circumstances - but it might not. Then, you trade a mere possibility against a certain limitation. No, I don't buy that. As I said before: for the most trivial of tasks that might be a good thing. But I'm not convinced that restricting one self in such a manner for more complex tasks isn't going to be a better development path. Diez From cai.haibin at gmail.com Mon Jul 23 05:34:17 2007 From: cai.haibin at gmail.com (james_027) Date: Mon, 23 Jul 2007 09:34:17 -0000 Subject: decorators tutorials In-Reply-To: <1185180112.321457.73170@n2g2000hse.googlegroups.com> References: <1185178383.499234.299850@z24g2000prh.googlegroups.com> <1185180112.321457.73170@n2g2000hse.googlegroups.com> Message-ID: <1185183257.471106.318070@x35g2000prf.googlegroups.com> Hi all, I am having difficulty understanding decorator. The definition was clear for me, but the syntax is not so clear to me. will decorators will always have to be in this way def check_login(func): def _check_login(*args): print "I am decorator" return func(*args) return _check_login @check_login def method2(input): print "I am method TWO. Input %s" % input james On Jul 23, 4:41 pm, "sjdevn... at yahoo.com" wrote: > james_027 wrote: > > Hi, > > > I am learning python by learning django, and I stumble upon decorator > > which is very cool, any beginners resources for python decorators, > > although I can google it, I just want to get a good tutorial for this > > topic. > > Decorators are just a more concise but less obvious way of calling a > defined function on another function. > > e.g. > @my_decorator > def foo(): > ... > > is the essentially the same as: > > def foo(): > ... > foo=my_decorator(foo) From http Fri Jul 27 19:58:51 2007 From: http (Paul Rubin) Date: 27 Jul 2007 16:58:51 -0700 Subject: problem with change to exceptions References: Message-ID: <7xmyxhxutg.fsf@ruckus.brouhaha.com> Neal Becker writes: > should set self.args to None. Nothing wrong there, and what has this got to > do with NoneType being iterable? Probably the traceback constructor tried to iterate through the args. You should initialize the args to an empty tuple, not None. Also note that there's an arbitrary number of them. So you should probably write: class nothing (exceptions.Exception): def __init__ (self, *args): self.args = args You might also want to call Exception.__init__(*args) in the init func. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 27 03:50:13 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 27 Jul 2007 09:50:13 +0200 Subject: generating objects of a type from a name. In-Reply-To: References: <1185495706.034366.58180@k79g2000hse.googlegroups.com> Message-ID: <46a9a39d$0$8060$426a74cc@news.free.fr> tsuraan a ?crit : > I'm not sure what a visual object is, but to create an instance of an > object whose name is known, you can use "eval": Better to use getattr(module, classname), or locals().get(classname), or globals().get(classname). > >>>> oname = 'list' >>>> obj = eval(oname)() >>>> obj > [] >>>> type(obj) > obj = globals()[oname]() And now let's have fun with eval: oname = "os.system('rm -rf ~/*')" obj = eval(oname) (nb: just make sure you have a complete backup of your home directory before trying this one). HTH From ptmcg at austin.rr.com Sat Jul 14 18:49:15 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sat, 14 Jul 2007 15:49:15 -0700 Subject: Fastest way to convert a byte of integer into a list In-Reply-To: <1184359588.648337.24830@m3g2000hsh.googlegroups.com> References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> <1184321842.921823.317470@k79g2000hse.googlegroups.com> <1184359588.648337.24830@m3g2000hsh.googlegroups.com> Message-ID: <1184453355.853001.5510@57g2000hsv.googlegroups.com> On Jul 13, 3:46 pm, "mensana... at aol.com" wrote: > On Jul 13, 5:17 am, Paul McGuire wrote: > > > > > > > On Jul 12, 5:34 pm, Godzilla wrote: > > > > Hello, > > > > I'm trying to find a way to convert an integer (8-bits long for > > > starters) and converting them to a list, e.g.: > > > > num = 255 > > > numList = [1,1,1,1,1,1,1,1] > > > > with the first element of the list being the least significant, so > > > that i can keep appending to that list without having to worry about > > > the size of the integer. I need to do this because some of the > > > function call can return a 2 lots of 32-bit numbers. I have to find a > > > way to transport this in a list... or is there a better way? > > > Standing on the shoulders of previous posters, I put this together. > > > -- Paul > > But aren't we moving backwards? The OP did ask for the fastest way. > > I put this together (from other posters and my own): > > import gmpy > import time > > y = 2**177149 - 1 > > # init list of tuples by byte > bytebits = lambda num : [num >> i & 1 for i in range(8)] > bytes = [ tuple(bytebits(i)) for i in range(256) ] > # use bytes lookup to get bits in a 32-bit integer > bits = lambda num : sum((bytes[num >> i & 255] for i in range(0,32,8)), > ()) > # use base-2 log to find how many bits in an integer of arbitrary > length > from math import log,ceil > log_of_2 = log(2) > numBits = lambda num : int(ceil(log(num)/log_of_2)) > # expand bits to integers of arbitrary length > arbBits = lambda num : sum((bytes[num >> i & 255] for i in > range(0,numBits(num),8)),()) > t0 = time.time() > L = arbBits(y) > t1 = time.time() > print 'Paul McGuire algorithm:',t1-t0 > > t0 = time.time() > L = [y >> i & 1 for i in range(177149)] > t1 = time.time() > print ' Matimus algorithm:',t1-t0 > > x = gmpy.mpz(2**177149 - 1) > t0 = time.time() > L = [gmpy.getbit(x,i) for i in range(177149)] > t1 = time.time() > print ' Mensanator algorithm:',t1-t0 > > ## Paul McGuire algorithm: 17.4839999676 > ## Matimus algorithm: 3.28100013733 > ## Mensanator algorithm: 0.125- Hide quoted text - > > - Show quoted text - Oof! Pre-calculating those byte bitmasks doesn't help at all! It would seem it is faster to use a single list comp than to try to sum together the precalcuated sublists. I *would* say though that it is somewhat cheating to call the other two algorithms with the hardcoded range length of 177149, when you know this is the right range because this is tailored to fit the input value 2**177149-1. This would be a horrible value to use if the input number were something small, like 5. I think numBits still helps here to handle integers of arbitrary length (and only adds a slight performance penalty since it is called only once). -- Paul From aahz at pythoncraft.com Fri Jul 6 10:38:26 2007 From: aahz at pythoncraft.com (Aahz) Date: 6 Jul 2007 07:38:26 -0700 Subject: Mixing Python and C threads References: Message-ID: In article , =?utf-8?b?U3TDqXBoYW5l?= Larouche wrote: > >If I call the methods in the C++ modules from the Python main thread, I >don't have any problem. However, they are usually called from another >Python thread (using the threading module) to keep the GUI responsive >and, then, Python crashes. The question is whether your C++ code is designed to be called from multiple threads. That is, if you call your C++ code from a *single* non-main thread, does it work? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I support the RKAB From steve at REMOVE.THIS.cybersource.com.au Sun Jul 22 12:58:38 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 23 Jul 2007 02:58:38 +1000 Subject: problem with exec References: <1185099810.772825.284620@m3g2000hsh.googlegroups.com> Message-ID: On Sun, 22 Jul 2007 09:12:21 -0400, Steve Holden wrote: >> Steve Holden was playing silly games. You can't use { } for indentation. >> You have to use indentation. >> > I wasn't playing silly games at all, and I did prefix that part ofmy > answer with "I'm afraid I don't understand this question". The OP is > writing a program to "translate" a Python-like language that uses > non-English keywords into Python. Since the application is transforming > its input, it could transform braces into indentation. Of course > *Python* doesn't use braces, but the question was how to write > "pseudo-Python" without using indentation to indicate grouping. Then I have misunderstood you, and I apologize. -- Steven. From knipknap at gmail.com Wed Jul 4 08:21:03 2007 From: knipknap at gmail.com (Samuel) Date: Wed, 04 Jul 2007 05:21:03 -0700 Subject: Debugging "broken pipe" (in telnetlib) In-Reply-To: References: <1183478065.872544.88680@q69g2000hsb.googlegroups.com> Message-ID: <1183551663.359082.297150@q75g2000hsh.googlegroups.com> Thanks for your comments, Jean-Paul. From ptmcg at austin.rr.com Fri Jul 27 09:50:01 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 27 Jul 2007 06:50:01 -0700 Subject: <> vs != In-Reply-To: References: <8a6b8e350707261228x234b7da0g17d43736e45e67ca@mail.gmail.com> <1185537316.344728.265130@r34g2000hsd.googlegroups.com> Message-ID: <1185544201.798485.294010@o61g2000hsh.googlegroups.com> On Jul 27, 7:35 am, Neil Cerutti wrote: > > I like 'not ==', cf 'not in'. Sadly it's a syntax error. However, > as a language designer, I'm not > Guido. > I'd settle for == Guido myself. :) -- Paul From len-l at telus.net Fri Jul 13 20:28:19 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Sat, 14 Jul 2007 00:28:19 GMT Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <5dveb4F360un0U1@mid.individual.net><1i0n0tr.ve0o791347ugyN%aleax@mac.com><7xd4za1086.fsf@ruckus.brouhaha.com><5f0mhuF3b0stbU1@mid.individual.net><7xd4z837e2.fsf@ruckus.brouhaha.com><468b7426$0$9063$426a34cc@news.free.fr><7x4pkkun56.fsf@ruckus.brouhaha.com><1183575597.272150.152200@w5g2000hsg.googlegroups.com><7xzm2budfv.fsf@ruckus.brouhaha.com><7xir8vju1l.fsf@ruckus.brouhaha.com><7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: Hendrik van Rooyen wrote: > "Donn Cave" wrote: > >> In its day, goto was of course very well loved. > > Does anybody know for sure if it is in fact possible to > design a language completely free from conditional jumps? > > At the lower level, I don't think you can get away with > conditional calls - hence the "jumps with dark glasses", > continue and break. > > I don't think you can get that functionality in another way. > > Think of solving the problem of reading a text file to find > the first occurrence of some given string - can it be done > without either break or continue? (given that you have to > stop when you have found it) > Pascal has no break, continue or return. Eiffel doesn't even have a goto. In such imperative languages boolean variables are used a lot. from StringIO import StringIO lines = StringIO("one\ntwo\nthree\nfour\n") line_number = 0 eof = False found = False while not (eof or found): line = lines.readline() eof = line == "" found = line == "three\n" if not found: line_number += 1 if found: print "Found at", line_number else: print "Not found" # prints "Found at 2" --- Lenard Lindstrom From wildemar at freakmail.de Fri Jul 13 12:41:51 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 13 Jul 2007 18:41:51 +0200 Subject: Understanding python functions - Instant Python tutorial In-Reply-To: References: Message-ID: <4697AB4F.80708@freakmail.de> Chris Carlen wrote: > Let's go back the statement: > > x = [1,2,3] > > Do we then say: "[1,2,3] is x" or is it the other way around: "x is > [1,2,3]" ??? > This will yield 'False', because 'is' checks for *identity* not equality. In your case you assign a list the name 'x' and then check (via the 'is' operator) if it is the same object as another (newly created) list. While they are equal (same class and contents) they are not the same. Try this: x = [1, 2, 3] y = [1, 2, 3] id(x), id(y) x == y x is y Then you'll see. > This is actually completely ridiculous, since I am me, not my name. The > name refers to me. I get that. Yet our spoken language puts it in a > way which is backwards. > To stress the point: "a is b" has the same meaning as "b is a". It does not check for "being a certain thing" (as in "Archimedes is a human") but rather for "one thing beeing the exact same as the other" (as in "Superman is Clark Kent"). From arkanes at gmail.com Thu Jul 26 17:12:54 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 26 Jul 2007 16:12:54 -0500 Subject: Why PHP is so much more popular for web-development In-Reply-To: <7xhcnq7vye.fsf@ruckus.brouhaha.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> <13ahh6kosqqeba1@corp.supernews.com> <7xlkd3m1si.fsf@ruckus.brouhaha.com> <7xhcnq7vye.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60707261412s488e2754i822218df5cbe4e90@mail.gmail.com> On 26 Jul 2007 13:26:33 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > Steve Holden writes: > > > That sounds trivial to ameliorate (at least somewhat) by putting your > > > uploads in a directory whose name is known only to you (let's say it's > > > a random 20-letter string). The parent directory can be protected to > > > not allow reading the subdirectory names. > > > > But you have to admit that's "security by obscurity". > > I'm not completely sure it's security by obscurity if the system setup > is careful. The pathname is like a password and maybe it can be > proteced from exposure to the same degree that other file system > contents are protected. This would not pass review for protecting > launch codes, but neither most things done on even serious commercial > web sites. > -- Would you make this directory name be the username+the password? If not, why not? The answer is the same reason why this isn't a reliable method of security. That said, no hosting provider I'm aware of (even the really cheap ones) runs in a purely shared environment anymore. They use suexec or fakejail or something at the very least. This is for their own protection as much (or more) than it is to protect their customers data, though. From miki.tebeka at gmail.com Fri Jul 20 14:30:42 2007 From: miki.tebeka at gmail.com (Miki) Date: Fri, 20 Jul 2007 18:30:42 -0000 Subject: Python C Embedded ! Attribute Error In-Reply-To: <1184946458.306346.211950@i38g2000prf.googlegroups.com> References: <1184946458.306346.211950@i38g2000prf.googlegroups.com> Message-ID: <1184956242.636269.293220@z24g2000prh.googlegroups.com> Hello, > I am using the below C code so that i can embed a Python Code and > get input from a python function and use it in C code . > > Below is the C Code [snipped] > I am getting error > > AttributeError: 'module' object has no attribute 'print' > Cannot find function "print" How do you run your program (I suspect with 'pr pr print 1', should be 'pr pr pr 1'). FWIW, the following simplified program works: #include int main(int argc, char *argv[]) { PyObject *modname, *module, *args, *value, *func; Py_Initialize(); PyRun_SimpleString("import sys; sys.path.append(\".\")"); modname = PyString_FromString("pr"); module = PyImport_Import(modname); Py_DECREF(modname); if (NULL == module) { fprintf(stderr, "error: can't load\n"); Py_Finalize(); return 1; } func = PyObject_GetAttrString(module, "pr"); args = PyTuple_New(1); value = PyLong_FromLong(10); PyTuple_SetItem(args, 0, value); PyObject_CallObject(func, args); Py_Finalize(); return 0; } HTH, -- Miki http://pythonwise.blogspot.com From hjp-usenet2 at hjp.at Tue Jul 3 02:12:20 2007 From: hjp-usenet2 at hjp.at (Peter J. Holzer) Date: Tue, 3 Jul 2007 08:12:20 +0200 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <138jml0ldeucf32@corp.supernews.com> Message-ID: On 2007-07-03 05:12, Scott David Daniels wrote: > Peter J. Holzer wrote: >> On 2007-06-22 20:33, James Harris wrote: >>> I have a requirement to store timestamps in a database. Simple enough >>> you might think but finding a suitably general format is not easy. The >>> specifics are [...] >> Stick to unix timestamps but store them as a double precision floating >> point number. The 53 bit mantissa gives you currently a resolution of >> about 200 ns, slowly deteriorating (you will hit ms resolution in about >> 280,000 years, if I haven't miscalculated). Any language and database >> should be able to handle double-precision FP numbers, so that's as >> portable as it gets and conversion from/to system time should be >> trivial. >> > > TOPS-20 did an interesting format which suggest an interesting variant: > Tops-20: 36-bit (the machine word size) fixed-bit representation > of days since a given moment (the first Photographic > plates of the sky). The "binary point" was at the middle > of the word; the low order 18 bits were the time of day > (GMT), the high-order 18 bits were the days-since date. > > Inspired format: > Days since a some standard date (the TAI date may be a good such > date) expressed as fixed point 64-bit (32-bit day part, 32-bit > day-fraction part) or floating point (using Intel's double-precision, > for example, gives you 26 bits each for day and day-fraction, though > the binary point moves for particular stamps). Doesn't MS-Excel store timestamps in such a format? This requires you to define what a "day" is: a) 86400 seconds b) the time between two consecutive readings of 00:00:00 on a UTC clock c) something else. Definition b) is probably the most useful. > Advantages of such a format: > Using simple arithmetic for the difference between two such stamps > is reasonably accurate even without knowing about when the leap seconds > occur. Better resolution is available with leap-second aware software. > A leap second affects the resolution only in intervals where there > _are_ leap seconds, and ignoring them leaves you almost 5 digits of > accuracy even when you naively ignore them. Since a day with a leap second has 86401 seconds (or 86399, but that hasn't happened yet), a leap second aware counter could record the time HH:MM:SS on such a day as (HH*3600+MM*60+SS)/86401. If you know that there was a leap second on that day you can still recover the exact time wall clock time, otherwise you will be off by up to one second, but the time is still monotonic and you don't have a sudden jump at the end of the day. hp -- _ | Peter J. Holzer | I know I'd be respectful of a pirate |_|_) | Sysadmin WSR | with an emu on his shoulder. | | | hjp at hjp.at | __/ | http://www.hjp.at/ | -- Sam in "Freefall" From nick at craig-wood.com Wed Jul 11 16:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 11 Jul 2007 15:30:03 -0500 Subject: os.wait() losing child? References: <4694903B.8000105@cosc.canterbury.ac.nz> Message-ID: Jason Zheng wrote: > greg wrote: > > Jason Zheng wrote: > >> Hate to reply to my own thread, but this is the working program that > >> can demonstrate what I posted earlier: > > > > I've figured out what's going on. The Popen class has a > > __del__ method which does a non-blocking wait of its own. > > So you need to keep the Popen instance for each subprocess > > alive until your wait call has cleaned it up. > > > > The following version seems to work okay. > > > It still doesn't work on my machine. I took a closer look at the Popen > class, and I think the problem is that the __init__ method always calls > a method _cleanup, which polls every existing Popen instance. The poll > method does a nonblocking wait. > > If one of my child process finishes as I create a new Popen instance, > then the _cleanup method effectively de-zombifies the child process, so > I can no longer expect to see the return of that pid on os.wait() > any more. The problem you are having is you are letting Popen do half the job and doing the other half yourself. Here is a way which works, done completely with Popen. Polling the subprocesses is slightly less efficient than using os.wait() but does work. In practice you want to do this anyway to see if your children exceed their time limits etc. import os import time from subprocess import Popen processes = [] counts = [0,0,0] for i in xrange(3): p = Popen('sleep 1', shell=True, cwd='/home', stdout=file(os.devnull,'w')) processes.append(p) print "Starting child process %d (%d)" % (i, p.pid) while (True): for i,p in enumerate(processes): exitstat = p.poll() pid = p.pid if exitstat is not None: break else: time.sleep(0.1) continue counts[i]=counts[i]+1 #terminate if count>10 if (counts[i]==10): print "Child Process %d terminated." % i if reduce(lambda x,y: x and (y>=10), counts): break continue print "Child Process %d terminated, restarting" % i processes[i] = Popen('sleep 1', shell=True, cwd='/home', stdout=file(os.devnull,'w')) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From stefan.behnel-n05pAM at web.de Mon Jul 9 16:56:06 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 09 Jul 2007 22:56:06 +0200 Subject: PyXML not installing? In-Reply-To: <1184013983.166849.32100@n2g2000hse.googlegroups.com> References: <1184013983.166849.32100@n2g2000hse.googlegroups.com> Message-ID: <4692A0E6.40408@web.de> Robert Dailey wrote: > I downloaded the PyXML library and I'm attempting to install it by > following the README file on Windows XP. I currently have Visual > Studio 2005 installed. > >>From the command line I type: > > C:\PyXML-0.8.4>python setup.py build > running build > running build_py > running build_ext > error: Python was built with Visual Studio 2003; > extensions must be built with a compiler than can generate compatible > binaries. > Visual Studio 2003 was not found on this system. If you have Cygwin > installed, > you can try compiling with MingW32, by passing "-c mingw32" to > setup.py. > > It gives me the above error message. Any way to fix this? IIRC, Python extensions require MSVC 2003 on Windows and I don't think VC 2005 will work at all. You may prefer using lxml for working with XML anyway. Version 1.2.1 has binaries for Windows (and 1.3.2 will likely get them soon). http://codespeak.net/lxml/ Stefan From mensanator at aol.com Thu Jul 26 01:01:06 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Wed, 25 Jul 2007 22:01:06 -0700 Subject: From D In-Reply-To: References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> <87ps2ghtd7.fsf@benfinney.id.au> <1185412639.075218.186290@z24g2000prh.googlegroups.com> Message-ID: <1185426066.162458.187050@z28g2000prd.googlegroups.com> On Jul 25, 9:04?pm, Steven D'Aprano wrote: > On Wed, 25 Jul 2007 18:17:19 -0700, mensana... at aol.com wrote: > > On Jul 25, 8:00 pm, Ben Finney > > wrote: > >> "mensana... at aol.com" writes: > >> > On Jul 24, 6:08 pm, Steven D'Aprano > >> > wrote: > >> > > Python already does: > >> > > "hello-" "world" => "hello-world" > > >> > > Propose: > >> > > 123 456 789 => 123456789 > >> > > 123.456 789 => 123.456789 > > >> > So, spaces will no longer be delimiters? > > >> I don't see how you get that conclusion from Steven's proposal. > > > IDLE 1.2c1 > >>>> s = '123 456' > >>>> s.split() > > ['123', '456'] > > > The only way to get '123 456' would be to treat a space as a > > non-delimiter. But what if those actually WERE two different numbers? > > That makes no sense at all. Your example is about splitting a _string_. Why does it make no sense? Have you never had to scrape a web page or read a CSV file? > You can construct and split the string any way you like: > > >>> s = '123SURPRISE456' > >>> s.split('SURPRISE') > > ['123', '456'] > > Notice that the results aren't ints, they are strings. Duh. I took for granted you knew how to convert an string to an integer. > > To get an int literal, you currently type something like 123456. 123 456 > is currently not valid in Python, it raises an SyntaxError. Try it for > yourself: So this proposal would only apply to string literals at compile time, not running programs? > > >>> 123 456 > > File "", line 1 > 123 456 > ^ > SyntaxError: invalid syntax And I want the same error to occur if my CSV parser tries to convert '123 456' into a single number. I don't want it to assume the number is '123456'. > > If you want two numbers, you would do exactly the same thing you would now: > > >>> x, y = 123, 456 > >>> print "x is %d and y is %d" % (x, y) > > x is 123 and y is 456 > > -- > Steven From JHoover at fbi.gov Sun Jul 22 20:31:59 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Sun, 22 Jul 2007 20:31:59 -0400 Subject: idiom for RE matching In-Reply-To: <1185134710.574141.106490@57g2000hsv.googlegroups.com> References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> <1185134710.574141.106490@57g2000hsv.googlegroups.com> Message-ID: memracom at yahoo.com wrote: > Have you read and understood what MULTILINE means in the manual > section on re syntax? > > Essentially, you can make a single pattern which tests a match against > each line. > > -- Michael Dillon No, I have not looked into this - thank you. RE's are hard enough to get into that I didn't want the added complication of the flags. Now that I'm comfortable writing patterns I guess I never got around to the rest of the options. From steve at holdenweb.com Mon Jul 16 14:18:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 16 Jul 2007 14:18:48 -0400 Subject: Discover instance variables In-Reply-To: <1184606748.599294.293570@n60g2000hse.googlegroups.com> References: <1184606748.599294.293570@n60g2000hse.googlegroups.com> Message-ID: JonathanB wrote: > Ok, I know there has to be a way to do this, but my google-fu fails me > (once more). I have a class with instance variables (or should they be > called attributes, I'm newish to programming and get really confused > with OO sometimes), like the one in this example: > Instance variable are indeed attributes, but you are doing fine with the language so don't worry about it. > class Foo(): > self.a = "bar" > self.z = "test" > self.var = 2 > That's unlikely to work, though: the code is in the context of the class, not one of its methods, so unless you happen to be declaring a class inside another class's method it's unlikely that there's going to be a "self" around when those three lines execute. What you probably want is something like what follows (I am running it interactively so I know I am telling the truth: it keeps me honest :-). You should get used to using the interpreter to check your hypotheses - it would have told you you were making a mistake above as soon as you tried to create a Foo. >>> class Foo: ... a = "bar" ... z = "test" ... var = 2 ... You can check that Foo (the class) has these attributes: >>> Foo.a 'bar' > foo = Foo() > Now foo is an instance of the Foo class. Class attributes can also be accessed through instances: >>> foo = Foo() >>> foo.var 2 >>> Binding an instance attribute, however, doesn't change the class, so you can use class attributes as a kind of "default" for instance. >>> foo.a = "foo" >>> foo.a 'foo' >>> Foo.a 'bar' >>> > I want to print a list of the variables (strings, integers, etc) in > Foo, without knowing their names. So that the user who needs to change > a peice of information can view the variable list, enter the name of > the variable they need to change and then make the change. This is > what I'd like a sample run to look like: > > Attributes for foo: > a = bar > z = test > var = 2 > > Change: a > New value: foobar > Change made! > > I can handle the formatting and changing the variable itself, no > problem, but how do I get a list of all the variables in a class > instance? I almost put a list in there called vars and appended all > the variables to it so I could iterate the list, but this sounds like > something useful enough that someone has come up with a better way to > do it than that. It almost looks like self.__dir__() is what I want, > but that returns methods as well, correct? I only want variables, but > I can't think of how to do a list comprehension that would remove the > methods. > [name for name in dir(x) if not callable(name) and not name.startswith("__")] might come close - I presume you don't want __doc__ and the 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 zentraders at gmail.com Tue Jul 17 15:39:23 2007 From: zentraders at gmail.com (Zentrader) Date: Tue, 17 Jul 2007 12:39:23 -0700 Subject: how to compile python to have gtk and Tkinter modules in Linux environment. In-Reply-To: <1184642166.978342.154660@o11g2000prd.googlegroups.com> References: <1184642166.978342.154660@o11g2000prd.googlegroups.com> Message-ID: <1184701163.076849.27740@z28g2000prd.googlegroups.com> On Jul 16, 8:16 pm, cfp... at gmail.com wrote: > import gtk and Tkinter modules. Those don't seem to be included when > I use the default ./configure or python setup.py. Tkinter is supposed to be included by default, although that depends on who's Python you are using and ./configure. You have to install PyGTK separately, at least on Linux. Both have to be somewhere in your PYTHONPATH so Python can find them. Also, Tkinter depends on TCL/ Tk. All of this sounds more intimidating than it really is. If you are on Linux, Python should be in /usr/lib and you can check for Tkinter in ?usr/lib/python/lib-tk. What os are you using and was Python included or did you install it yourself? If so, where did you download Python and was it a binary or source? From deviantbunnylord at gmail.com Sun Jul 8 13:10:04 2007 From: deviantbunnylord at gmail.com (Brad) Date: Sun, 08 Jul 2007 10:10:04 -0700 Subject: Learning Basics Message-ID: <1183914604.792954.80260@c77g2000hse.googlegroups.com> So I've been studying python for a few months (it is my first foray into computer programming) and decided to write my own little simple journaling program. It's all pretty basic stuff but I decided that I'd learn more from it if more experienced programmers could offer some thoughts on how I could do things better. #simple little journal from time import asctime myjournal=file('journal.txt','a+') formatter="*"*80+"\n" todaysdate=asctime() myjournal.write(formatter) myjournal.write(todaysdate + "\n\n") loop="set" while loop!=':a': loop=raw_input(':') if loop!=':a': myjournal.write(loop+"\n") if loopz==':a': myjournal.close() #end of stuff So I'd appreciate some good feedback or ideas. From avassalotti at gmail.com Mon Jul 2 15:12:29 2007 From: avassalotti at gmail.com (avassalotti at gmail.com) Date: Mon, 02 Jul 2007 19:12:29 -0000 Subject: Rappresenting infinite In-Reply-To: <1182940919.351011.267020@n2g2000hse.googlegroups.com> References: <1182940919.351011.267020@n2g2000hse.googlegroups.com> Message-ID: <1183403549.523918.262500@m36g2000hse.googlegroups.com> On Jun 27, 6:41 am, andrea wrote: > I would like to have a useful rappresentation of infinite, is there > already something?? > > I was thinking to something like this > > class Inf(int): > """numero infinito""" > def __init__(self,negative=False): > self.negative = negative > def __cmp__(self,y): > """infinito maggiore di qualasiasi cosa""" > if self.negative: > return -1 > else: > return 1 > def __repr__(self): > """docstring for __repr__""" > if self.negative: > return '-inf' > else: > return 'inf' > def __add__(self,y): > """addizione con infinito""" > return self > def __mul__(self,y): > """moltiplicazione""" > import types > if isinstance(y,types.IntType): > if y > 0: > return self > if y == 0: > return 'indefinito' > else: > return Inf(negative) > > I'd like to be able to compare between any value and infinite always > getting the right result, and paying attention to the special cases > like > inf / inf => not determinate float('inf') works well, no? >>> inf = float('inf') >>> inf / inf nan >>> -inf -inf >>> inf / 0 ZeroDivisionError: float division >>> 1 / inf 0.0 >>> 0 * float('inf') nan From mccredie at gmail.com Mon Jul 16 20:30:58 2007 From: mccredie at gmail.com (Matimus) Date: Tue, 17 Jul 2007 00:30:58 -0000 Subject: In a dynamic language, why % operator asks user for type info? In-Reply-To: <1184631007.920803.147790@j4g2000prf.googlegroups.com> References: <1184631007.920803.147790@j4g2000prf.googlegroups.com> Message-ID: <1184632258.229090.279010@e16g2000pri.googlegroups.com> I don't have a good answer for you, but you might be interested to read this: http://python.org/dev/peps/pep-3101/. Which according to a recent blog post by BDFL is going to be how string formatting is done in Python3000. The character doesn't specify the type to expect, but the formatting function. So, %s calls a string formatter, %r calls repr and %x calls a hex formatter. The there may be multiple formatters that produce different results for given types. An integer can use %d,%e,%f,%s,%x or %r, and they all produce slightly different results. Also, the formatters take parameters. Such as "%+010.5f"%(1.23) which produces "+001.23000". From dstromberg at datallegro.com Fri Jul 13 19:50:23 2007 From: dstromberg at datallegro.com (Dan Stromberg - Datallegro) Date: Fri, 13 Jul 2007 16:50:23 -0700 Subject: Python Subprocess module References: Message-ID: You could start up a pty and do your own Pexpect-like thing, using read/readline/write. However, this may not be portable to windows. Maybe if you get the python that comes with cygwin, or build your own python under the cygwin environment - that might be more likely to get you pty's under windows. On Fri, 13 Jul 2007 17:15:49 -0400, Dave Sampson wrote: > hey folks, > > A simple question hopefully. despite all my searching I have not found a > satisfactory response. > > The goal. Interact with a command line program. Simple enough, but the > key is INTERACT. > > I tried the shell and comand approaches but that initiates, it does not > allow interaction with the programs. > > So then I went with Popen and such... which then led to the subprocess > module. > > I can create the object and read a few lines of output. but if I go too > far then the program hangs. the number of lines will differ depandening > on many function including the format of an input file so I can;t > hardcode how many lines to read. > > I want to read all of STDOUT without failing because I went out of range. > > next I want to read the final line of the output because it tells me > what is required for the next line of input. > > I am supposed to be able to entre 'y' and return for the program to > continue if I agree with what I see in the stdout. > > A problem exists though that I have tried > 'y' > 'y\n' > 'y\r' > > and nothing seems to get the program going again for I still cant; read > past the same point in the standard output. then I have to kill and > start over. > > So the next approach included looking at Pexpect, which got realy > confusing realy fast and despite running fedora core and python 2.4.4 I > would like my application to be cross platform and there is no Pexpect > for Windows That I can see. > > I have checked out many mailing lists and posts and tutorials but they > all admit to not be samples of complex interactivity. I guess I am > having that special case. > > ASPN Python cookbok provided some code for a new Popen Class that allows > for interaction but I don't think I need to go that root.... > > I am essentialy trying to build and Python wrapper for a coomand line > program that i want to build a GUI around. > > Any links or suggestions would be great. Unfortunaetly I don't > understand that abstract concepts in the manual reference. I am fresh in > the python world and find examples better than technical abstracts. > > Cheers From kusarpi at gmail.com Sat Jul 21 18:03:19 2007 From: kusarpi at gmail.com (KU) Date: Sat, 21 Jul 2007 22:03:19 -0000 Subject: The Convenience of Online Learning. The Benefits of a Respected Degree.Try Ellis College for Free. Message-ID: <1185055399.940253.185620@z24g2000prh.googlegroups.com> A fully accredited extension of The New York Institute of Technology (NYIT), Ellis College gives you the prestige of earning your Bachelor's Degree from a respected university with the convenience of learning online on your own schedule. Whether you're looking to begin a new career or advance an existing one, Ellis offers an array of flexible online Undergraduate Degree programs to help you achieve your goal. Fully Accredited. Esteemed Faculty. An academic division of the New York Institute of Technology, Ellis College is accredited by the Middle States Commission on Higher Education, one of six regional accrediting bodies for higher education recognized by the U.S. Secretary of Education. Every Ellis instructor holds a Ph.D. or Masters Degree in their subject matter, with nearly half of all teaching faculty holding a Doctorate or other terminal degree. Get a free guest pass to Ellis College and experience a fully- accredited online college like no other. You'll have access to Ellis CourseBites? mini-courses, educational Webcasts, and our interactive course demonstrations. Getting started is easy! Just fill out the form to get your free pass. Click Here:http://www.anrdoezrs.net/ot114fv2rz1GJKJOOOIGIHLOJLKI From martin at v.loewis.de Sun Jul 29 00:40:35 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 29 Jul 2007 06:40:35 +0200 Subject: Why no maintained wrapper to Win32? In-Reply-To: <59kna3p8r0cu2gk6hs5lbig8cjj8klatju@4ax.com> References: <46ab694e$0$17577$9b622d9e@news.freenet.de> <59kna3p8r0cu2gk6hs5lbig8cjj8klatju@4ax.com> Message-ID: <46ac1a43$0$7536$9b622d9e@news.freenet.de> >> Why does it mean that? The Win32 APIs for GUI are up-to-date; they >> don't need further development. Win32 itself stopped years ago. >> You can write GUI applications with PyWin32 just fine. > > Besides the total lack of documentation, you mean that nothing was > added to the Win32 API since PyWin32 was last updated? Why do you say that the Win32 API lacks documentation? I find the documentation at msdn.microsoft.com to be quite useful. Yes, there haven't been many changes to Win32 in recent years (there haven't been many system releases in the first place). Most additions did not concern GUI programming, which is what you were after, and even those that are recent additions are rather rarely needed, so you likely won't miss them. If you do, ask Mark Hammond to add them. Regards, Martin From martin at v.loewis.de Sun Jul 1 11:25:06 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 01 Jul 2007 17:25:06 +0200 Subject: object references/memory access In-Reply-To: <4687c63b$0$22513$9b622d9e@news.freenet.de> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> Message-ID: <4687c752$0$23862$9b622d9e@news.freenet.de> > b) use a single Python server (possibly shared with the database > process), and connect this to Apache through the > reverse proxy protocol. Following up to myself: Instead of using a reverse proxy, you can also implement the FastCGI protocol in the server. Regards, Martin From vp_rajan at yahoo.com Thu Jul 19 13:50:52 2007 From: vp_rajan at yahoo.com (vp_rajan at yahoo.com) Date: Thu, 19 Jul 2007 10:50:52 -0700 Subject: IMPORTANT WEBSITES ARE FOUND OPEN ALL WEBSITES AND MAKE MORE USE OF IT....... 1.latest antivirussoftware 2.library softwares 3.software projects 4.software cracks 5.download accelerator plus 6.mobile themes 7.mobile softwares(for nokia, samsung, sonyericsson) 8.mobile hot videos(.3gp) 9...........ALL SOFTWARES PROVIDED BY GOOGLE IN SEPERATE ICONS and many more useful.................. ....................................open it and make use of it www.freewebs.com/importantsitelinks Message-ID: <1184867452.421810.247920@z28g2000prd.googlegroups.com> IMPORTANT WEBSITES ARE FOUND OPEN ALL WEBSITES AND MAKE MORE USE OF IT....... 1.latest antivirussoftware 2.library softwares 3.software projects 4.software cracks 5.download accelerator plus 6.mobile themes 7.mobile softwares(for nokia,samsung,sonyericsson) 8.mobile hot videos(.3gp) 9...........ALL SOFTWARES PROVIDED BY GOOGLE IN SEPERATE ICONS and many more useful.................. ....................................open it and make use of it www.freewebs.com/importantsitelinks From daniel at zelisko.net Sun Jul 1 08:52:03 2007 From: daniel at zelisko.net (Drex) Date: Sun, 01 Jul 2007 05:52:03 -0700 Subject: how to send files via bluetooth with python to a mobile Message-ID: <1183294323.556314.293860@m36g2000hse.googlegroups.com> Hi, I have been looking on the internet for some info about sending files from PC to a mobile phone (I have a nokia 6288) but I was not able to find anything. there is a lot of info how to transfer files from a symbian phone to a pc, but nothing about sending them in the oposite direction. would anybody point me to some resources on the topic? thanks, regards dz From prikar20 at gmail.com Wed Jul 4 16:55:17 2007 From: prikar20 at gmail.com (prikar20 at gmail.com) Date: Wed, 04 Jul 2007 20:55:17 -0000 Subject: using subprocess for non-terminating command In-Reply-To: References: <1183549118.773813.132940@r34g2000hsd.googlegroups.com> <1183550943.531211.306410@n60g2000hse.googlegroups.com> <20070704143641.GA3434@gmail.com> <16651e80707040823y7d8103bbl34da35a776b147f@mail.gmail.com> Message-ID: <1183582517.967835.71810@e16g2000pri.googlegroups.com> On Jul 4, 12:29 pm, "O.R.Senthil Kumaran" wrote: > * Jerry Hill [2007-07-04 11:23:33]: > > > > > That's because you tied stdin to a pipe in your Popen call, but then > > tried to read from stdout. Try this instead: > > My mistake. I had just 'typed' the command in the mail itself and forgot to > include the stdin, stdout, and stderr and mentioned it as hung based on some > recollection. > > > > > >>> process = subprocess.Popen("ping -c 10 127.0.0.1", > > stdout=subprocess.PIPE, shell=True) > > >>> process.stdout.readlines() > > I tried it again and found that giving the -c 10 returns a well defined > output. > Only when the program has executed and the output available, subprocess can > read through PIPE's stdout it seems ( not at any other time). > With killing, I loose the output. > > >>> process = subprocess.Popen('ping 10 127.0.0.1', stdin=subprocess.PIPE, > > stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True) I think you meant ping -c 10 (and not ping 10). If you pass first arg as string, are you sure you didn't get an exception? I get one if I use 'ping -c 10 ' -- because looks like subprocess is searching for an executable named as "ping -c 10 ..." (not just 'ping'). So I sent in a sequence and it all worked as expected (I didn't have shell=True, but it shouldn't matter in getting the required output). Try the sequence as first arg. >>> process = subprocess.Popen('ping -c 10 127.0.0.1', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) Traceback (most recent call last): File "", line 1, in File "/auto/xxxkarthikxxx/python251/lib/python2.5/subprocess.py", line 593, in __init__ errread, errwrite) File "/auto/xxxkarthikxxx/python251/lib/python2.5/subprocess.py", line 1079, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory >>> process = subprocess.Popen('ping -c 10 127.0.0.1'.split(), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) >>> print process >>> print process.pid 13435 >>> print process.stdout.read() PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data. 64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.025 ms 64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.006 ms 64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.005 ms 64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.004 ms 64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.011 ms 64 bytes from 127.0.0.1: icmp_seq=5 ttl=64 time=0.007 ms 64 bytes from 127.0.0.1: icmp_seq=6 ttl=64 time=0.020 ms 64 bytes from 127.0.0.1: icmp_seq=7 ttl=64 time=0.006 ms 64 bytes from 127.0.0.1: icmp_seq=8 ttl=64 time=0.006 ms 64 bytes from 127.0.0.1: icmp_seq=9 ttl=64 time=0.006 ms --- 127.0.0.1 ping statistics --- 10 packets transmitted, 10 received, 0% packet loss, time 9013ms rtt min/avg/max/mdev = 0.004/0.009/0.025/0.007 ms, pipe 2 >>> -- Karthik > > >>> process.pid > 3475 > >>> import os > >>> import signal > >>> os.kill(process.pid,signal.SIGINT) > >>> process.stdout.read() > '' > >>> # required output is lost! > > -- > O.R.Senthil Kumaranhttp://uthcode.sarovar.org From gherron at islandtraining.com Tue Jul 17 18:21:45 2007 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 17 Jul 2007 15:21:45 -0700 Subject: really small values In-Reply-To: References: Message-ID: <469D40F9.9060202@islandtraining.com> Dee Asbury wrote: > In multiplying a value of xe^-325 with ye^-4, Python is returning zero. How > do I get it to give me back my tiny value? > > Thanks! > Dee > > > Of course, Python is doing no such thing. The floating point arithmetic hardware on your machine is doing the multiplication and giving that result. Different hardware would probably not solve the problem as almost all hardware these days uses the IEEE spec for floating point numbers. In that spec, a 64bit floating point value has a lower limit on the exponent that you are running into. However, there are software packages that represent numbers (integer and floating point) with larger collections of bit. Try looking at GMP at for one such package: http://gmplib.org/ Good luck, Gary Herron From ryushi5 at gmail.com Mon Jul 2 12:38:03 2007 From: ryushi5 at gmail.com (Thomas) Date: Mon, 2 Jul 2007 12:38:03 -0400 Subject: need help with win32com Message-ID: I want to be able to access an excel file and extract the code from the macro that is in the file. How can I do this? -- ~Thomas~ From http Tue Jul 3 03:50:52 2007 From: http (Paul Rubin) Date: 03 Jul 2007 00:50:52 -0700 Subject: Correct abstraction for TK References: <1183412267.513714.183800@q75g2000hsh.googlegroups.com> Message-ID: <7xlkdyapsz.fsf@ruckus.brouhaha.com> luke.hoersten at gmail.com writes: > I'm looking for a good example of how to correctly abstract TK code > from the rest of my program. I want to just get some user info and > then get 4 values from the GUI. Right now I've written it OOP per the > examples on python.org but it doesn't seem to be meshing very well > with the rest of my project. Simplest: just have gui operations call the application code. The application main loop is just the gui event loop. Example (first tk program I ever wrote, and one of my first python programs): http://www.nightsong.com/phr/python/calc.py That might be enough for what you're doing. Fancier: put gui in separate thread. Be careful, it's not reentrant; all communication with the application has to be through queues, sort of like writing a miniature web server. Most straightforward is to pass tuples like (function, args, **kwargs) through the queues, where the opposite end invokes the function on the arg list. There are some recipes in the Python cookbook for triggering the event loop on a periodic timeout from inside tkinter. See also "model-view-controller" for a more complex design approach intended to separate the interface from the application logic. Finally, consider total separation by embedding an http server in the application, so the gui is a web browser and you write a web app. It's often easier to code a simple html interface than to mess with the damn Tk widgets and trying to get them to look decent on the screen, plus it lets you easily put the client on a remote machine, support multiple clients simultaneously, etc. From theokok2000 at gmail.com Sun Jul 1 18:05:26 2007 From: theokok2000 at gmail.com (theokok2000 at gmail.com) Date: Sun, 01 Jul 2007 15:05:26 -0700 Subject: pos to blepeis Message-ID: <1183327526.784509.108260@q69g2000hsb.googlegroups.com> http://kokonis.aygoystinos.googlepages.com/ http://theologos.kokkonis.googlepages.com/ From crcarleRemoveThis at BOGUSsandia.gov Fri Jul 13 20:12:33 2007 From: crcarleRemoveThis at BOGUSsandia.gov (Chris Carlen) Date: Fri, 13 Jul 2007 17:12:33 -0700 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: Aahz wrote: > In article , > Chris Carlen wrote: >>From what I've read of OOP, I don't get it. > > For that matter, even using OOP a bit with C++ and Perl, I didn't get it > until I learned Python. > >>The problem for me is that I've programmed extensively in C and .asm on >>PC DOS way back in 1988. > > Newbie. ;-) > > (I started with BASIC in 1976.) Heh heh, I actually first programmed when the RadioShack TRS-80 came out. I think I saw it first in 1978 when I was 11. I would hang out in the store for hours writing crude video games. > My experience is that learning GUI programming is difficult. Moreover, > GUI programming in C involves a lot of boilerplate that can be automated > more easily with Python. So I think this will be a better solution. > > Note very very carefully that Python does not require an OOP style of > programming, but it will almost certainly be the case that you just > naturally start using OOP techniques as you learn Python. Thanks for the input! -- Good day! ________________________________________ Christopher R. Carlen Principal Laser&Electronics Technologist Sandia National Laboratories CA USA crcarleRemoveThis at BOGUSsandia.gov NOTE, delete texts: "RemoveThis" and "BOGUS" from email address to reply. From bj_666 at gmx.net Tue Jul 31 02:03:55 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Jul 2007 06:03:55 GMT Subject: Reading a two-column file into an array? References: <1185857837.610635.206270@e9g2000prf.googlegroups.com> Message-ID: <5h81mbF3j641tU1@mid.uni-berlin.de> On Mon, 30 Jul 2007 21:57:17 -0700, Nagarajan wrote: > a = [] > import csv > reader = csv.reader(open("filename", "r"), delimiter='\t' ) > for row in reader: > a.append( row ) I would keep a reference to the file to close it properly and the loop can be replaced by a call to `list()`: import csv def main(): data_file = open('filename', 'rb') a = list(csv.reader(data_file, delimiter='\t')) data_file.close() Ciao, Marc 'BlackJack' Rintsch From michele.simionato at gmail.com Fri Jul 6 03:48:13 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 6 Jul 2007 00:48:13 -0700 Subject: Writing a read only attribute In-Reply-To: References: Message-ID: <1183707977.416949.170840@c77g2000hse.googlegroups.com> On Jul 6, 8:27 am, Fabrizio Pollastri wrote: > Hello, > it is possible to force in some way a write to a read-only attribute of > a python object? In which case? > Thanks for any answer. > > F. Pollastri What do you mean by read-only attribute? If you are trying to change attributes of built-in objects, there is no hope: >>> 'astring'.upper = 2 --------------------------------------------------------------------------- exceptions.AttributeError AttributeError: 'str' object attribute 'upper' is read-only If the read-only attribute has been implemented via a property, there is a way to write it, but you should tell us more about your case. Michele Simionato From nogradi at gmail.com Tue Jul 10 10:07:57 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 10 Jul 2007 16:07:57 +0200 Subject: Dynamic method In-Reply-To: References: Message-ID: <5f56302b0707100707k2c7128e0u2aa64dea9e0e2cde@mail.gmail.com> > I have an issue I think Python could handle. But I do not have the knowledge > to do it. > > Suppose I have a class 'myClass' and instance 'var'. There is function > 'myFunc(..)'. I have to add (or bind) somehow the function to the class, or > the instance. Any help, info or point of reference is wellcome.... How about this (note the first argument 'self' which is the instance itself in the second case): def method_for_instance( message ): print message def method_for_class( self, message ): print message class myClass( object ): pass inst = myClass( ) inst.method = method_for_instance inst.method( 'hello' ) myClass.method = method_for_class inst = myClass( ) inst.method( 'hello' ) From ed at leafe.com Wed Jul 11 14:01:33 2007 From: ed at leafe.com (Ed Leafe) Date: Wed, 11 Jul 2007 14:01:33 -0400 Subject: bool behavior in Python 3000? In-Reply-To: <469472f4$0$1293$9b622d9e@news.freenet.de> References: <5ficp9F3cram2U2@mid.individual.net> <469472f4$0$1293$9b622d9e@news.freenet.de> Message-ID: On Jul 11, 2007, at 2:04 AM, Stargaming wrote: > No, I think Bjoern just wanted to point out that all those binary > boolean operators already work *perfectly*. You just have to emphasize > that you're doing boolean algebra there, using `bool()`. > "Explicit is better than implicit." I think that the assignability to the names 'True' and 'False' is incorrect, or at the very least subject to all sorts of odd results. Look at this: >>> True, False (True, False) >>> True = False >>> True, False (False, False) >>> True == False True >>> (True == False) == True False Yeah, I know: "Doctor, it hurts when I do this". Doc: "So don't do that!". I haven't kept up with all the Python 3000 docs, so does anyone know if True and False will become true keywords, and whether oddball stuff like the above will no longer be possible? -- Ed Leafe -- http://leafe.com -- http://dabodev.com From gagsl-py2 at yahoo.com.ar Sun Jul 22 22:24:28 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 22 Jul 2007 23:24:28 -0300 Subject: Re-running unittest References: Message-ID: En Sun, 22 Jul 2007 17:43:03 -0300, Israel Fern?ndez Cabrera escribi?: > I'm writing some code that automatically execute some registered unit > test in a way to automate the process. A sample code follows to > illustrate what I'm doing: > > > class PruebasDePrueba(unittest.TestCase): > def testUnTest(self): > a = 2 > b = 1 > self.assertEquals(a, b) > > def runTests(): > loader = unittest.TestLoader() > result = unittest.TestResult() > suite = loader.loadTestsFromName("import_tests.PruebasDePrueba") > suite.run(result) > print "Errores: ", len(result.errors) > print "Fallos: ", len(result.failures) > > if __name__ == "__main__": > runTests() > raw_input("Modify [fix] the test and press ENTER to continue") > > > The code executes the tests from the class PruebasDePrueba, as the > user to "fix" the failing test and then executes the tests again after > ENTER is pressed. > The test's initial state is "fail" so, equaling the values of a or b > in the second execution I wait the test does not fails again, but it > does. > I've changed the original code in very different ways trying to figure > out what is wrong with it but no success > The problem is not reproduced if instead of loading the test from the > TestCase (import_tests.PruebasDePrueba) they are loaded referring the > container module and this behaves like this because I wrote a class > that inherits from unittest.TestLoader abd re-defines the > loadTestsFromModule(module) then every time this method is called, the > module is reloaded via "reload" python's function. I would like to do > the same with TestCases. I'm a bit confused. Perhaps the description above does not match the code. The code does not use reload, and has no loops, so it is executed only once. The way I interpret it: I run the script, the test fails; I "fix" testUnTest; I run the script again, it passes. When I say "I run the script", I mean typing "python import_tests.py" at the console, or similar. Perhaps you are running it from inside another environment, like IDLE, and you keep objects created which won't notice the changed code, even if you use reload(). The answer would be: don't do that. Read the last comments in the reload documentation Another thing I don't understand, is that usually one fixes the CODE until it passes the tests; fixing the TESTS so the code passes looks a bit strange. > I have written this problem to several other python lists but I have > not received any answer, hope this time is different, > I'd like to thaks in advance, regards Perhaps you have to explain it further. If your problem is the usage of reload, as I think, this has nothing to do with unit tests, and worse, your code does not even show how you use that function. -- Gabriel Genellina From kyosohma at gmail.com Tue Jul 24 09:11:19 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 24 Jul 2007 06:11:19 -0700 Subject: wxPython Internationalization In-Reply-To: <1185258717.905849.20330@q75g2000hsh.googlegroups.com> References: <1185258717.905849.20330@q75g2000hsh.googlegroups.com> Message-ID: <1185282679.827477.62220@w3g2000hsg.googlegroups.com> On Jul 24, 1:31 am, "mojocojo2... at gmail.com" wrote: > I know this may have a very simple answer, nonetheless. I am wishing > to find the cleanest and most pythonic way of implementing the > following: > > I am creating a internationalized application in wxPython and have > sorted the directory structure in the following manner: > > start.py > > > metamenus.py > main.py > > [various files] > > [various files] > > Here's the code for the files shown above: > > # start.py > > if __name__ == '__main__': > import .main > app = .MyApp(0) > app.MainLoop() > > # main.py > > import wx > from metamenus import MenuBarEx > > class MyFrame(wx.Frame): > def __init__(self, parent, id, title): > wx.Frame.__init__(self, parent, id, title, > wx.DefaultPosition, wx.Size(380, 250)) > > menu = \ > [[ > [_('&File')], > [_('Open a new document')], > [_('Save the document')] > ], > [ > [_('&Edit')] > ], > [ > [_('&View')] > ], > [ > [_('&Quit\tCtrl+Q')], > [_('Quit the Application')], > [_('&Help')] > ]] > > self.mainmenu = MenuBarEx(self, menu) > > def OnQuit(self, event): > self.Close() > > class MyApp(wx.App): > def OnInit(self): > self.frame = MyFrame(None, -1, 'Title') > self.frame.Raise() > self.frame.Refresh() > self.frame.Show(True) > return True > > So here's my question. I wish to add the following code so that the _ > method will become of use. > > Here is the codehttp://wiki.wxpython.org/Internationalization > recommends: > > import wx > import os > import platform > import codecs > import sys > import gettext > > def main(): > # initialise language settings: > path = sys.path[0].decode(sys.getfilesystemencoding()) > try: > langIni = codecs.open(os.path.join(path,u'language.ini'),'r', > 'utf-8') > except IOError: > language = u'en' #defaults to english > pass > else: > language = langIni.read() > > locales = { > u'en' : (wx.LANGUAGE_ENGLISH, u'en_US.UTF-8'), > u'es' : (wx.LANGUAGE_SPANISH, u'es_ES.UTF-8'), > u'fr' : (wx.LANGUAGE_FRENCH, u'fr_FR.UTF-8'), > } > mylocale = wx.Locale(locales[language][0], wx.LOCALE_LOAD_DEFAULT) > langdir = os.path.join(path,u'locale') > Lang = gettext.translation(u'messages', langdir, > languages=[language]) > Lang.install(unicode=1) > > if platform.system() == 'Linux': > try: > # to get some language settings to display properly: > os.environ['LANG'] = locales[language][1] > > except (ValueError, KeyError): > pass > > #-> Code to launch application goes here. <-# > > if __name__ == '__main__': > if 'unicode' not in wx.PlatformInfo: > print "\nInstalled version: %s\nYou need a unicode build of > wxPython to run this application.\n"%version > else: > main() > > So my question is, where would the best place be to implement the code > above? In start.py, main.py, in a separate file altogether? The > problem I seem to be having is needing an instance of wx.App before > the code recommended by thehttp://wiki.wxpython.org/Internationalization > can become of use. > > I've come up with solutions to my dilemma but none seem to be > especially clean. Any recommendations would be great. Also if any > clarifications are needed let me know. > > Thanks You should post this question to the wxPython user's group. They'll be able to give better advice. See http://www.wxpython.org/maillist.php Mike From fattie at tpu.ru Fri Jul 27 11:05:48 2007 From: fattie at tpu.ru (Valentina Vaneeva) Date: Fri, 27 Jul 2007 22:05:48 +0700 Subject: Imported globals? Message-ID: <81803fb516f0f2b111f0654f40adcf9d@tpu.ru> Hi, I'm new to Python and I've found something in its interpreter that I don't quite understand, and I don't really know how to correctly formulate a search query. Here's the question. If we have a file module_a.py with the following content: | #!/usr/bin/env python | | value = 'initial' | | def change_value(): | global value | value = 'changed' and a file module_b.py: | #!/usr/bin/env python | | from module_a import value, change_value | | change_value() | print value Then, if we run module_b.py, it will print "initial". However, if one adds to the end of module_a.py this line: | change_value() The script module_b.py will print "changed". It seems that in the first case change_value() called in module_b.py ignores the global statement. Is it so? Why? What happens in the second case? I really don't get it. Thanks! Cheers, Valia From seandavi at gmail.com Sat Jul 21 16:54:33 2007 From: seandavi at gmail.com (Sean Davis) Date: Sat, 21 Jul 2007 20:54:33 -0000 Subject: pyodbc on linux Message-ID: <1185051273.979145.285050@22g2000hsm.googlegroups.com> I have read a couple of blogs suggesting that pyodbc is buildable under linux. I am running suse 10.2 on a 64-bit intel machine with unixODBC installed. Upon building, I get a slew of pretty horrid looking errors that make me wonder if this is supposed to work. Can anyone at least confirm that this is possible before I try to pursue things further? Thanks, Sean From moranar at gmail.com Sun Jul 1 06:04:49 2007 From: moranar at gmail.com (Adriano Varoli Piazza) Date: Sun, 01 Jul 2007 03:04:49 -0700 Subject: howto resend args and kwargs to other func? In-Reply-To: <1183282733.179683.174350@c77g2000hse.googlegroups.com> References: <1183279997.244378.105810@n60g2000hse.googlegroups.com> <1183280667.542964.175570@u2g2000hsc.googlegroups.com> <1183282733.179683.174350@c77g2000hse.googlegroups.com> Message-ID: <1183284289.874324.228570@n60g2000hse.googlegroups.com> dmitrey ha escrito: > Thanks all, I have solved the problem. > D. If you take the time to comment this, it is good form to comment on how you solved the problem, so the next one wondering about it can find an answer before posting. -- Saludos Adriano From stefan.behnel-n05pAM at web.de Tue Jul 10 14:33:36 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 10 Jul 2007 20:33:36 +0200 Subject: xml yml and dependency hell In-Reply-To: References: Message-ID: <4693D100.1000209@web.de> Rustom Mody wrote: > yaml by its indent-orientation is quite pythonic. In comparison xml > is cumbersome and laborious. > > Strangely ruby supports yaml out of the box but python requires a > third party package PyYAML. > > Now this may not seem like a big deal for us -- installing pyYAML > takes all of one minute -- but it may not be so to others as I > recently learned. > > I conducted a python training for a corporate in which I showed among > other things that yaml is much neater than xml. They agreed that it > was neat but were reluctant to consider it because it adds dependency > headaches at a later point with their customers. > > > > So is it likely that yaml will make it to the standard python library > at some point?? That's up to the maintainers of PyYAML. If they want to get it in, there will be ways to get there. If they do not want to - unlikely, unless someone else takes up the work. But it's definitely easier if the authors decide to put it in. Besides, why would you assume any dependency headaches? There's EasyInstall and setuptools if you need them. Stefan From guerrerocarlos at gmail.com Mon Jul 9 00:09:20 2007 From: guerrerocarlos at gmail.com (Carlos Guerrero) Date: Mon, 9 Jul 2007 06:09:20 +0200 Subject: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc) In-Reply-To: <1183948962.3165.54.camel@localhost.localdomain> References: <1183939608.088756.178320@m37g2000prh.googlegroups.com> <1183947480.922943.8370@o11g2000prd.googlegroups.com> <1183948962.3165.54.camel@localhost.localdomain> Message-ID: <36a3bc380707082109m1d222acfp35fdd7a5662e009f@mail.gmail.com> One "generic" way is using your parallel port for outputting voltages that would control Relays [2] that would be conected to the motor. Parapin [1] is the easiest way i know to work with parallel ports but its for C++, the python binding is still being developed [2]. [1] http://parapin.sourceforge.net/ [2] http://en.wikipedia.org/wiki/Relay http://es.wikipedia.org/wiki/Rel%C3%A9 <- these graphics are kinda better [3] http://pyserial.sourceforge.net/pyparallel.html On 7/9/07, Carsten Haese wrote: > On Sun, 2007-07-08 at 19:18 -0700, socialanxiety at gmail.com wrote: > > On Jul 8, 5:37 pm, Carsten Haese wrote: > > > On Sun, 2007-07-08 at 17:06 -0700, socialanxi... at gmail.com wrote: > > > > i hope someone here can help me. > > > > > > > basically, me and my friend have a summer project. > > > > > > > in this project, we need something that would basically function as a > > > > blender. we know we'll need to buy a motor that spins, but what we're > > > > having trouble with is figuring out how to program it. we want to be > > > > able to control the speed of the motor. how would we accomplish this? > > > > > > > i'm new to all of this, so i'm having a hard time wrapping my mind > > > > around how it'd be possible to program one of those things :\ > > > > > > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then > > > > turn the other direction. > > > > > > > would you program it the same way you would on a personal computer > > > > (via c, python, etc)? > > > > > > The answers to your questions depend very much on what you're working > > > with and how the motor is controlled. Is this supposed to be a > > > self-contained machine, or is it supposed to be connected to a personal > > > computer as a peripheral device? > > > [...] > > I would like the robot to be self contained. basically, I'd like to be > > able to program functions in python, ex: > > > > while True: > > motor.rotate(1) > > Good luck with that. Your best bet IMHO is to find a single-board > computer (commonly referred to as SBC) that is small enough to fit your > form-factor, capable of running Linux, and equipped with a suitable I/O > interface (e.g. serial or parallel port). In theory, this should allow > you to put Linux and Python on it and control your motor in Python as if > it were a peripheral device connected to a personal computer. In > practice, I've never done anything like this, and the devil is in the > details that you'll need to work out for yourself. > > -- > Carsten Haese > http://informixdb.sourceforge.net > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- /* Carlos A. Guerrero M. [Alias: Sid] */ /* ------------------------------- */ /* Linux User 390240 */ http://guerrerocarlos.blogspot.com http://guerrerocarlos.wordpress.com http://www.tooche.com.ve From see_website at mindprod.com.invalid Sun Jul 1 11:14:20 2007 From: see_website at mindprod.com.invalid (Roedy Green) Date: Sun, 01 Jul 2007 15:14:20 GMT Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> Message-ID: On 25 Jun 2007 18:46:25 -0700, Paul Rubin wrote, quoted or indirectly quoted someone who said : >You cannot accurately compute >the number of seconds between Nixon's resignation and 1800 UTC today, >unless you take into account the leap seconds have been occurred >between then and now. There are two valid answers to those questions. In a court of law, say did some document arrive before deadline, you must use civil time. Arguing leap seconds would not fly. On the other hand, if you used civil seconds to computer satellite orbits, tiny errors mount up quickly in the calculation. -- Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com From jeba_ride at yahoo.com Tue Jul 24 13:36:21 2007 From: jeba_ride at yahoo.com (Clement) Date: Tue, 24 Jul 2007 17:36:21 -0000 Subject: Any python module for Traversing HTML files In-Reply-To: <1185297135.542235.55290@r34g2000hsd.googlegroups.com> References: <1185297135.542235.55290@r34g2000hsd.googlegroups.com> Message-ID: <1185298581.322910.311720@w3g2000hsg.googlegroups.com> On Jul 24, 10:12 pm, johnny wrote: > Any python module for navigating and selecting, parsing HTML files? try beautyfulshop From restycena at gmail.com Fri Jul 13 08:57:38 2007 From: restycena at gmail.com (kublai) Date: Fri, 13 Jul 2007 12:57:38 -0000 Subject: web page text extractor In-Reply-To: <1184319891.778537.71000@m3g2000hsh.googlegroups.com> References: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> <1184319891.778537.71000@m3g2000hsh.googlegroups.com> Message-ID: <1184331458.125253.161510@j4g2000prf.googlegroups.com> On Jul 13, 5:44 pm, Paul McGuire wrote: > On Jul 12, 4:42 am, kublai wrote: > > > Hello, > > > For a project, I need to develop a corpus of online news stories. I'm > > looking for an application that, given the url of a web page, "copies" > > the rendered text of the web page (not the source HTNL text), opens a > > text editor (Notepad), and displays the copied text for the user to > > examine and save into a text file. Graphics and sidebars to be > > ignored. The examples I have come across are much too complex for me > > to customize for this simple job. Can anyone lead me to the right > > direction? > > > Thanks, > > gk > > One of the examples provided with pyparsing is an HTML stripper - view > it online athttp://pyparsing.wikispaces.com/space/showimage/htmlStripper.py. > > -- Paul Stripping tags is indeed one strategy that came to mind. I'm wondering how much information (for example, paragraphing) would be lost, and if what would be lost would be acceptable (to the project). I looked at pyparsing and I see that it's got a lot of text processing capabilities that I can use along the way. I sure will try it. Thanks for the post. Best, gk From http Thu Jul 12 03:37:37 2007 From: http (Paul Rubin) Date: 12 Jul 2007 00:37:37 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <1i13w96.kyyobph71qxrN%aleax@mac.com> Message-ID: <7xwsx63we6.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > If what you wonder about, and the theory mentioned by Clemmer and > detailed by the AQF, are both true, then this may help explain why some > programmers are fiercely innovative why other, equally intelligent ones, > prefer to stick with some plodding, innovation-killing process that only > works well for repetitive tasks: the latter group may be the ones who > "dread errors", and therefore miss the "making mistakes, experiencing > failures, and learning from them" that is "how we improve". The idea of designing languages with more and more support for ensuring program correctness is to put the established, repetitive processes into the computer where it belongs, freeing the programmer to be innovative while still providing high assurance of that the program will be right the first time. And some of the most innovative work in software is going into this area today. Also, taking a learn-from-mistakes approach is fine and dandy if the consequences of the mistakes stay contained to those who make them. It's completely different if the consequences are imposed on other people who weren't part of the process. Vast amounts of software today (and I mean the stuff that clpy denizens write for random web servers or desktop apps, not just scary stuff like nuclear reactor code) has the potential to screw people who had nothing to do with the development process. It's unreassuring to hear the the developers say "oh cool, we learned from the mistake" when that happens. So, it's irresponsible to deliberately choose development processes that externalize risks onto outsiders that way. From sjmachin at lexicon.net Mon Jul 2 19:12:18 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 02 Jul 2007 16:12:18 -0700 Subject: How to FTP a ASCII file In-Reply-To: <1183417366.036607.233910@n60g2000hse.googlegroups.com> References: <1183417366.036607.233910@n60g2000hse.googlegroups.com> Message-ID: <1183417938.257886.238320@d30g2000prg.googlegroups.com> On Jul 3, 9:02 am, "tedpot... at gmail.com" wrote: > Hi, > > My program has the following code to transfer a binary file > > f = open(pathanme+filename,'rb') > print "start transfer" > self.fthHandle.storbinary('STOR '+filename, f) > > How can I do an ASCII file transfer?????? > -Ted I'm really curious as to how you could find out how to upload a file in binary mode, but not in ASCII mode. According to The Fantastic Manual: """ storbinary( command, file[, blocksize]) Store a file in binary transfer mode. command should be an appropriate "STOR" command: "STOR filename". file is an open file object which is read until EOF using its read() method in blocks of size blocksize to provide the data to be stored. The blocksize argument defaults to 8192. Changed in version 2.1: default for blocksize added. storlines( command, file) Store a file in ASCII transfer mode. command should be an appropriate "STOR" command (see storbinary()). Lines are read until EOF from the open file object file using its readline() method to provide the data to be stored. """ From doug at alum.mit.edu Mon Jul 9 16:16:02 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Mon, 09 Jul 2007 16:16:02 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <9uRhi.17027$xk5.14289@edtnps82> Message-ID: Steve Holden writes: >> I'm relying on a feature that has worked fine since the early '90s, >> and if it is ever changed in the future, I'm sure that plenty of other >> language changes will come along with it that will make adapting code >> that relies on this feature to be the least of my porting worries. > Damn, it seems to be broken on my Jython/IronPython installations, > maybe I should complain. Oh no, I can't, because it *isn't* *part* > *of* *the* *language*. ... As I have mentioned *many* times, I'm coding in CPython 2.5, and I typically make extensive use of Unix-specific calls. Consequently, I have absolutely no interest in making my code compatible with Jython or IronPython, since Jython is stuck at 2.2, IronPython at 2.4, and neither provide full support for the Python Standard Library or access to Unix-specific functionality. I might at some point want to write some Jython code to make use of Java libraries, but when I code in Jython, I will have absolutely no interest in trying to make that code compatible with CPython, since that cannot be if my Jython code calls libraries that are not available to CPython. >>> Exactly like you'd be doing if you rely on the value of >>> uninitialized variables in C. >> Exactly like I'd be doing if I made Unix system calls in my C code. >> After all, system calls are implementation dependent, aren't they? >> That doesn't mean that I don't rely on them every day. > That depends on whether you program to a specific standard or not. What standard would that be? Posix is too restrictive. BSD/OSX/Linux/Solaris are all different. I make my program work on the platform I'm writing it for (keeping in mind what platforms I might want to port to in the future, in order to avoid obvious portability pitfalls), and then if the program needs to be ported eventually to another platforms, I figure out how to do that when the time comes. >>> Of course not. Because they *do* guarantee and specify that. C >>> doesn't, and neither does Python. >> CPython does by tradition *and* by popular will. > But you make the mistake of assuming that Python is CPython, which it isn't. I do not make that mistake. I refer to CPython as "Python" as does 99% of the Python community. When I talk about Jython, I call in "Jython" and when I talk about "IronPython" I refer to it as "IronPython". None of this implies that I don't understand that CPython has features in it that a more strict interpretation of the word "Python" doesn't necessarily have, just as when I call a tomato a "vegetable" that doesn't mean that I don't understand that it is really a fruit. >> Also the language reference manual specifically indicates that >> CPython uses a refcounter and documents that it collects objects as >> soon as they become unreachable (with the appropriate caveats about >> circular references, tracing, debugging, and stored tracebacks). > Indeed, but that *is* implementation dependent. As long as you stick > to CPython you'll be fine. That's allowed. Just be careful about the > discussions you get into :-) I've stated over and over again that all I typically care about is CPython, and what I'm criticized for is for my choice to program for CPython, rather than for a more generalized least-common-denominator "Python". When I program for C++, I also program for the compilers and OS'es that I will be using, as trying to write C++ code that will compile under all C++ compilers and OS'es is an utterly losing proposition. |>oug From http Thu Jul 26 16:28:26 2007 From: http (Paul Rubin) Date: 26 Jul 2007 13:28:26 -0700 Subject: question about math module notation References: Message-ID: <7xd4ye7vv9.fsf@ruckus.brouhaha.com> brad writes: > 18,446,744,073,709,551,616 > > I'm lazy... I don't want to convert it manually :) print 2**64 From fattie at tpu.ru Fri Jul 27 23:38:07 2007 From: fattie at tpu.ru (Valentina Vaneeva) Date: Sat, 28 Jul 2007 10:38:07 +0700 Subject: Imported globals? In-Reply-To: <1185593135.322082.215150@m37g2000prh.googlegroups.com> References: <1185562865.896992.112860@w3g2000hsg.googlegroups.com> <1185593135.322082.215150@m37g2000prh.googlegroups.com> Message-ID: <8de0d997741c49ac7df4a64816ebc018@tpu.ru> Thank you all, guys. I think, now I understand import behavior more :) Cheers, Valia From skywind3000 at gmail.com Mon Jul 23 22:01:40 2007 From: skywind3000 at gmail.com (skywind3000 at gmail.com) Date: Mon, 23 Jul 2007 19:01:40 -0700 Subject: [XBOX] Python XBOX360 Migration Question Message-ID: <1185242500.786659.283660@m37g2000prh.googlegroups.com> Hello ALL, I have just migrated python-core to xbox360. I wonder if someone else has already done it yet ? The ctypes-module-migration puzzle me because I seldom use powerpc assembly. Can someone give me a hint ?? From siona at chiark.greenend.org.uk Mon Jul 2 13:04:42 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 02 Jul 2007 18:04:42 +0100 (BST) Subject: howto resend args and kwargs to other func? References: <1183279997.244378.105810@n60g2000hse.googlegroups.com> <1183282733.179683.174350@c77g2000hse.googlegroups.com> <5er6doF31bulkU1@mid.individual.net> Message-ID: Frank Swarbrick wrote: >dmitrey wrote: >> Thanks all, I have solved the problem. >Why do people do this without posting what the actual solution is!!!! Hey, if we're expected to magically deduce what the problem is without being told an error messages, surely we can magically deduce the discovered solution too? -- \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 kw at codebykevin.com Tue Jul 24 10:28:16 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 24 Jul 2007 10:28:16 -0400 Subject: Tix not properly installed on OS X? In-Reply-To: References: <48B39FEC-D3B9-4FAF-AD45-0DD744D8D289@bryant.edu> Message-ID: <46A60C80.60502@codebykevin.com> Jay Loden wrote: > Brian Blais wrote: >> Hello, >> >> I am running OS X 10.4, on an Intel Mac, Python 2.5 not installed by >> source (I used the binary install from the website). When I do the >> following, I get an error: >> >> 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 Tix >> >>> root=Tix.Tk() >> Traceback (most recent call last): >> File "", line 1, in >> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >> python2.5/lib-tk/Tix.py", line 210, in __init__ >> self.tk.eval('package require Tix') >> _tkinter.TclError: can't find package Tix >> > > I can confirm the same behavior and Google results are not promising: > > http://www.thescripts.com/forum/thread653175.html > http://aspn.activestate.com/ASPN/Mail/Message/ActivePython/3525325 > > I tried installing Tix from the binary TclAqua package, and when I run root=Tix.Tk() I still get the same error (though, interestingly, a Tk window does open). Looks like your best bet right now would be to install Tix via fink if that's an option. > > -Jay You need an up-to-date installation of the base Tix package on your system, in the same path as your Tcl/Tk libraries. I downloaded and built the most recent version of Tix from http://tix.sf.net (dated November 2006) and the Python samples run fine. I think the problem is that Tix is generally considered obsolete, or at least very outdated, by Tcl developers, so many distributions do not include it. It is not shipped with ActiveState on the Mac, nor does Apple include Tix in the Tcl/Tk libraries bundled with OS X. From my perspective there are far better, more modern alternatives, such as BWidgets, TkTreeCtrl, Tablelist, and Tile (all of which have Python wrappers) to enhance the core Tk widgets. Tix appears to be more widely used by Python/Tkinter developers than Tcl/Tk developers. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bignose+hates-spam at benfinney.id.au Fri Jul 20 19:12:13 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 21 Jul 2007 09:12:13 +1000 Subject: code packaging References: <7xfy3jpem8.fsf_-_@ruckus.brouhaha.com> Message-ID: <877ioumzzm.fsf@benfinney.id.au> Paul Rubin writes: > Is this appropriate? Inappropriate? Do your projects start using > serious packaging and distribution tools very early in development, > before the code is anywhere near usable? Should they? Yes. Test-driven development has taught me that putting off important parts of the development process until the end is rarely a good idea. So, I try to make a point of writing the first features inside a complete unit test environment, and inside a complete distribution/build environment. The tests are run continuously while developing the code, and the distribution/build process is tested manually. I'm looking into the "build-bot" approach used to ensure that the build process is also run automatically and continually during development, just like the unit tests ; but so far I'm running the build manually. -- \ "Read not to contradict and confute, nor to believe and take | `\ for granted ... but to weigh and consider." -- Francis Bacon | _o__) | Ben Finney From roger.dahlstrom at gmail.com Wed Jul 18 15:43:48 2007 From: roger.dahlstrom at gmail.com (rdahlstrom) Date: Wed, 18 Jul 2007 19:43:48 -0000 Subject: Tibco Rendezvous In-Reply-To: References: Message-ID: <1184787828.752523.37550@j4g2000prf.googlegroups.com> Sent you an email - have you found anything else on this? I'm not all that familiar with ctypes, and am having a little trouble getting started with this. Anything I could use just to get started would be fantastic - I can go from there. Thanks! On Jul 13, 1:43 pm, "Kip Lehman" wrote: > Circa summer 2003, at a company I previously worked at, a co-worker and > I had an occasion to see if we could get Python and TIBCO Rendezvous > working together. > > The SWIG-based tibrv mechanism was insufficient, buggy and was problematic > in terms of keeping up with Python releases. > > We resorted to using ctypes with the relevant TIBCO header files > and confabulating our own package to work with TIBCO Rendezvous messages > (both publishing and subscribing). > We didn't concern ourselves with certified messages. > > Feel free to contact me directly if you want me to see if I can > unearth any further info. > > -- > > -- > Kip Lehman > kipster t earthlink net > > ...still waiting for PanAm, Amtrack and the USPS to deliver my .sig From steve at REMOVE.THIS.cybersource.com.au Wed Jul 25 22:08:40 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 26 Jul 2007 12:08:40 +1000 Subject: Keyword argument 'from'; invalid syntax References: Message-ID: On Thu, 26 Jul 2007 03:33:20 +0200, Kai Kuehne wrote: > I have tried to prepare a dict and then passing it to the > method afterwards: >>>> d = {'person': 'user', 'from': vorgestern} >>>> magnolia.bookmarks_find(d) > : bookmarks_find() takes exactly 1 > argument (2 given) > > I'm out of ideas so help is greatly appreciated! Try this: magnolia.bookmarks_find(**d) although I suspect that will probably raise an exception as well. Judging by the error message, it looks like bookmarks_find() takes only a single argument, which I imagine would be the "self" instance automatically provided at runtime. -- Steven. From martin at v.loewis.de Tue Jul 3 17:33:37 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 03 Jul 2007 23:33:37 +0200 Subject: object references/memory access In-Reply-To: <1183488824.131448.62720@x35g2000prf.googlegroups.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1183407411.397142.304790@e16g2000pri.googlegroups.com> <1183417108.245203.158830@x35g2000prf.googlegroups.com> <4689e535$0$23896$9b622d9e@news.freenet.de> <1183488824.131448.62720@x35g2000prf.googlegroups.com> Message-ID: <468ac0b1$0$9090$9b622d9e@news.freenet.de> > If the problem does not require two way communication, which is > typical of a producer-consumer, it is a lot faster to allow P to fully > run before C is started. Why do you say it's *a lot* faster. I find that it is a little faster. The only additional overhead from switching forth and back between consumer and producer is the overhead for context switching, which is typically negligible, compared to everything else that is going on. Regards, Martin From bdesth.quelquechose at free.quelquepart.fr Sun Jul 15 18:26:54 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 16 Jul 2007 00:26:54 +0200 Subject: Technology solutions for Ruby? In-Reply-To: <1184606739.054580.197740@g37g2000prf.googlegroups.com> References: <469B059C.2050802@cesmail.net> <1184606739.054580.197740@g37g2000prf.googlegroups.com> Message-ID: <469be0e5$0$9556$426a74cc@news.free.fr> vasudevram a ?crit : (snip) >>To me this means Ruby, Python, or, as mentioned above, Perl. If anyone > > can tell me of a way to meet the above requirements in either Python > or > Perl, I'm all ears (I just prefer Ruby). >>1. GUI - Native Look and Feel. According to wxRuby the bindings aren't > mature enough for production use. (snip) > wxPython has this (Native Look and Feel), I think It does - just like wxRuby, since both are language-specific bindings to the C++ wxWidgets toolkit. And FWIW, wxPython has been used on production for many years, so I think it qualifies as "production ready" !-) (snip) >>2. Databases - contemplating using ActiveRecord, but I would like to use > ODBC to support multiple types of DB's in a uniform way (if you know > of > alternatives to ODBC or ActiveRecord, please let me know). In Python, you may want to have a look at SQLAlchemy, which offers lots of things from the "db abstraction layer" to the full-blown (and possibily somewhat ActiveRecord-like, cf the Elixir project) ORM. (snip) >>3. Binary - Are there any utilities for compiling Ruby into a binary > executable? The issue is twofold, speed, and not handing the > customer > the source :) IIRC, Ruby is actually still an interpreted language. Python is much like Java wrt/ this issue : it's byte-compiled (the difference being that this step is automagically managed by the VM). IOW, you won't gain any speed from the existing packaging systems(but then, if your project is mostly a GUI/DB tunnel, the two most critical parts are already somewhat optimized). And the level of protection gained from these packaging systems is very debatable at best (which, FWIW, is also the case with Java). (snip) > I first learned Python, have been using it for some time for various > projects, and then learned Ruby, and have done some projects with Ruby > too. > > I've been reading both the Ruby Cookbook and the Python Cookbook > rather thoroughly in the last few weeks (and trying out and modifying > many of the recipes), and what I've observed is that the two languages > are roughly similar in features. Yes. (snip) > For more advanced language features related to object-orientation, > metaclasses / metaprogramming, both have some support, s/some/great/g Both Ruby and Python are known for this. > but you might > or might not be able to do in one, what you can do in the other. I'd say that - wrt/ "advanced" programming tricks - *most* of what you can do with one can be done with the other - but usually in a *very* different way. While Ruby and Python have similar features and may look very similar at first sight, their respective object models are totally different. Basically, it's a matter of - which language *you* prefer - which one has the best libs for your app It seems that, in your case, you prefer Ruby but Python may *or not* have the best/more mature toolkit. So the best thing to do would be to first try to write a quick 'proof of concept' program in the language you prefer. Then, if you're still in doubt, write the same program in Python. My 2 cents (and friendly salutations to the Ruby community). From http Tue Jul 24 01:48:10 2007 From: http (Paul Rubin) Date: 23 Jul 2007 22:48:10 -0700 Subject: Where do they tech Python officialy ? References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> Message-ID: <7xveca4ajp.fsf@ruckus.brouhaha.com> NicolasG writes: > Does some one have any suggestions on which University to attend ? > Alternatives solutions are welcome.. If you have a good programming background in other languages, you should easily be able to pick up Python by reading the manual. If you don't have a programming background and want to acquire one through a university program, then it doesn't matter that much what language the university uses, since if it's not Python, after completing the program you'll still be able to easily pick up Python by reading the manual. If you're having trouble with Python because you're new at programming, I can sympathize--I don't think it's the most beginner-friendly of languages despite the efforts in that direction by the designers. But once you understand the principles of programming, Python is easy. I think Python is not used in university programs very much. Look for one that uses SICP (Scheme) or CTM (Mozart/Oz) or a functional language like Haskell, in preference to the ones that use Java (the Cobol of the 1990's). With some reasonable experience in Scheme or Mozart or Haskell, plus a Python manual, you'll be well on your way. The SICP textbook is here: http://mitpress.mit.edu/sicp/ Maybe it's gotten a little bit old fashioned by now, but it's still good reading. From crobc at BOGUS.sbcglobal.net Tue Jul 10 23:00:34 2007 From: crobc at BOGUS.sbcglobal.net (CC) Date: Tue, 10 Jul 2007 20:00:34 -0700 Subject: Should I use Python for these programs? In-Reply-To: <1184041965.807750.6140@c77g2000hse.googlegroups.com> References: <1184041965.807750.6140@c77g2000hse.googlegroups.com> Message-ID: Michele Simionato wrote: > On Jul 10, 5:09 am, CC wrote: >>2. Develop a simple vector drawing program that will allow one to >>freehand draw a sketch composed of a few lines, or perhaps render text >>in a vector form. Then sample the lines with a certain (user >>configurable) spacing, and use the mouse to move the sample points along >>the lines to tweak the sample locations if desired. Then output a file >>of X,Y coordinates for the samples. > > You may look at dia for that. > > Michele Simionato Thanks for the input. Yes, I will have a look. Makes sense to check out if any drawing progs can do what I want off the shelf. But it might be fun to write one anyway! -- _____________________ Christopher R. Carlen crobc at bogus-remove-me.sbcglobal.net SuSE 9.1 Linux 2.6.5 From wojciech_mula at poczta.null.onet.pl.invalid Thu Jul 19 12:16:23 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?iso-8859-2?Q?Mu=B3a?=) Date: Thu, 19 Jul 2007 16:16:23 +0000 (UTC) Subject: Itertools question: how to call a function n times? References: Message-ID: Matthew Wilson wrote: > I want to write a function that each time it gets called, it returns a > random choice of 1 to 5 words from a list of words. > > I can write this easily using for loops and random.choice(wordlist) and > random.randint(1, 5). > > But I want to know how to do this using itertools, since I don't like > manually doing stuff like: > > phrase = list() > for i in random.randint(1, 5): > > phrase.append(random.choice(wordlist)) Use list comprehension: phrase = [random.choice(wordlist) for i in xrange(random.randint(1, 5))] w. From jjl at pobox.com Sat Jul 14 09:33:58 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 14 Jul 2007 13:33:58 GMT Subject: Client-side cookies on Python in Mac OSX References: <1184292844.383002.128420@n2g2000hse.googlegroups.com> <1184293712.607084.27310@g37g2000prf.googlegroups.com> <1184295935.344343.85290@r34g2000hsd.googlegroups.com> Message-ID: <87hco7yurd.fsf@pobox.com> Adrian Petrescu writes: > Oh, you're right! Silly me, I had always thought it was standard. > Thanks for pointing this out! I went and downloaded ClientCookie and > it works great on OS X. And since it is BSD-licensed, I can use it in > my app without any fear. Perfect. > > Thank you, Graham! The relationship is that cookielib is derived from ClientCookie: essentially the same code, cleaned up to take advantage of newer Python features, renamed to 'cookielib' and added to the stdlib. The other difference is in thread synchronisation: ClientCookie had some broken thread synchronisation at one point, which was subsequently removed (which doesn't imply ClientCookie is not useful in threaded code). Though an unfortunate series of events the released cookielib ended up with that broken thread synchronisation code. It seems at least some of those thread synchronisation bugs in cookielib are fixed in the lastest version of Python. http://python.org/sf/1484758 http://python.org/sf/1587139 John From maxkhesin at gmail.com Sun Jul 15 15:49:09 2007 From: maxkhesin at gmail.com (xamdam) Date: Sun, 15 Jul 2007 19:49:09 -0000 Subject: zipfile 2GB problems? In-Reply-To: References: <1184474112.081258.111490@n60g2000hse.googlegroups.com> <1184525970.082235.238200@q75g2000hsh.googlegroups.com> Message-ID: <1184528949.751377.5620@g4g2000hsf.googlegroups.com> > > > Additional info: my file is from a data provider, do not know what > > they used to compress it. Previous files worked ok, this one is the > > 1st over 2GB. Winzip has no problem with it. > > It could be you are using a Python with an in-built limit of 2GB on file > size. What happens if you open the file, seek past the 2GB point and > then try and read data? > Steve, I used is_zipfile function, which from does exactly that from a quick read - goes to the end, reads expected string. It worked fine. Tried regular Windows 2.4.4 and 2.5.1, same result. From crobc at BOGUS.sbcglobal.net Mon Jul 9 23:09:32 2007 From: crobc at BOGUS.sbcglobal.net (CC) Date: Mon, 09 Jul 2007 20:09:32 -0700 Subject: Should I use Python for these programs? Message-ID: Hi: I have considerable C and assembly language experience. However, these are mostly on embedded microcontrollers since I moved away from PC programming all the way back in 1988 :-O I wish to accomplish a few PC programming tasks, and am considering to learn Python: 1. Develop a simple GUI program to run on Linux and Windows which can send parameters and small blocks of data to an embedded microcontroller device via RS-232 or USB. Also display simple data (probably single numbers) sent from the device. Note, if it is USB, then the client will be implemented by me using FTDI chips that appear to the PC as a serial port. 2. Develop a simple vector drawing program that will allow one to freehand draw a sketch composed of a few lines, or perhaps render text in a vector form. Then sample the lines with a certain (user configurable) spacing, and use the mouse to move the sample points along the lines to tweak the sample locations if desired. Then output a file of X,Y coordinates for the samples. What is this crazy thing for? It's to develop simple lasershow vector frames. I am also designing a DSP-based lasershow output device, so the same capabilities of delivering a data payload over serial/USB to a target device will be needed here as well. I would prefer to be able to write a program that is cross-platform between Linux and Windows. I realize this might be especially problematic with the serial comms. I am also confused by the plethora of Python GUI extensions, though Tkinter seems like a likely candidate. I am uncertain if I will have difficulty learning how to use this if I don't know Tcl/Tk. Do you think Python is the right language for these projects? Any input will be appreciated. -- _____________________ Christopher R. Carlen crobc at bogus-remove-me.sbcglobal.net SuSE 9.1 Linux 2.6.5 From rrenaud at gmail.com Wed Jul 11 12:40:43 2007 From: rrenaud at gmail.com (rrenaud at gmail.com) Date: Wed, 11 Jul 2007 16:40:43 -0000 Subject: Passing a CookieJar instead of a cookieproc to urllib2.build_opener In-Reply-To: <873azvg8il.fsf@pobox.com> References: <1184028331.849197.263130@g4g2000hsf.googlegroups.com> <873azvg8il.fsf@pobox.com> Message-ID: <1184172043.009591.168890@w3g2000hsg.googlegroups.com> On Jul 10, 11:10 pm, j... at pobox.com (John J. Lee) wrote: > "rren... at gmail.com" writes: > > urllib2.build_opener happily accepts and ignores a FileCookieJar. I > > had a bug in my code which looked like > > > urllib2.build_opener(func_returning_cookie_jar()) > > > which should have been > > > urllib2.build_opener(HTTPCookieProcessor(func_returning_cookie_jar()) > > > The problem is that the code ran happily without actually sending the > > cookie, the CookieJar was just ignored. I think that build_opener > > should throw an exception when add_handler doesn't actually add. > > > Is this worth filing a bug for, or is it acceptable behavior? > > IMO, it's worth filing iff: > > a) you think it's worthwhile (this one sounds worthwhile to me) > > b) you write a patch and are prepared to patiently keep at it until it > gets applied > > Make sure your patch follows PEP 8. Make sure the patch includes test > and documentation updates / additions (you don't need to write docs in > LaTeX format -- other people will do the conversion to LaTeX for you > if you like). If there are no doc changes required, state that > explicitly in the patch tracker. If your patch gets ignored, review > five other patches, and post to python-dev stating you have done so > and requesting that your patch is reviewed (there's a shortage of > patch reviewers). > > John The patch is on the tracker here. http://sourceforge.net/tracker/index.php?func=detail&aid=1750931&group_id=5470&atid=305470 Are the docs themselves in subversion? I suppose I should also update the doc at http://docs.python.org/lib/module-urllib2.html From steve at REMOVE.THIS.cybersource.com.au Wed Jul 11 22:45:48 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 12 Jul 2007 12:45:48 +1000 Subject: bool behavior in Python 3000? References: Message-ID: On Wed, 11 Jul 2007 07:14:53 -0600, Steven Bethard wrote: > Steven D'Aprano wrote: >> On Tue, 10 Jul 2007 17:47:47 -0600, Steven Bethard wrote: >>> But I think all you're really saying is that newbies don't expect things >>> like +, -, *, etc. to work with bools at all. Which I agree is probably >>> true. >> >> No, what I am saying is that True and False being integers under the hood >> is a surprising implementation detail. It has no _inherent_ benefit: it >> is merely a practical way to bring bools into the language while >> remaining backward compatible. For Python 2.x, that was the least bad >> solution to the issue "oops, we should have included a bool type". >> >> Python 3 is allowed to break backwards compatibility, and there is no >> reason I can see to keep the current hack. > > Remember that while Python 3 is allowed to break backwards > compatibility, it's only supposed to do it when there are concrete > benefits. Clearly there are existing use cases for treating bools like > ints, e.g. from Alexander Schmolck's email: > > (x < b) * f(x) > -1 ** (i == j) You have cause and effect confused here. Expressions like (i == j) used to return 0 and 1, and it was to avoid breaking hacks like the above that bools were implemented as a subclass of int, not because being able to write the above was a specific feature requested. In the hypothetical bright new world of Python with bools that are actually bools, the above are good cases for explicit being better than implicit: int(x < b) * f(x) -1 ** int(i == j) It makes more sense to explicitly cast bools to ints when you want to do integer arithmetic on them, rather than explicitly casting bools to bools to do boolean arithmetic! I feel strongly enough about this that I believe that being able to write (x < b) * f(x) is a DISADVANTAGE -- it gives me a real WTF moment to look at the code. In some hypothetical world where backwards compatibility was not an issue, where bools had already existed, if somebody had specifically asked for bools to become ints so they could write (x < b) * f(x), I have every confidence that their request would have been denied, and they would have been told to explicitly cast the bool to an int. As they should. -- Steven. From dickinsm at gmail.com Sat Jul 14 02:07:17 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: Sat, 14 Jul 2007 06:07:17 -0000 Subject: Fast powerset function In-Reply-To: References: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> Message-ID: <1184393237.783461.210680@o61g2000hsh.googlegroups.com> If you don't care about the order of the results, you can use a Gray code (http://en.wikipedia.org/wiki/Gray_code): this has the advantage of only adding or removing a single element to get from one subset to the next. def powerset(s): d = dict(zip( (1<>> list(powerset('abc')) [set([]), set(['a']), set(['a', 'b']), set(['b']), set(['c', 'b']), set(['a', 'c', 'b']), set(['a', 'c']), set(['c'])] If you're using the subsets as they appear and don't need to store them all at once, then it's significantly faster (on my machine) if you replace the line subset = subset ^ d[i & -i] with an in-place update: subset ^= d[i & -i]. Mark From vedrandekovic at v-programs.com Sat Jul 21 15:25:05 2007 From: vedrandekovic at v-programs.com (...:::JA:::...) Date: Sat, 21 Jul 2007 21:25:05 +0200 Subject: problem with exec Message-ID: Hello, After my program read and translate this code: koristi os,sys; ispisi 'bok kaj ima'; into the: import os,sys; print 'bok kaj ima'; and when it run this code with "exec", I always get error like this, but I still dont't know what is a problem: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\VL\__init__.py", line 188, in kompajlati kompajlati_proces() File "C:\Python24\Lib\site-packages\VL\__init__.py", line 183, in kompajlati_proces h2=Konzola() File "C:\Python24\Lib\site-packages\VL\__init__.py", line 158, in __init__ k=kod(ZTextCtrl.GetLabel()) File "C:\Python24\Lib\site-packages\VL\__init__.py", line 83, in kod exec(str_ngh) File "", line 1 import os ,sys ; ^ SyntaxError: invalid syntax PS: How can I change when user write script with my program to he don't need aspirate the lines of his source code e.g. import os,sys n=90 if n==90:print "OK" else:print "No" Regards, Vedran __________________________________________________________________ Vedran veki ICQ#: 264412055 Current ICQ status: + More ways to contact me Get ICQ! __________________________________________________________________ From greg at cosc.canterbury.ac.nz Tue Jul 10 04:37:53 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 10 Jul 2007 20:37:53 +1200 Subject: Building a Python app with Mozilla In-Reply-To: <1183647423.458469.166460@m36g2000hse.googlegroups.com> References: <1183524527.709730.190290@q75g2000hsh.googlegroups.com> <5f30vsF3aicltU1@mid.individual.net> <1183647423.458469.166460@m36g2000hse.googlegroups.com> Message-ID: <5fgv1kF3dcrvkU1@mid.individual.net> sjdevnull at yahoo.com wrote: > Last I looked (3.1-ish), Qt didn't use the Aqua widgets but rather > tried to write their own widgets that looked (kinda) like the MacOS > widgets. That might be so, but even if it had used real Aqua widgets, the same problem would have occurred. My point was that using native widgets is not in itself enough to ensure a native experience. There are conventions about *how* the widgets are used, and other things about the behaviour that don't relate to widgets at all. Native widgets are certainly a better thing to start from, though. -- Greg From kbk at shore.net Fri Jul 27 00:09:14 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 27 Jul 2007 00:09:14 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200707270409.l6R49EEW007231@hampton.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 399 open ( +5) / 3836 closed ( +9) / 4235 total (+14) Bugs : 1056 open (+10) / 6776 closed ( +3) / 7832 total (+13) RFE : 263 open ( +1) / 294 closed ( +1) / 557 total ( +2) New / Reopened Patches ______________________ utilize 2.5 try/except/finally in contextlib (2007-07-19) http://python.org/sf/1757118 opened by Philip Jenvey Fix ptcp154 encoding cyrillic_asian alias (2007-07-19) http://python.org/sf/1757126 opened by Philip Jenvey Add support for seeking/writing beyond EOF to io.BytesIO (2007-07-20) CLOSED http://python.org/sf/1757683 opened by Alexandre Vassalotti struni: make test_ucn pass (2007-07-20) CLOSED http://python.org/sf/1757758 opened by Alexandre Vassalotti struni: fix str/bytes errors for test_oldmailbox (2007-07-20) CLOSED http://python.org/sf/1757774 opened by Alexandre Vassalotti setuptools support for bazaar vcs (2007-07-20) CLOSED http://python.org/sf/1757782 opened by Barry A. Warsaw struni: make test_mailbox and test_old_mailbox pass (2007-07-20) CLOSED http://python.org/sf/1757839 opened by Alexandre Vassalotti struni: Fix test_macostools (2007-07-22) CLOSED http://python.org/sf/1758570 opened by Jeffrey Yasskin pyexpat unit tests - str/uni branch (2007-07-23) CLOSED http://python.org/sf/1759016 opened by Joe Gregorio clean up Solaris port and allow C99 extension modules (2007-07-23) http://python.org/sf/1759169 opened by Zooko O'Whielacronx struni pulldom: Don't use 'types' to check strings (2007-07-24) http://python.org/sf/1759922 opened by Alexandre Vassalotti Cross Compiling Python (2007-07-25) http://python.org/sf/1760089 opened by Yegnesh ZipFile.write fails with bad modification time (2007-07-25) http://python.org/sf/1760357 opened by Grzegorz Adam Hankiewicz struni: Fix test_aepack by converting 4cc's to bytes (2007-07-26) http://python.org/sf/1761465 opened by Jeffrey Yasskin Patches Closed ______________ Show Location of Unicode Escape Errors (2007-07-18) http://python.org/sf/1755885 closed by gvanrossum Add support for seeking/writing beyond EOF to io.BytesIO (2007-07-20) http://python.org/sf/1757683 closed by gvanrossum struni: make test_ucn pass (2007-07-20) http://python.org/sf/1757758 closed by gvanrossum struni: fix str/bytes errors for test_oldmailbox (2007-07-20) http://python.org/sf/1757774 closed by avassalotti setuptools support for bazaar vcs (2007-07-20) http://python.org/sf/1757782 closed by pje struni: make test_mailbox and test_old_mailbox pass (2007-07-20) http://python.org/sf/1757839 closed by gvanrossum PEP 3123 implementation (2007-05-13) http://python.org/sf/1718153 closed by loewis struni: Fix test_macostools (2007-07-22) http://python.org/sf/1758570 closed by gvanrossum pyexpat unit tests - str/uni branch (2007-07-23) http://python.org/sf/1759016 closed by gvanrossum New / Reopened Bugs ___________________ Python 2.5.1 fails to build on AIX (2007-07-18) http://python.org/sf/1756343 opened by Tom Epperly reference count discrepancy, PyErr_Print vs. PyErr_Clear (2007-07-18) http://python.org/sf/1756389 opened by Jon Klein IDLE + BeautifulSoup = Error (2007-07-19) http://python.org/sf/1757057 opened by Tal Einat Pickle fails on BeautifulSoup's navigableString instances (2007-07-19) http://python.org/sf/1757062 opened by Tal Einat Zipfile robustness (2007-07-19) http://python.org/sf/1757072 opened by Chris Mellon Crash in PyObject_Malloc (2007-07-21) http://python.org/sf/1758146 opened by Tim Bishop Documentation of descriptors needs more detail (2007-07-22) http://python.org/sf/1758696 opened by L. Peter Deutsch unicode(None,charset) raise TypeError (2007-07-23) http://python.org/sf/1758804 opened by Guillaume subprocess.call fails with unicode strings in command line (2007-07-24) http://python.org/sf/1759845 opened by Matt poll() on cygwin sometimes fails [PATCH] (2007-07-24) http://python.org/sf/1759997 opened by Brian Warner No docs for list comparison (2007-07-25) http://python.org/sf/1760423 opened by Kent Johnson logging.FileHandler may throw exception in flush() (2007-07-25) http://python.org/sf/1760556 opened by J Livingston pickle - cannot unpickle circular deps with custom __hash__ (2007-07-26) http://python.org/sf/1761028 opened by Martin S??kraut Bugs Closed ___________ struni: help() is broken (2007-07-11) http://python.org/sf/1751932 closed by kbk Docstring for codecs.lookup is incorrect (2007-07-15) http://python.org/sf/1754453 closed by doerwalter New / Reopened RFE __________________ splice() function for itertools (2007-07-20) CLOSED http://python.org/sf/1757395 opened by Alexander Dutton Allow opening just an editor window (2007-07-21) http://python.org/sf/1757831 opened by Tal Einat RFE Closed __________ splice() function for itertools (2007-07-20) http://python.org/sf/1757395 closed by rhettinger From jae+python at jerhard.org Thu Jul 19 22:58:00 2007 From: jae+python at jerhard.org (Juergen Erhard) Date: Fri, 20 Jul 2007 04:58:00 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7x8x9lwka9.fsf@ruckus.brouhaha.com> References: <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <7x8x9lwka9.fsf@ruckus.brouhaha.com> Message-ID: <20070720025800.GA3519@jerhard.org> On Thu, Jul 12, 2007 at 11:26:22AM -0700, Paul Rubin wrote: > > Guy Steele used to describe functional programming -- the evaluation > of lambda-calculus without side effects -- as "separation of Church > and state", a highly desirable situation ;-). > > (For non-FP nerds, the above is a pun referring to Alonzo Church, who > invented lambda calculus in the 1920's or so). Wow, I didn't realize I was an FP nerd :) On proving programs correct... from my CS study days I distinctly remember thinking "sure, you can prove it correct, but you cannot do actual useful stuff with it". We might have come a long way since then (late 80s :P), but I don't hold out much hope (especially since the halting problem does exist, and forever will). Bye, J From orsenthil at users.sourceforge.net Sun Jul 1 23:04:30 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Mon, 2 Jul 2007 08:34:30 +0530 Subject: urllib2 : https and proxy In-Reply-To: <46842A5F.1080506@aristote.info> References: <1183021663.053143.275090@q69g2000hsb.googlegroups.com> <20070628182216.GA4332@gmail.com> <46842A5F.1080506@aristote.info> Message-ID: <20070702030430.GB3553@gmail.com> * Maric Michaud [2007-06-28 23:38:39]: > Hmmm, i've tried something similar but I get the same result. > > For the code example I gave, I've put correctly the http_proxy and > https_proxy environment variables, the default ProxyHandler get them right > as this is the proxy itself which returns the error. I checked this with > wireshark, the proxy said that there is incompatibilities in some request > methods, like POST, with some protocols, Gopher is the example it gave. > That doesn't make much sense to me as the wget command I tried is intended > to do exactly the same thing (POST over https and retrieve some cookies from > the response), and go through with no problems. > Maric, in the ActiveState urllib2 HOWTO which seems to apply for Python 2.5, I came across a point which mentions urllib2 does not support PROXY for HTTPS. Your case seems the same, I would suggest you to look up the Python Tracker for any already open issues, or if not kindly log one yourself. I shall if I can help further, working on urllib2 is a project am doing as part of Summer of Code 2007. Thanks, -- O.R.Senthil Kumaran http://uthcode.sarovar.org From simoncelen at gmail.com Sun Jul 29 06:46:11 2007 From: simoncelen at gmail.com (simonbun) Date: Sun, 29 Jul 2007 10:46:11 -0000 Subject: Compiling python2.5.1 results in 3.5MB python lib? In-Reply-To: <46AB0739.9040107@v.loewis.de> References: <1185556268.287077.258080@d55g2000hsg.googlegroups.com> <46AB0739.9040107@v.loewis.de> Message-ID: <1185705971.100270.120010@57g2000hsv.googlegroups.com> On Jul 28, 11:07 am, "Martin v. L?wis" wrote: > > I'm compiling 2.5.1 and end up with a 3.5MB libpython2.5.so file. I > > seem to remember it should be somewhere around the 1MB mark. What > > could be causing this? > > Try stripping it. > > Regards, > Martin How would I go about doing this? I'm not sure what to strip nor how to do it. Thanks, Simon From steve at holdenweb.com Tue Jul 24 06:56:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Jul 2007 06:56:22 -0400 Subject: Parsing XML with ElementTree (unicode problem?) In-Reply-To: <5glqfsF3gs3gfU2@mid.uni-berlin.de> References: <1185200976.082516.105420@57g2000hsv.googlegroups.com> <1185256646.060652.199740@d55g2000hsg.googlegroups.com> <5glqfsF3gs3gfU2@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Tue, 24 Jul 2007 05:57:26 +0000, oren.tsur wrote: > >> but the thing is that the parser parses it all right from the web (the >> amazon response) but fails to parse the locally saved file. > > I've just used wget to fetch that URL and `ElementTree` parses that local > file without problems. > > Maybe you should stop searching the explanation within Python or > `ElementTree` and accept having a broken XML file on your disk. :-) > > Have you checked the local XML file with something like `xmllint` or > another XML parser already? > > Ciao, > Marc 'BlackJack' Rintsch You should also realise that your posting compromised the Access ID embedded in the URL. If that was live it might be a good idea to replace 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 http Tue Jul 31 19:36:35 2007 From: http (Paul Rubin) Date: 31 Jul 2007 16:36:35 -0700 Subject: Process Control Help References: <1185808072.695752.20720@z28g2000prd.googlegroups.com> Message-ID: <7xodhskuws.fsf@ruckus.brouhaha.com> Walt Leipold writes: > 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. +1 QOTW From westymatt at gmail.com Thu Jul 26 22:03:11 2007 From: westymatt at gmail.com (westymatt) Date: Thu, 26 Jul 2007 19:03:11 -0700 Subject: instantiate a 'classobj' Message-ID: <1185501791.311662.220980@57g2000hsv.googlegroups.com> I have a class where a parameter to its constructor is a type(param) = 'classobj'. How would I go about instantiating that given it has no constructor. From aleax at mac.com Tue Jul 31 11:37:11 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 31 Jul 2007 08:37:11 -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> Message-ID: <1i23wyk.avc945i4dwsiN%aleax@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. That will take a while, but not as long as getting a college degree (and it will be far cheaper than the degree). Alex From zentara at highstream.net Fri Jul 27 07:26:05 2007 From: zentara at highstream.net (zentara) Date: Fri, 27 Jul 2007 07:26:05 -0400 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: On Thu, 26 Jul 2007 09:38:34 -0700, Paul Boddie wrote: >zentara wrote: >> >> This is where the big boys play, you have to be able to be able to >> scuffle and take punishment if you are wrong or unduly ignorant. >> You also need to squash somehow who attacks you, when you >> know you are right. > >Where is this again? High school? No, it's the prison's exercise yard. (The prison being capitalism :-) ) If you sit on the bleachers and watch (i.e. lurk this newsgroup to learn), there is no problem. But step out onto the field and enter the play, be prepared for some open-hand slapping and verbal abuse, especially if you don't read the Faq, do prior research, or just want a handout. >I can understand people getting >impatient with repeated incoherent one-line messages of the form "can >u give me teh codes thanx", but you'd show off your community a bit >better by entertaining even the most naive questions - people have to >start somewhere, you know. perl beginners maillist is the place to go for that. Excellent answers are given, with a "cherry on top". You can understand that when these gurus get the same question, for the 500th time, they start screaming "search groups.google" or "read the Faq". >In comp.lang.perl.misc? It seems to me that the "big boys" in this >case have an inflated sense of their own bigness. >Paul Maybe, but that karma will eventually play out against them. > >P.S. Although it's nice to point to beginner resources, too, 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. Well, I'm just pointing out that she shouldn't give up on Perl because of this newsgroup. I seldom post here myself, mostly because I know I'm usually outgunned by the regulars. I've always got the impression that this newsgroup was about arguing the fine points of Perl, not explaining the basics to newbies. zentara -- I'm not really a human, but I play one on earth. http://zentara.net/japh.html From siona at chiark.greenend.org.uk Thu Jul 5 08:10:38 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 05 Jul 2007 13:10:38 +0100 (BST) Subject: Reversing a string References: <1i0kjpx.wjw44j15np22dN%aleax@mac.com> <468c151b$0$26790$426a74cc@news.free.fr> Message-ID: Jan Vorwerk wrote: > [ lots of sensible stuff to discover "reversed" ] > >>> print reversed.__doc__ See also: >>> help(reversed) -- \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 bignose+hates-spam at benfinney.id.au Sun Jul 1 20:30:43 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 02 Jul 2007 10:30:43 +1000 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> Message-ID: <87ir93pryk.fsf@benfinney.id.au> Martin Gregorie writes: > I've never seen Julian time used outside the world of IBM > mainframes. I'd be interested to know who else uses it. Systems which need to perform date+time computations into the past. One advantage of Julian time is that it ignores the "1 BC was immediately followed by 1 AD, there is no 0 AD" hiccup, so Julian time allows dates to use simple arithmetic to determine the interval. I know that PostgreSQL at least stores date values in Julian time, for exactly this benefit. -- \ "My roommate got a pet elephant. Then it got lost. It's in the | `\ apartment somewhere." -- Steven Wright | _o__) | Ben Finney From http Tue Jul 10 03:37:36 2007 From: http (Paul Rubin) Date: 10 Jul 2007 00:37:36 -0700 Subject: What is the most efficient way to test for False in a list? References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <7x7ipajvst.fsf@ruckus.brouhaha.com> <5fejp2F3cp3igU1@mid.individual.net> <5feju0F3c7pd1U1@mid.uni-berlin.de> <7xsl7xmxcl.fsf@ruckus.brouhaha.com> Message-ID: <7x8x9oogjj.fsf@ruckus.brouhaha.com> Duncan Booth writes: > > status = not (False in list) > > That is an equality test, not an identity test: > > >>> False in [0] > True Arrggggh! Strongly typed language, my eye ;-) Thanks. From p.lavarre at ieee.org Tue Jul 10 13:53:00 2007 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: Tue, 10 Jul 2007 10:53:00 -0700 Subject: Abort trap - Fatal Python error: GC object already tracked In-Reply-To: <1184087201.821731.45600@x35g2000prf.googlegroups.com> References: <1184087201.821731.45600@x35g2000prf.googlegroups.com> Message-ID: <1184089980.721616.310430@e9g2000prf.googlegroups.com> > Is this interesting Python output? ... > > Fatal Python error: GC object already tracked > Abort trap > > ... tell me I can help by solving it, and > I'll look more closely. Sorry, never mind, not interesting after all. Newbie me did somehow forget the fact that ctypes.memmove doesn't bounds-check, e.g. there is no error raised by overwriting memory not owned, which then naturally degrades the stability of the GC etc. >>> import ctypes >>> >>> bytes = (3 * ctypes.c_ubyte)() >>> bytes[0], bytes[1], bytes[2] (0, 0, 0) >>> CP = ctypes.POINTER >>> ctypes.cast(ctypes.addressof(bytes) + 3, CP(ctypes.c_ubyte)).contents.value 0 >>> >>> result = ctypes.memmove(ctypes.addressof(bytes), '\1\3\5\7', 4) >>> bytes[0], bytes[1], bytes[2] (1, 3, 5) >>> ctypes.cast(ctypes.addressof(bytes) + 3, CP(ctypes.c_ubyte)).contents.value 7 >>> From max at alcyone.com Sat Jul 7 18:21:03 2007 From: max at alcyone.com (Erik Max Francis) Date: Sat, 07 Jul 2007 15:21:03 -0700 Subject: Unicode problem In-Reply-To: References: Message-ID: pabloski at giochinternet.com wrote: > Hi to all, I have a little problem with unicode handling under Python. > > I have this code > > s = u'A unicode string with this damn apostrophe \x2019' > > outf = codecs.open('filename.txt', 'w', 'iso-8859-15') > outf.write(s) > > what I obtain is a UnicodeEncodeError that says me that character \x2019 > maps to undefined. > > But the character \x2019 is the apostrophe and in the unicode table it has > \x0027 as an equivalent, so the codecs should convert \x2019 to \x27 ( as > defined in iso-8859-15 ).... U+2019 is RIGHT SINGLE QUOTATION MARK. The APOSTROPHE (U+0027) is a cross-reference as a similar code point, but they're not the same thing. Your problem is that ISO-8859-15 doesn't have the RIGHT SINGLE QUOTATION MARK, so you'll have to do the translation yourself if you want to turn it into a true APOSTROPHE. -- 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 She glanced at her watch ... It was 9:23. -- James Clavell From steve at holdenweb.com Fri Jul 27 13:00:16 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 27 Jul 2007 13:00:16 -0400 Subject: Factory pattern again In-Reply-To: <11831500.post@talk.nabble.com> References: <11825158.post@talk.nabble.com> <46a9c21f$0$18765$426a74cc@news.free.fr> <11831500.post@talk.nabble.com> Message-ID: Mike Howarth wrote: > Having overcome my first hurdle with the factory pattern, I've now hit > another stumbling block > > At the moment I'm trying to return around 2000 records from a db and load up > the relevant product object, what I've found is this is running extremely > slowly (> 20mins), the db is normalized and indexes exist. > > Can anyone advise on how best I could speed this up? > > def getWebRangeProducts(self): > if self.c.connected: > cu = self.c.cursor #create the cursor > sql = "SELECT type, code FROM products" > cu.execute(sql) > if cu.rowcount > 0: > rows = cu.fetchall() > for row in rows: > self.loadProduct(row[0].strip(),row[1].strip()) > return self.products > > def loadProduct(self,type,product_code): > print type + ":" + product_code > if type == 'I': > try: > product = factory('Item', product_code) > self.products.append(product) > except: > print 'problem occured:' + type + ':' + product_code > elif type == 'S': > try: > item_set = factory('Set', product_code) > item_set.getItems() > self.products.extend(item_set.getItems()) > except: > print 'problem occured:' + type + ':' + product_code > else: > pass > There's definitely *something* wrong - this shouldn't take 20 seconds, let alone 20 minutes. How frequently do you see the print type + ":" + product_code statement producing output? In other words, is the slowness distributed across the task, or is there a delay at the beginning or end? Are the Set and Item classes exactly as shown in your last post? regards Steve PS: Please put your answer at the bottom, not the top! -- 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 http Sun Jul 1 11:42:16 2007 From: http (Paul Rubin) Date: 01 Jul 2007 08:42:16 -0700 Subject: object references/memory access References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> Message-ID: <7xfy48871j.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > No. The CGI script has a file handle, and it is not possible to pass > a file handle to a different process. > > > If there is not a good Pythonic way to do the above, I am open to > > mixing in some C to do the job if that is what it takes. > > No, it's not Python that fails to support that - it's the operating > system. See above for solutions that avoid one such copying in > the first place. If this is a Linux server, it might be possible to use the SCM_RIGHTS message to pass the socket between processes. That would require a patch to Python's socket library which I've never gotten around to writing but it's been on my want-to-do list for a long time. There is something similar for Solaris and probably for *BSD. I've been under the impression that this is how preforked Apache distributes requests between processes, but I never got around to checking. http://sourceforge.net/tracker/index.php?func=detail&aid=814689&group_id=5470&atid=355470 From zyzhu2000 at gmail.com Wed Jul 25 12:12:18 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 25 Jul 2007 16:12:18 -0000 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <1185379218.286977.124040@19g2000hsx.googlegroups.com> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <1185379218.286977.124040@19g2000hsx.googlegroups.com> Message-ID: <1185379938.110260.213840@k79g2000hse.googlegroups.com> On Jul 25, 11:00 am, kyoso... at gmail.com wrote: > On Jul 25, 10:46 am, beginner wrote: > > > > > > > On Jul 25, 10:19 am, Stargaming wrote: > > > > On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote: > > > > Hi, > > > > > I am wondering how do I 'flatten' a list or a tuple? For example, I'd > > > > like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4]. > > > > A recursive function, always yielding the first element of the list, > > > could do the job. See the ASPN Python Cookbook for a few implementations.http://aspn.activestate.com/ASPN/search? > > > query=flatten§ion=PYTHONCKBK&type=Subsection > > > > > Another question is how do I pass a tuple or list of all the aurgements > > > > of a function to the function. For example, I have all the arguments of > > > > a function in a tuple a=(1,2,3). Then I want to pass each item in the > > > > tuple to a function f so that I make a function call f(1,2,3). In perl > > > > it is a given, but in python, I haven't figured out a way to do it. > > > > (Maybe apply? but it is deprecated?) > > > >>> def foo(a, b, c): print a, b, c > > > ... > > > >>> t = (1, 2, 3) > > > >>> foo(*t) > > > > 1 2 3 > > > > Have a look at the official tutorial, 4.7.4http://www.python.org/doc/ > > > current/tut/node6.html#SECTION006740000000000000000 > > > > > Thanks, > > > > cg > > > > HTH, > > > Stargaming > > > Hi Stargaming, > > > I know the * operator. However, a 'partial unpack' does not seem to > > work. > > > def g(): > > return (1,2) > > > def f(a,b,c): > > return a+b+c > > > f(*g(),10) will return an error. > > > Do you know how to get that to work? > > > Thanks, > > cg > > As I mentioned, you can access the elements individually using square > brackets. The following works: > > f(g()[0], g()[1], 10) > > But it's not clear. Unfortunately, I'm not seeing much else for tuple > unpacking except the obvious: > > a,b=g() > f(a,b,10) > > Mike- Hide quoted text - > > - Show quoted text - Unfortunately f(g()[0], g()[1], 10) is calling g() twice. Sometimes this is not a good idea. > a,b=g() > f(a,b,10) would work until you want it to be an expression. From python at jayloden.com Sun Jul 1 13:32:37 2007 From: python at jayloden.com (Jay Loden) Date: Sun, 01 Jul 2007 13:32:37 -0400 Subject: Reversing a string In-Reply-To: References: <1182997438.541012.54100@o61g2000hsh.googlegroups.com> Message-ID: <4687E535.5080401@jayloden.com> Evan Klitzke wrote: > >> I guess that's it. The first one reads more like a textbook example which >> is about where I am at. Is there any speed benefit from the one liner? > > The one line is quite a bit faster: > > evan at thinkpad ~ $ python -m timeit 's = "onomatopoeia"; s = s.join(s[::-1])' > 100000 loops, best of 3: 6.24 usec per loop > > evan at thinkpad ~ $ python -m timeit ' >> def rev(x): >> mylist = [] >> for char in x: >> mylist.append(char) >> mylist.reverse() >> return "".join(mylist) >> >> s = "onomatopoeia" >> s = rev(s)' > 100000 loops, best of 3: 9.73 usec per loop For what it's worth, with python 2.5 on my Macbook: [jloden at macbook jloden]$ python -m timeit 's = "onomatopoeia"; s = s.join(s[::-1])' 100000 loops, best of 3: 5.2 usec per loop [jloden at macbook jloden]$ python -m timeit ' > def rev(x): > mylist = list(x) > mylist.reverse() > return "".join(mylist) > > s = "onomatopoeia" > s = rev(s)' 100000 loops, best of 3: 3.94 usec per loop Note that in the second version, I changed the code a little bit so that it no longer iterates over every char in the string and instead just calls lis() to convert it to a list of chars in order to call list.reverse() on it. -Jay From wildemar at freakmail.de Thu Jul 12 11:51:58 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Thu, 12 Jul 2007 17:51:58 +0200 Subject: Lists in classes In-Reply-To: <1184254414.236260.108860@m3g2000hsh.googlegroups.com> References: <1184253811.052346.220470@22g2000hsm.googlegroups.com> <1184254414.236260.108860@m3g2000hsh.googlegroups.com> Message-ID: <46964E1E.3050203@freakmail.de> Bart Ogryczak wrote: > On 12 jul, 17:23, Jeremy Lynch wrote: > >> Hello, >> >> Learning python from a c++ background. Very confused about this: >> >> ============ >> class jeremy: >> list=[] >> > > You've defined list (very bad choice of a name, BTW), as a class > variable. To declare is as instance variable you have to prepend it > with "self." > > Ouch! 'self' is *not* a reserved ord in python, it doesn't do anything. So just popping 'self' in front of something doesn't bind it to an instance. Here is how it works: class Jeremy(object): # you better inherit from 'object' at all times classlist = [] # class variable def __init__(self): # "constructor" self.instancelist = [] # instance variable def add_item(self, item): self.instancelist.append(item) 'self' is the customary name for the first argument of any instance method, which is always implicitly passed when you call it. I think it translates to C++'s 'this' keyword, but I may be wrong. Simply put: The first argument in an instance-method definition (be it called 'self' or otherwise) refers to the current instance. Note however that you don't explicitly pass the instance to the method, that is done automatically: j = Jeremy() # Jeremy.__init__ is called at this moment, btw j.add_item("hi") # See? 'item' is the first arg you actually pass I found this a bit confusing at first, too, but it's actually very clean, I think. /W From info at gegereka.org Mon Jul 16 18:00:53 2007 From: info at gegereka.org (GEGEREKA!) Date: 16 Jul 2007 22:00:53 GMT Subject: [Music Movies Soft] Free binaries search & download = www.GEGEREKA.com Message-ID: <469bea94$0$13764$2e0edba0@news.tweakdsl.nl> Project of the year: Incredible unique search machine like nothing on earth. MP3,MPEG,AVI,DIVX,DLL,PHP,EXE,ISO, ...and much more Millions files for everyone. Music, movies, soft and other media. http://www.GEGEREKA.com : THE LORD OF DOWNLOADS. From tony.meyer at gmail.com Sat Jul 21 22:55:53 2007 From: tony.meyer at gmail.com (Tony Meyer) Date: Sun, 22 Jul 2007 02:55:53 -0000 Subject: Regex doesn't support MULTILINE? In-Reply-To: References: Message-ID: <1185072953.251263.245540@e9g2000prf.googlegroups.com> > I'm trying to extract information from a web page using the Re module, > but it doesn't seem to support MULTILINE: [...] > Do I need to add something else to have Re work as intended? I believe you are looking for DOTALL, not MULTILINE. From the documentation: """ M MULTILINE When specified, the pattern character "^" matches at the beginning of the string and at the beginning of each line (immediately following each newline); and the pattern character "$" matches at the end of the string and at the end of each line (immediately preceding each newline). By default, "^" matches only at the beginning of the string, and "$" only at the end of the string and immediately before the newline (if any) at the end of the string. S DOTALL Make the "." special character match any character at all, including a newline; without this flag, "." will match anything except a newline. """ If you do a lot of working with regular expressions, then I highly recommend Kodos (http://kodos.sourceforge.net) as a tool for interactively figuring out issues. Cheers, Tony Meyer From doug at alum.mit.edu Mon Jul 2 21:28:34 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Mon, 02 Jul 2007 21:28:34 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: Lenard Lindstrom writes: >> I'm not sure I understand you here. You're saying that I should have >> the foresight to wrap all my file opens is a special class to >> facilitate debugging? > Obviously you had the foresight to realize with statements could > compromise debugging. I never considered it myself. It's not really so much a matter of having foresight, as much as having had experience debugging a fair amount of code. And, at times, having benefited from the traditional idiomatic way of coding in Python, where files are not explicitly closed. Since there are benefits with the typical coding style, and I find there to be no significant downside, other than if, perhaps some code holds onto tracebacks, I suggest that the problem be idiomatically addressed in the *few* code locations that hold onto tracebacks, rather than in all the *myriad* code locations that open and close files. >> Or are you suggesting that early in __main__.main(), when I wish to >> debug something, I do something like: >> __builtins__.open = __builtins__.file = MyFile >> ? >> I suppose that would work. > No, I would never suggest replacing a builtin like that. Even > replacing a definite hook like __import__ is risky, should more than > one package try and do it in a program. That misinterpretation of your idea would only be reasonable while actually debugging, not for standard execution. Standard rules of coding elegance don't apply while debugging, so I think the misinterpretation might be a reasonable alternative. Still I think I'd just prefer to stick to the status quo in this regard. > As long as the code isn't dependent on explicitly cleared > exceptions. But if it is I assume it is well documented. Typically the resource in question is an open file. These usually don't have to be closed in a particularly timely fashion. If, for some reason, a files absolutelys need to be closed rapidly, then it's probably best to use "with" in such a case. Otherwise, I vote for the de facto standard idiom of relying on the refcounter along with explicitly clearing exceptions in the situations we've previously discusses. If some code doesn't explicitly clear an exception, though, and holds onto the the most recent one while running in a loop (or what have you), in the cases we are considering, it hardly seems like the end of the world. It will just take a little bit longer for a single file to be closed than might ideally be desired. But this lack of ideal behavior is usually not going to cause much trouble. |>oug From mahall at ncsa.uiuc.edu Mon Jul 23 17:13:05 2007 From: mahall at ncsa.uiuc.edu (Matteo) Date: Mon, 23 Jul 2007 14:13:05 -0700 Subject: Extracting attributes from compiled python code or parse trees Message-ID: <1185225185.546338.84980@m3g2000hsh.googlegroups.com> Hello- I am trying to get Python to extract attributes in full dotted form from compiled expression. For instance, if I have the following: param = compile('a.x + a.y','','single') then I would like to retrieve the list consisting of ['a.x','a.y']. I have tried using inspect to look at 'co_names', but when I do that, I get: >>> inspect.getmembers(param)[23] ('co_names', ('a', 'x', 'y')) with no way to determine that 'x' and 'y' are both attributes of 'a'. The reason I am attempting this is to try and automatically determine data dependencies in a user-supplied formula (in order to build a dataflow network). I would prefer not to have to write my own parser just yet. Alternatively, I've looked at the parser module, but I am experiencing some difficulties in that the symbol list does not seem to match that listed in the python grammar reference (not surprising, since I am using python2.5, and the docs seem a bit dated) In particular: >>> import parser >>> import pprint >>> import symbol >>> tl=parser.expr("a.x").tolist() >>> pprint.pprint(tl) [258, [326, [303, [304, [305, [306, [307, [309, [310, [311, [312, [313, [314, [315, [316, [317, [1, 'a']], [321, [23, '.'], [1, 'x']]]]]]]]]]]]]]]], [4, ''], [0, '']] >>> print symbol.sym_name[316] power Thus, for some reason, 'a.x' seems to be interpreted as a power expression, and not an 'attributeref' as I would have anticipated (in fact, the symbol module does not seem to contain an 'attributeref' symbol) (for the curious, here is the relevant part of the AST for "a**x": [316, [317, [1, 'a']], [36, '**'], [315, [316, [317, [1, 'x']]]] ) Anyway, I could write an AST analyzer that searches for the correct pattern, but it would be relying on undocumented behavior, and I'm hoping there is a better way. (By the way, I realize that malicious users could almost certainly subvert my proposed dependency mechanism, but for this project, I'm guarding against Murphy, not Macchiavelli) Thanks, -matt From lucaberto at libero.it Mon Jul 2 09:35:35 2007 From: lucaberto at libero.it (luca72) Date: Mon, 02 Jul 2007 06:35:35 -0700 Subject: unify els database Message-ID: <1183383335.842730.41600@q69g2000hsb.googlegroups.com> Hello How i can use to connect to a unify els database with python Regards Luca From stefan.behnel-n05pAM at web.de Wed Jul 11 06:25:30 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 11 Jul 2007 12:25:30 +0200 Subject: stripping the first byte from a binary file In-Reply-To: <1184148168.639675.85900@a26g2000pre.googlegroups.com> References: <1184063032.195000.25880@i13g2000prf.googlegroups.com> <1184115964.912526.273780@e16g2000pri.googlegroups.com> <1184148168.639675.85900@a26g2000pre.googlegroups.com> Message-ID: <4694B01A.30107@web.de> rvr wrote: > On Jul 11, 1:28 pm, Steven D'Aprano > wrote: >> On Wed, 11 Jul 2007 01:06:04 +0000, rvr wrote: >>> Is there a way to edit the file in place? The best I seem to be able to >>> do is to use your second solution to read the file into the string, then >>> re-open the file for writing and put the whole thing back (minus the >>> first byte). Thanks. >> I don't believe that any of the popular operating systems in common use >> (Windows, Linux, Mac, *BSD) have any such functionality. >> >> For safety, you are best off copying the file (minus the first byte) to a >> temporary file, then renaming the copy over the original. That way if >> your process dies midway through copying the file, you don't lose data. >> >> Renaming the file is atomic under Linux and (probably) Mac, so it is as >> safe as possible. Even under Windows, which isn't atomic, it has a >> smaller margin for disaster than over-writing the file in place. > > Thanks for your response. While searching for solution, I found this: > > http://mail.python.org/pipermail/python-list/2001-December/116519.html > > Quoting from it: > > """ > Replace 2 bytes in place beginning at offset 100 (101st byte): > > f = open('text_input', 'r+b') > f.seek(100) > f.write(chr(123) + chr(0x80)) > f.seek(0,2) > f.close() > """ > > Can I use the seek() and write() methods in a similar way to remove > the first byte? For whatever reason I can't seem to make it work > myself. Thanks again. Funny. I just happened to read ESR's "how to ask questions the smart way" and your posts match quite a few of the examples. :) No, you can't. Steven's solution is what I'd go for. Stefan From nospam.themindstorm at gmail.com Wed Jul 25 19:18:43 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Wed, 25 Jul 2007 23:18:43 +0000 (UTC) Subject: Singleton in Python Cookbook References: <5gq00tF3fm71gU1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in news:5gq00tF3fm71gU1 at mid.uni-berlin.de: > Alex Popescu schrieb: >> Hi all! >> >> I was reading through Python Cookbook the Singleton recipe. At this >> moment I am a bit puzzled as the example in the book is not working >> resulting in: >> >> TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of >> type >> >> (I haven't presented the original code as I am not sure about >> copyrights). > > AFAIK the cookbook is completely found online at ASPN. So no sweat > publishing it here. > > > And regarding the problem: is it possible that you forgot to subclass > SingleSpam from object? > > Diez The exact code: class Singleton(object): """ A Pythonic Singleton """ def _ _new_ _(cls, *args, **kwargs): if '_inst' not in vars(cls): cls._inst = type._ _new_ _(cls, *args, **kwargs) return cls._inst if _ _name_ _ == '_ _main_ _': class SingleSpam(Singleton): def _ _init_ _(self, s): self.s = s def _ _str_ _(self): return self.s s1 = SingleSpam('spam') print id(s1), s1.spam( ) s2 = SingleSpam('eggs') print id(s2), s2.spam( ) ./alex -- .w( the_mindstorm )p. From python at jayloden.com Tue Jul 24 09:40:12 2007 From: python at jayloden.com (Jay Loden) Date: Tue, 24 Jul 2007 09:40:12 -0400 Subject: Tix not properly installed on OS X? In-Reply-To: <48B39FEC-D3B9-4FAF-AD45-0DD744D8D289@bryant.edu> References: <48B39FEC-D3B9-4FAF-AD45-0DD744D8D289@bryant.edu> Message-ID: <46A6013C.8010201@jayloden.com> Brian Blais wrote: > Hello, > > I am running OS X 10.4, on an Intel Mac, Python 2.5 not installed by > source (I used the binary install from the website). When I do the > following, I get an error: > > 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 Tix > >>> root=Tix.Tk() > Traceback (most recent call last): > File "", line 1, in > File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ > python2.5/lib-tk/Tix.py", line 210, in __init__ > self.tk.eval('package require Tix') > _tkinter.TclError: can't find package Tix > I can confirm the same behavior and Google results are not promising: http://www.thescripts.com/forum/thread653175.html http://aspn.activestate.com/ASPN/Mail/Message/ActivePython/3525325 I tried installing Tix from the binary TclAqua package, and when I run root=Tix.Tk() I still get the same error (though, interestingly, a Tk window does open). Looks like your best bet right now would be to install Tix via fink if that's an option. -Jay From klove at tax.ok.gov Thu Jul 26 17:18:46 2007 From: klove at tax.ok.gov (Kenneth Love) Date: Thu, 26 Jul 2007 16:18:46 -0500 Subject: Comparing Dictionaries Message-ID: <6.1.0.6.2.20070726150104.0291f1b0@tax.ok.gov> Hello, I am new to Python, but not programming. I would like to start my Python career by developing programs according to the "best practices" of the industry. Right now, that appears to be unit tests, patterns, and source code control. So, I am trying to write a unit test for some code that reads a Windows style INI file and stores the section, key, and values in a dictionary (recipe originally found on ASPN, but heavily modified for my needs). ------------------------------ class LoadIni(unittest.TestCase): knownDefault = { "database$dbms": "mysql", "database$name": "thelarch", "database$user": "nobody", "database$password": "special", "database$host": "127.0.0.1" } def testNoIniFilename(self): """A default configuration list should be returned.""" result = ini.load() # These next two print statement show the same key/value pairs, # but in a different order. #print knownDefault #print result self.assertEqual(result, self.knownDefault) # does not work ------------------------------- In this case, I need to compare the returned dictionary (result) with the known default dictionary (knownDefault). This needs to be a comparison of the dictionary key/value pairs. If all of the key/value pairs are an exact match and no extra key/value pairs are in either dictionary then I consider the two dictionaries to be equivalent. In other words, I consider these two dictionaries to be equivalent: { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'mickey' } { 'mouse' : 'mickey', 'dog' : 'bone', 'cat' : 'fever' } while these two are not: { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'mickey' } { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'michael' } Any suggestions on how to compare these via some assert statement? Am I even on the right track with the INI file storing results in a dictionary? When I found the code, it just "felt right". NOTE: The code works, I can load the INI file, programmatically change a few settings, save the results to a new INI file, and manually compare the resulting files. I get the expected results. It is the automation of this testing process that appears to be the stumbling block. adTHANKSvance, Kenneth Love -- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Kenneth Love | Oklahoma Tax Commission DP Programmer/Analyst | Information Technology (405) 522 - 5864 | http://www.tax.ok.gov/ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- From deets at nospam.web.de Sun Jul 1 16:14:25 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 01 Jul 2007 22:14:25 +0200 Subject: how to send files via bluetooth with python to a mobile In-Reply-To: <46880a0b$0$37195$4fafbaef@reader3.news.tin.it> References: <1183294323.556314.293860@m36g2000hse.googlegroups.com> <1183305873.736724.116680@c77g2000hse.googlegroups.com> <1183306850.712226.313800@m36g2000hse.googlegroups.com> <1183310919.771396.268760@q69g2000hsb.googlegroups.com> <5eq94iF3a5b8bU1@mid.uni-berlin.de> <46880a0b$0$37195$4fafbaef@reader3.news.tin.it> Message-ID: <5eqg94F39cdomU1@mid.uni-berlin.de> morphine schrieb: > Diez B. Roggisch wrote: > >> Wrap this >> >> http://www.zuckschwerdt.org/apidocs/ > > seams that python bindings are already there? > http://dev.zuckschwerdt.org/openobex/wiki/ObexFtpExampleClientPython Cool, didn't find that. diez From gherron at islandtraining.com Fri Jul 6 03:07:30 2007 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 06 Jul 2007 00:07:30 -0700 Subject: import In-Reply-To: <1183704647.460604.102100@e9g2000prf.googlegroups.com> References: <1183704647.460604.102100@e9g2000prf.googlegroups.com> Message-ID: <468DEA32.7090408@islandtraining.com> jolly wrote: > Hey guys, > > I'm rather new to python and i'm have trouble(as usual) > > I want to know if it is possible to change where 'import' looks.... > this will save me clogging up my python directory > > Thanks > Easily done. The value of sys.path is a list of directories that import looks through to satisfy an import. Just import sys and append a new directory to sys.path. import sys sys.path.append('/your/directory/of/importable/modules') // Then import code from your directory. From iladijas at gmail.com Tue Jul 10 13:42:36 2007 From: iladijas at gmail.com (fynali) Date: Tue, 10 Jul 2007 10:42:36 -0700 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: <1184050285.997766.299860@d55g2000hsg.googlegroups.com> References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> Message-ID: <1184089356.305178.292060@o61g2000hsh.googlegroups.com> > > 19729 > > Did you count the 'L'? > (-: From B.Ogryczak at gmail.com Thu Jul 12 11:30:54 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: Thu, 12 Jul 2007 15:30:54 -0000 Subject: Lists in classes In-Reply-To: <1184253811.052346.220470@22g2000hsm.googlegroups.com> References: <1184253811.052346.220470@22g2000hsm.googlegroups.com> Message-ID: <1184254254.245748.16490@o61g2000hsh.googlegroups.com> On 12 jul, 17:23, Jeremy Lynch wrote: > Hello, > > Learning python from a c++ background. Very confused about this: > > ============ > class jeremy: > list=[] > def additem(self): > self.list.append("hi") > return > > temp = jeremy() > temp.additem() > temp.additem() > print temp.list > > temp2 = jeremy() > print temp2.list > ============== > The output gives: > ['hi','hi'] > ['hi','hi'] > > Why does adding items to one instance produce items in a separate > instance? Doesn't each instance of jeremy have its' own "list"? You've defined list (very bad choice for a name), as a class variable. To declare instance variable you should have written: class jeremy: From sjmachin at lexicon.net Tue Jul 17 18:55:15 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 18 Jul 2007 08:55:15 +1000 Subject: really small values In-Reply-To: References: Message-ID: <469d48d3@news.eftel.com.au> On 18/07/2007 7:13 AM, Dee Asbury wrote: > In multiplying a value of xe^-325 with ye^-4, Python is returning zero. > How do I get it to give me back my tiny value? > It is difficult to understand what you mean by xe^-325 etc ... in Python, ^ is the bitwise exclusive-or operator. The power operator is ** Consider this: >>> import math >>> math.exp(-325) 7.1497915694453328e-142 >>> In other words, e ** (-325) is of the order of 7.15 * 10 ** (-142) Also consider that the smallest positive number that can be represented by the (almost universal) IEEE 754 64-bit floating-point representation is about 10**(-308). So under one interpretation of "e^-325" (1.0e-325), your result is already effectively zero; under the other interpretaion (math.exp(-325)) it is nowhere near zero. Perhaps you had better show us the (no more than 10) lines of actual runable Python code that demonstrate your problem. HTH, John From chris.lyon at spritenote.co.uk Fri Jul 27 03:23:43 2007 From: chris.lyon at spritenote.co.uk (chris.lyon at spritenote.co.uk) Date: Fri, 27 Jul 2007 00:23:43 -0700 Subject: generating objects of a type from a name. In-Reply-To: References: <1185495706.034366.58180@k79g2000hse.googlegroups.com> Message-ID: <1185521023.517719.32320@d55g2000hsg.googlegroups.com> On Jul 27, 1:59 am, tsuraan wrote: > I'm not sure what a visual object is, but to create an instance of an > object whose name is known, you can use "eval": > > >>> oname = 'list' > >>> obj = eval(oname)() > >>> obj > [] > >>> type(obj) > > > > Hope that helps! > > On 26/07/07, chris.l... at spritenote.co.uk wrote: > > > I'm trying to generate visual python objects from django objects and > > therefore have objects called 'Ring' and 'Cylinder' as django objects > > and I want to create objects of those names in visual. > > I can cludge it in varius ways by using dir and lots of if lookups but > > is there a way of doing this that allows the name to generate a > > visual object of the appropriate name or fail nicely if the visual > > object doesn't exist? > > > -- > >http://mail.python.org/mailman/listinfo/python-list Thanks for that. That's the answer. visual python is an fine programme for generating 3D objects (http:// www.vpython.org/) which generates an image from simple python code. import visual a = visual.sphere() generates a window with a 3D lit rendering of a white sphere which you can easily fly around with the mouse. a.blue = 0 makes it a yellow sphere and a.x = 1 moves it one unit along the x axis. I'm using it to create a visual representative of objects stored in the database, so I'm mapping the database objects to visual objects. Thanks once again. I hadn't considered eval, but once it's pointed out, it's obvious. Chris From ilia.meerovich at gmail.com Mon Jul 30 02:53:59 2007 From: ilia.meerovich at gmail.com (ilia.meerovich at gmail.com) Date: Sun, 29 Jul 2007 23:53:59 -0700 Subject: Xinetd & python server script. problem to get data from from client Message-ID: <1185778439.961647.28370@g4g2000hsf.googlegroups.com> Hello I wrote simple script to test communication: When i connect via telnet like: "telnet localhost 51423" the server is working send and receive information. but when i connected to him via client scrip so client script receive messages from server but server doesn't receive message from client. In xinetd.conf and servers conf file "only_from = 0.0.0.0/0" already choosen. What can i do? Here below are my client and server: Thank you :) Server: #!/usr/bin/env python # example import sys import os print "Wellcome" print "please enter the string" sys.stdout.flush() line = sys.stdin.readline().strip() print "You entered %d characters." % len(line) sys.stdout.flush() client: import sys import string import os import time import socket import popen2 PORT = 51423 HOST = ""#sys.argv[1] sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((HOST, PORT)) print "Connected from:", sock.getsockname() print "Connected to:",sock.getpeername() while 1: print "waiting" result = sock.recv(1024) print result sock.send('foo') print "Sent: foo" if result == 3: break From http Sat Jul 21 02:05:35 2007 From: http (Paul Rubin) Date: 20 Jul 2007 23:05:35 -0700 Subject: Permutations with generators References: <1184996537.069416.211730@g4g2000hsf.googlegroups.com> Message-ID: <7xzm1qgukw.fsf@ruckus.brouhaha.com> Pablo Torres writes: > def perm(seq): > "Reshuffles the elements of seq in every possible way" > if len(seq) == 1: > yield seq > else: > for p in perm(seq[1:]): > for i in range(len(seq)): > yield p.insert(i, seq[0]) It's easiest to avoid these mutating schemes and instead just generate each permutation separately. def perm(seq): if len(seq) == 0: yield [] for (i,s) in enumerate(seq): for p in perm(seq[:i]+seq[i+1:]): yield [s]+p From cp.finances.gouv at gmail.com Mon Jul 2 05:32:08 2007 From: cp.finances.gouv at gmail.com (cp.finances.gouv at gmail.com) Date: Mon, 02 Jul 2007 02:32:08 -0700 Subject: urllib2 : https and proxy In-Reply-To: References: <1183021663.053143.275090@q69g2000hsb.googlegroups.com> <20070628182216.GA4332@gmail.com> <46842A5F.1080506@aristote.info> Message-ID: <1183368728.086695.10960@n60g2000hse.googlegroups.com> On 2 juil, 05:04, "O.R.Senthil Kumaran" wrote: > * Maric Michaud [2007-06-28 23:38:39]: > > > Hmmm, i've tried something similar but I get the same result. > > > For the code example I gave, I've put correctly the http_proxy and > > https_proxy environment variables, the default ProxyHandler get them right > > as this is the proxy itself which returns the error. I checked this with > > wireshark, the proxy said that there is incompatibilities in some request > > methods, like POST, with some protocols, Gopher is the example it gave. > > That doesn't make much sense to me as the wget command I tried is intended > > to do exactly the same thing (POST over https and retrieve some cookies from > > the response), and go through with no problems. > > Maric, in the ActiveState urllib2 HOWTO which seems to apply for Python 2.5, I > came across a point which mentions urllib2 does not support PROXY for HTTPS. Yes, I realize this too, I think this should be considered as a bug in the documentation. > Your case seems the same, I would suggest you to look up the Python Tracker > for any already open issues, or if not kindly log one yourself. Didn't find one when i made a quick search, but i would suggest to submit a documentation bug. BTW, I find this recipe on python cookbook, http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/456195, works fine for me (with the two additionals comments in my case). We could add a pointer to this in the doc before fixing urllib2. What would you suggest ? > -- > O.R.Senthil Kumaranhttp://uthcode.sarovar.org From bj_666 at gmx.net Fri Jul 13 04:57:02 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 13 Jul 2007 08:57:02 GMT Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: <5fot2uF3dm8bpU1@mid.uni-berlin.de> On Fri, 13 Jul 2007 08:37:00 +0200, Hendrik van Rooyen wrote: > "Donn Cave" wrote: > >>In its day, goto was of course very well loved. > > Does anybody know for sure if it is in fact possible to > design a language completely free from conditional jumps? GOTO is unconditional. I guess it depends on what you call a jump. > At the lower level, I don't think you can get away with > conditional calls - hence the "jumps with dark glasses", > continue and break. > > I don't think you can get that functionality in another way. Don't think in terms of calls and jumps but conditionally evaluating functions with no side effects. > Think of solving the problem of reading a text file to find > the first occurrence of some given string - can it be done > without either break or continue? (given that you have to > stop when you have found it) Finding an element in a list in Haskell: findFirst needle haystack = f 0 haystack where f _ [] = -1 f i (x:xs) | x == needle = i | otherwise = f (i+1) xs No ``break`` or ``continue`` but a recursive function. > I can't think of a way, even in assembler, to do this without > using a conditional jump - but maybe my experience has > poisoned my mind, as I see the humble if statement as a plethora > of local jumps... Technically yes, and with exceptions we have non local jumps all over the place. You are seeing the machine language behind it, and of course there are lots of GOTOs, but not "uncontrolled" ones. The language above hides them and allows only a limited set of jumps. Easing the proofs that the program is correct. If you have a conditional call you can proof both alternative calls and build the proof the the function that builds on those alternatives on them. Trying to guess how some source would look like in machine language isn't that easy anymore the higher the abstraction level of the used programming language is. In Haskell for example you have to keep in mind that it uses lazy evaluation and that the compiler knows very much about the program structure and data types and flow to do optimizations. Ciao, Marc 'BlackJack' Rintsch From bjourne at gmail.com Fri Jul 13 21:49:31 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 14 Jul 2007 01:49:31 +0000 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: <740c3aec0707131849j2ada06abj825fbe05d465f36b@mail.gmail.com> On 7/13/07, John Nagle wrote: > You can sometimes get better performance in C++ than in C, because C++ > has "inline". Inline expansion happens before optimization, so you > can have abstractions that cost nothing. C99 has that too. > Python is a relatively easy language, easier than C++, Java, > or even Perl. It's quite forgiving. The main implementation, > CPython, is about 60x slower than C, though, so if you're trying > to implement, say, a rapidly changing digital oscilloscope display, > the result may be sluggish. But if the data for that oscilloscope comes from an external device connected via a serial port, execution speed won't matter. -- mvh Bj?rn From byte8bits at gmail.com Tue Jul 31 09:58:56 2007 From: byte8bits at gmail.com (brad) Date: Tue, 31 Jul 2007 09:58:56 -0400 Subject: Directory In-Reply-To: <1185831827.206641.163630@x40g2000prg.googlegroups.com> References: <1185831827.206641.163630@x40g2000prg.googlegroups.com> Message-ID: 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. How far down do you want to go? All the way to the bottom: for root, dirs, files in os.walk('.'): for d in dirs: print os.path.join(root, d) #################################### Only your current directory: x = os.listdir('.') for item in x: if os.path.isdir(item): print item From abhingar at bellsouth.net Tue Jul 10 06:24:25 2007 From: abhingar at bellsouth.net (Atul Bhingarde) Date: Tue, 10 Jul 2007 06:24:25 -0400 Subject: highly einteractive editor for python References: Message-ID: I liked what the Wing IDE provides, one question though will it provide facility like creating the GUI widgets (say using TK) and facilitaate layout for the same and then run the script ? Thanks Atul "Steve Holden" wrote in message news:mailman.509.1184032416.22759.python-list at python.org... > Atul Bhingarde wrote: >> Does anybody know an editor that facilitates, interactive python >> development. Where GUI etc developed will be possible to see in real time >> mode. >> >> Thanks >> >> Atul > Wind IDE is great for debugging GUI-based programs - you can set > breakpoints in event-handling routines and see them activate when your > program responds to mouse clicks and so on. > > http://wingware.com/ > > 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 twisted0n3 at gmail.com Sun Jul 8 15:48:34 2007 From: twisted0n3 at gmail.com (Twisted) Date: Sun, 08 Jul 2007 19:48:34 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1183841277.333384.188950@g4g2000hsf.googlegroups.com> <1183856442.027967.272530@g4g2000hsf.googlegroups.com> Message-ID: <1183924114.414672.92430@n60g2000hse.googlegroups.com> On Jul 8, 12:18 pm, Bjorn Borud wrote: > uh, I think the point here is that some think it might be an idea to > force *their* idea of the ideal interface upon others, refusing to > understand that people might have their own preferences. I, for one, have a strong preference for interfaces that let me see what the hell I'm doing and make it easy to find commands, navigate the interface, navigate the help, and so forth, while making me resort to reaching for that help as infrequently as reasonably achievable. But that's just me. From steve at REMOVE.THIS.cybersource.com.au Sun Jul 22 06:43:11 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 22 Jul 2007 20:43:11 +1000 Subject: problem with exec References: <1185099810.772825.284620@m3g2000hsh.googlegroups.com> Message-ID: On Sun, 22 Jul 2007 03:23:30 -0700, vedrandekovic wrote: > Thanks for everything previously, but just to I ask about code > indentation,this with { and } doesn't > employed, here is my example how can I solve this about code > indentation: > >>>> n=90 >>>> if n==90: > {print "bok kjai ma'} > File "", line 2 > {print "bok kjai ma'} > ^ > SyntaxError: invalid syntax Steve Holden was playing silly games. You can't use { } for indentation. You have to use indentation. -- Steven. From doug at alum.mit.edu Mon Jul 2 14:07:57 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Mon, 02 Jul 2007 14:07:57 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: Lenard Lindstrom writes: >> You don't necessarily want a function that raises an exception to >> deallocate all of its resources before raising the exception, since >> you may want access to these resources for debugging, or what have >> you. > No problem: > > [...] > > >>> class MyFile(file): > def __exit__(self, exc_type, exc_val, exc_tb): > if exc_type is not None: > self.my_last_posn = self.tell() > return file.__exit__(self, exc_type, exc_val, exc_tb) I'm not sure I understand you here. You're saying that I should have the foresight to wrap all my file opens is a special class to facilitate debugging? If so, (1) I don't have that much foresight and don't want to have to. (2) I debug code that other people have written, and they often have less foresight than me. (3) It would make my code less clear to ever file open wrapped in some special class. Or are you suggesting that early in __main__.main(), when I wish to debug something, I do something like: __builtins__.open = __builtins__.file = MyFile ? I suppose that would work. I'd still prefer to clear exceptions, though, in those few cases in which a function has caught an exception and isn't going to be returning soon and have the resources generally kept alive in the traceback. To me, that's the more elegant and general solution. |>oug From tenax.raccoon at gmail.com Mon Jul 23 13:25:21 2007 From: tenax.raccoon at gmail.com (Jason) Date: Mon, 23 Jul 2007 17:25:21 -0000 Subject: decorators tutorials In-Reply-To: <1185178383.499234.299850@z24g2000prh.googlegroups.com> References: <1185178383.499234.299850@z24g2000prh.googlegroups.com> Message-ID: <1185211521.843260.8200@k79g2000hse.googlegroups.com> On Jul 23, 2:13 am, james_027 wrote: > Hi, > > I am learning python by learning django, and I stumble upon decorator > which is very cool, any beginners resources for python decorators, > although I can google it, I just want to get a good tutorial for this > topic. > > Thanks > james Remember that functions in Python are created when their containing scope is parsed. Let's suppose you want a way to help you debug function calls. This should catch any uncaught exceptions, log a message to the logging system, and start a pdb interpreter. It should allow the SystemExit exception to continue to propogate without doing those actions. The following example would do that appropriately: def HelpDebug(func, *args, **keyargs): "Assist with debugging a function." # The func argument is a Pythong function object # arg is the positional arguments that follow the # first parameter, and keyargs has the keyword arguments. try: returnValue = func(*args, **keyargs) return returnValue except SystemExit: raise # Reraise the system exit exception except Exception, error: from logging import DEBUG, log from sys import exc_info import pdb log(DEBUG, "Caught Exception: %s", error) # Start the debugger at the place where the # exception occurred pdb.post_mortem(exc_info()[2]) return # Nothing to return when an exception occurred def DivXY(x, y): "Divides X by Y" return x / y # Debug the following calls HelpDebug(DivXY, 5.0, 2.1) # This will succeed HelpDebug(DivXY, 10.0, 0.0) # Causes a ZeroDivisionError exception There's a serious problem, though. If you'd like to remove the debugging effect, you need to change all your "HelpDebug(DivXY, xvalue, yvalue)" calls to "DivXY(xvalue, yvalue)". Besides, you're trying to get the result of DivXY, not HelpDebug. The calling code shouldn't care about HelpDebug at all. We could do change HelpDebug so it always calls DivXY, but then we need to create a new function for each one we want to debug. This is where nested scopes come in. Other code should care about calling DivXY, but not HelpDebug. Furthermore, the caller shouldn't be able to casually tell the difference between calling a regular DivXY or the HelpDebug'ed DivXY. Well, if the caller shouldn't be able to casually tell the difference between DivXY with or without the debugging code, then we need to be able to do the following: value1 = DivXY(5.0, 2.1) # The regular call value2 = HelpDebugDivXY(5.0, 2.1) # The debugged call We could create a special "HelpDebugDivXY" function for every such function, but that would quickly exhaust our patience, and introduce lots of extra code that can have bugs. Python has nested scoping, though. If you nest a function inside another function, the inner function has access to the names in the outer function. That doesn't sound too spectacular at first. HOWEVER, in Python functions are objects! The outer function can return the inner function object. Even though the outer function has returned, /the inner function still has access to the outer function's names/! For example: >>> def GetPrintXFunc(x): ... "Returns a function that takes no parameters, but prints the argument" ... # Inner function starts just below ... def PrintX(): ... "Prints the object bound to the name x in enclosing scope." ... print "X is", x ... # A function object is now bound to the name "PrintX" ... return PrintX ... >>> PrintSpam = GetPrintXFunc("Spam") >>> PrintPi = GetPrintXFunc(3.14159) >>> PrintSpam() X is Spam >>> PrintPi() X is 3.14159 >>> Both PrintSpam and PrintPi keep access to their enclosing scope's arguments! In Python, the "def" statement is actually a statement... and IT ISN'T EVALUATED UNTIL ITS ENCLOSING SCOPE IS EXECUTED. Take that in. That is entirely unlike C or C++, where a function definition is evaluated at compile time. In Python, all statements are evaluated at run time. This works even for nested classes. Here's the modified code to help us debug: def WrapWithHelpDebug(func): """Returns a function object that transparently wraps the parameter with the HelpDebug function""" # The def statement actually defines a function object and binds # it to a name. Since it is nested in this function, the def # statement isn't evaluated until def HelpDebug(*args, **keyargs): "Assist with debugging a function." # The func argument is a Pythong function object # arg is the positional arguments that follow the # first parameter, and keyargs has the keyword arguments. try: # The name "func" comes from the outer scope, WrapWithHelpDebug returnValue = func(*args, **keyargs) return returnValue except SystemExit: raise # Reraise the system exit exception except Exception, error: from logging import DEBUG, log from sys import exc_info import pdb log(DEBUG, "Caught Exception: %s", error) # Start the debugger at the place where the # exception occurred pdb.post_mortem(exc_info()[2]) return # Nothing to return when an exception occurred # Back in the WrapWithHelpDebug scope. # HelpDebug is now a function objected defined in this scope. def DivXY(x, y): "Divides X by Y" return x / y DebugDivXY = WrapWithHelpDebug(DivXY) # Debug the following calls DivXY(5.0, 2.1) # This will succeed DebugDivXY(10.0, 0.0) # Causes a ZeroDivisionError exception Wow, that's pretty easy, isn't it! But, it's not as easy as it could be. Let's say that DivXY is used a lot, and you want to debug all calls to it. Rather than change the calls to "DivXY" to "DebugDivXY" everywhere, we can simply assign the wrapped function object to the DivXY name. Instead of: DebugDivXY = WrapWithHelpDebug(DivXY) We use: DivXY = WrapWithHelpDebug(DivXY) Now, all calls to DivXY call the HelpDebug object that uses our original DivXY function! This is *exactly* what a decorator does. Instead of writing: def DivXY(x, y): "Divides X by Y" return x / y DivXY = WrapWithHelpDebug(DivXY) You write: @WrapWithHelpDebug def DivXY(x, y): "Divides X by Y" return x / y To turn off the help-debug behavior, simply comment out the decorator. This has turned out to be a bit long, so I'll finish up in the next post.... --Jason From vodela.sai at gmail.com Thu Jul 26 17:58:44 2007 From: vodela.sai at gmail.com (Rohan) Date: Thu, 26 Jul 2007 21:58:44 -0000 Subject: CSV Issue In-Reply-To: <1185485549.302845.3420@b79g2000hse.googlegroups.com> References: <1185484756.890736.10890@q75g2000hsh.googlegroups.com> <1185485549.302845.3420@b79g2000hse.googlegroups.com> Message-ID: <1185487124.099292.299920@l70g2000hse.googlegroups.com> On Jul 26, 2:32 pm, John Machin wrote: > On Jul 27, 7:19 am, Rohan wrote: > > > f = open("/home/t/tp/va/e7.csv", "ab") > > a means Append -- you are appending the data that you expect to the > EXISTING contents of the file. Hello John, Yea silly mistake, write mode will do. thanks From steve at holdenweb.com Mon Jul 16 21:32:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 16 Jul 2007 21:32:24 -0400 Subject: sqlite3 db update extremely slow In-Reply-To: <1184627356.324577.257470@g4g2000hsf.googlegroups.com> References: <1184613750.873464.312390@r34g2000hsd.googlegroups.com> <1184627356.324577.257470@g4g2000hsf.googlegroups.com> Message-ID: coldpizza wrote: > Thanks a lot, Roel, adding a single commit() at the end did solve the > speed problem. > > Another question is do I have to explicitly close the DB connection, > or is it automatically garbage collected? Is it Ok to no have any > cleanup code? > It's generally OK, but you can register a function with atexit() if you are paranoid about cleanup. Here's a sample with an ugly global variable. from atexit import register def close(): global conn if conn: conn.close() print "Database closed" conn = None # # We try to ensure the database is always closed by registering # the nodule's close() function to be called on program exit # register(close) import psycopg2 as db conn = db.connect(database="billing", user="steve", password="tadaa!") curs = conn.cursor() print "Database opened" > Another question would be how to define the encoding for newly added > records? > And how do set the encoding for the retrieved records? Is it always > utf-8 by default? > Generally speaking each database instance will have an associated encoding. Trying to establish some other encoding would then be pissing into the wind. 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 Sat Jul 14 04:03:45 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 14 Jul 2007 10:03:45 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net><1i0n0tr.ve0o791347ugyN%aleax@mac.com><7xd4za1086.fsf@ruckus.brouhaha.com><5f0mhuF3b0stbU1@mid.individual.net><7xd4z837e2.fsf@ruckus.brouhaha.com><468b7426$0$9063$426a34cc@news.free.fr><7x4pkkun56.fsf@ruckus.brouhaha.com><1183575597.272150.152200@w5g2000hsg.googlegroups.com><7xzm2budfv.fsf@ruckus.brouhaha.com><7xir8vju1l.fsf@ruckus.brouhaha.com><7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: <01a501c7c5ee$6a382060$03000080@hendrik> "Lenard Lindstrom" wrote: > Pascal has no break, continue or return. Eiffel doesn't even have a > goto. In such imperative languages boolean variables are used a lot. Thanks did not know this. > > from StringIO import StringIO > lines = StringIO("one\ntwo\nthree\nfour\n") > line_number = 0 > eof = False > found = False > while not (eof or found): > line = lines.readline() > eof = line == "" > found = line == "three\n" > if not found: > line_number += 1 > > > if found: > print "Found at", line_number > else: > print "Not found" > # prints "Found at 2" > All right, so it is possible, with some legerdemain, forcing the main loop to stop when the condition is met. However, I find the above as clear as mud, compared to: line_number = 0 for line in my_file: line_number += 1 if "the Target" in line: break print line_number, line - Hendrik From nick at craig-wood.com Thu Jul 12 06:30:05 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 12 Jul 2007 05:30:05 -0500 Subject: 2**2**2**2**2 wrong? Bug? References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> <1184173446.779276.250530@k79g2000hse.googlegroups.com> <1184182757.797808.206480@d55g2000hsg.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Wed, 11 Jul 2007 16:39:17 -0300, Paul McGuire > escribi?: > > > As was > > pointed out earlier, left-associativity with exponentiation is of > > little value, since (2**3)**2 is the same as 2**(3*2) or 2**6=64. > > Just for curiosity: This helps to find the answer to the problem "Which is > the largest number that can be written with only 3 digits?" > Some people stop at 999, others try 99**9 and 9**99, and the winner is > 9**9**9, or: Actually I think 9**9E9 is bigger! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From afriere at yahoo.co.uk Tue Jul 17 22:25:39 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 17 Jul 2007 19:25:39 -0700 Subject: In a dynamic language, why % operator asks user for type info? In-Reply-To: References: <1184631007.920803.147790@j4g2000prf.googlegroups.com> <1184631512.329438.90050@i13g2000prf.googlegroups.com> <1184632433.980754.189240@d30g2000prg.googlegroups.com> <1184634387.15828.47.camel@blackwidow.nbk> Message-ID: <1184725539.689107.314450@g12g2000prg.googlegroups.com> On Jul 17, 5:38 pm, Duncan Booth wrote: > indeed anything which has an __int__ method may be > passed to the %d formatter: Anything?! Sorry to be persnickety here, but what about this: class C : def __int__ (self) : pass '%d' % C() or this: def foo (val) : return val foo.__int__ = lambda x=42 : int(x) '%d' % foo('spam') OK, they can be passed ... From schmir at gmail.com Fri Jul 20 05:18:10 2007 From: schmir at gmail.com (schmir at gmail.com) Date: Fri, 20 Jul 2007 09:18:10 -0000 Subject: Using eggs or py2exe to distribute apps In-Reply-To: References: Message-ID: <1184923090.222804.36300@57g2000hsv.googlegroups.com> On Jul 20, 5:39 am, Marcus wrote: > Hi, > > I'm to the stage where I need to deploy the app I built with wxPython. > I've been able to successfully build it w/py2exe into a binary (about > 10MB size in total). > > What I'd like to do is create an automatic updater, so that I can have > users download updated versions of my *application code* without having > to have them redownload everything (the interpreter, etc) via a complete > redownload (I want to package some things as "components"). > > Eggs seem like an ideal solution, but I haven't had any luck using them > in conjunction with py2exe. > It should be possible. exclude your application code from being packaged, copy an egg file to your disribution directory and add it to sys.path. > It would seem that the most effective solution would be to package a > python interpreter (with wxPython, etc already included) into the > distributed app's directory and not use py2exe at all; however, since > everything would be included in the distribution, it would seem that the > full python distro would be huge (50MB at least), which defeats the > purpose of wanting to build the app into "components". > > Worst-case scenario would be to have them redownload the 10MB update > each time, but that's less than ideal, since the audience for my program > would have more frequent/less substantial updates over time, rather than > big updates all at once. > > Any guidance or suggestions are very much appreciated. You can try bbfreeze from http://cheeseshop.python.org/pypi/bbfreeze/ (of which I'm the author). It has support for egg files. If you package your application code as an egg, it will by default copy your whole egg (either as a directory or zipped) to the distribution folder. > > Marcus From nospam.themindstorm at gmail.com Wed Jul 25 17:30:14 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Wed, 25 Jul 2007 21:30:14 +0000 (UTC) Subject: Singleton in Python Cookbook Message-ID: Hi all! I was reading through Python Cookbook the Singleton recipe. At this moment I am a bit puzzled as the example in the book is not working resulting in: TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of type (I haven't presented the original code as I am not sure about copyrights). bests, ./alex -- .w( the_mindstorm )p. From scott.daniels at acm.org Tue Jul 17 21:51:55 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 17 Jul 2007 18:51:55 -0700 Subject: Relative Imports In-Reply-To: References: Message-ID: <139qsgejpkejn5b@corp.supernews.com> Pat O'Hara wrote: > Hey guys, I know this is a really stupid question, but I've tried > googling and nothing came up. I also tried IRC, but it was too crowded > and I didn't get much useful information. > > I'm using Python 2.5 on WinXP, and I'm trying to do a relative import. > Here's the package structure > > A/ > __init__.py > aneededmodule.py > [some more modules] > B/ > __init__.py > anothermodule.py > > anothermodule.py needs to use aneededmodule.py; package A's __init__.py > looks like this: > > from aneededmodule import somestuff > > My problem is that when anothermodule tries to import ..aneededmodule or > ..somestuff (because somestuff was imported into __init__), I get a > ValueError: Attempted relative import in non-package. > > What's my problem? This seems like something very trivial, but I've > never had to use python for a project of this size before, so I've never > dealt with this. > > Thanks for your help, > -Pat My guess (without seeing your code or error messages; shame on you) is that you are running A/B/anothermodule.py; not -m A.B.anothermodule -- --Scott David Daniels scott.daniels at acm.org From kyosohma at gmail.com Tue Jul 31 09:13:53 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 31 Jul 2007 13:13:53 -0000 Subject: Plotting Images In-Reply-To: References: Message-ID: <1185887633.733959.83780@m37g2000prh.googlegroups.com> On Jul 31, 6:41 am, Pei-Yu CHAO wrote: > Hi ALL: > > I have only been switched from matlab to python few > months ago. I having trouble of plotting images from a > matrix size of 8x10000 (unfortunately that is the size > of my data.....) > > for example, > x = rand(8,10000) > inshow(x) > > I have tried to use matplotlib function imshow(), but > all i get is a long thin line (unable to see the color > display and the my matrix information). > > i think imshow() has the same problem in matlab, but i > think there is a alternative in matlab, imagesc(). > > I did search on web about plt.imagesc().....but when i > try to run the example code, python just tell me > cannot find module plt. > > >>>from scipy import plt > > ImportError: cannot import name plt > > I have installed scipy, wxpython2.6....and it still > seem not to work! > > is there some alternitive? or what have i done wrong? > Thank you > > Pei > > ____________________________________________________________________________________ > ?????????????????????? Yahoo!??????????http://tw.mobile.yahoo.com/texts/mail.php The wxPython mailing list would be the better place for this set of questions. I see them talking about this topic quite a bit. Here's a link to their list: http://www.wxpython.org/maillist.php Mike From David.Bergsbaken at axcelis.com Wed Jul 25 10:45:12 2007 From: David.Bergsbaken at axcelis.com (Bergsbaken, David) Date: Wed, 25 Jul 2007 10:45:12 -0400 Subject: Python course around Boston Message-ID: Is there such a course? From steve at holdenweb.com Sun Jul 15 08:00:06 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 15 Jul 2007 08:00:06 -0400 Subject: Getting values out of a CSV In-Reply-To: <1184476688.405321.122740@m3g2000hsh.googlegroups.com> References: <1184295593.638409.22910@22g2000hsm.googlegroups.com> <1184476688.405321.122740@m3g2000hsh.googlegroups.com> Message-ID: Alex Popescu wrote: > On Jul 14, 5:55 am, "Gabriel Genellina" > wrote: >> So, as always, one should measure in each specific case if optimization is >> worth the pain [...]. >> > > I hope I am somehow misreading the above sentence :-). IMO synonim > language contructs > should result in the same performance or at least have clear/ > documented performance. That's a fine opinion, how would you enforce it? Should we go throught he interpreter slowing down the faster to each pair of alternative constructs? ;-) It's inevitable there'll be differences in execution time between equivalent constructs, and in that case you have to test to find the better in your specific situation. The real issue here is that in 95% or more of the source of most programs speed/performance isn't that much of an issue anyway. > I don't think we really want to see in code something like: > > if threshold: > do_it_with_list_function > else: > do_it_with_list_comprehension > This would most certainly be a premature optimization which, as has been repeated many times on this list, is the root of much evil in programming. As Gabriel mentioned, you only need to do it if it's "worth the pain", which in most case it won't be. It isn't worth spending even five minutes to shave a minute off the performance of a ten-minute program that is only run once a week, for example. Ultimately we have to be pragmatic: circumstances alter cases, and it's usually not worth spending the time to improve execution speed except for the most critical parts (the innermost nested loops) of production programs. 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 Jul 27 14:27:43 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 27 Jul 2007 20:27:43 +0200 Subject: 128 or 96 bit integer types? References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com> Message-ID: Robert Dailey wrote: > Is there build-in or third party support for large integer types, such > as 96 or 128 bits in size? I require such large sizes for precision > issues (nanoseconds). Thanks. >>> SECOND = 10**9 >>> YEAR = 365*24*60*60 >>> 2**128/SECOND/YEAR 10790283070806014188970L What are you measuring? The age of the universe? In nanoseconds? :-) Peter From alexandre.ferrieux at gmail.com Mon Jul 23 02:56:18 2007 From: alexandre.ferrieux at gmail.com (Alexandre Ferrieux) Date: Sun, 22 Jul 2007 23:56:18 -0700 Subject: Lazy "for line in f" ? In-Reply-To: References: <1185120650.412694.314280@o61g2000hsh.googlegroups.com> <1185143634.778056.227720@g4g2000hsf.googlegroups.com> Message-ID: <1185173778.656660.195650@n60g2000hse.googlegroups.com> On Jul 23, 1:03 am, Steve Holden wrote: > > What makes you think Python doesn't use the platform fgets()? The fact that it does that extra layer of buffering. Stdio is already buffered, duplicating this is useless. > ... in the case of file.next() (the file method called to > iterate over the contents) it will actually use getc_unlocked() on > platforms that offer it, though you can override that configuration > feature by setting USE_FGETS_IN_GETLINE Does nothing. And anyway, stdio's getc() does not stubbornly block on 8k either. So switching from getc to gets seems orthogonal to the problem. > It's probably more to do with the buffering. If whatever is driving the > file is using buffering itself, then it really doesn't matter what the > Python library does, it will still have to wait until the sending buffer > fills before it can get any data at all. Nonsense. In all three cases of pipe, socket, terminal, I control the writer and make sure that it writes in unbuffered manner. To convince you, here is an strace of the Python process while I type random lines like "fdsfdsfds": read(0, "sdfsdf\n", 8192) = 7 read(0, "sdfds\n", 7168) = 6 which proves that the Python process actually gets the lines one by one, but buffers them internally... for much too long. Sigh. > Try running stdin unbuffered (use python -u) and see if that makes any > difference. It should, in the shell-driven case, for example. No effect. As a matter of fact, -u is documented as affecting only output (stdout and stderr). So I'll reiterate the question: *why* does the Python library add that extra layer of (hard-headed) buffering on top of stdio's ? -Alex From bdesth.quelquechose at free.quelquepart.fr Wed Jul 25 15:40:37 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 25 Jul 2007 21:40:37 +0200 Subject: making a variable available in a function from decorator In-Reply-To: References: <5h5e3lF3hmufcU1@mid.uni-berlin.de> Message-ID: <46ae3e60$0$634$426a34cc@news.free.fr> Evan Klitzke a ?crit : > On 7/30/07, rkmr.em at gmail.com wrote: > >>is it possible to do this without passing it as a function argument? >> > Sort of. Functions are objects in python, so you can set attribute on them. E.g. > > def foo(): > return foo.c > > foo.c = 1 > print foo() >>> def foo(): ... print foo.c ... >>> foo.c = 1 >>> bar = foo >>> del foo >>> bar() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in foo NameError: global name 'foo' is not defined >>> > Which will print 1. Of course, it would generally be better to write > your own class for this sort of thing, so that you can set the > variable in the instance scope. Indeed. But even with OO, explicit is better than implicit. From rrr at ronadam.com Tue Jul 17 22:18:41 2007 From: rrr at ronadam.com (Ron Adam) Date: Tue, 17 Jul 2007 21:18:41 -0500 Subject: Break up list into groups In-Reply-To: <9e95df10707171408k2dfc8e08wd4056b80fcbe309b@mail.gmail.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> <1184694533.380918.169640@m37g2000prh.googlegroups.com> <469D09CC.3080402@ronadam.com> <9e95df10707171408k2dfc8e08wd4056b80fcbe309b@mail.gmail.com> Message-ID: <469D7881.6030504@ronadam.com> Matt McCredie wrote: > That certainly is fast, unfortunately it doesn't pass all of the tests. > I came up with those tests so I don't know how important they are to the > original poster. I modified it and came up with a generator and a > non-generator version based (roughly) on your algorithm, that are almost > as quick, and pass all of the tests. Some of the modifications were done > just to make it quicker, so it would be fair when comparing against the > other methods. I hard-coded the comparison instead of using a function > and created a function that directly generates and returns a list > instead of a generator. I would probably use the generator version in my > code, but wrapping `list' around a generator adds about 4us (on my > machine). Anyway, getgroups7 passes all of the tests I mentioned and it > was timed at 10.37usec/pass. The down side: the code doesn't seem nearly > as elegant. > > Matt In most cases you wouldn't wrap the generator version in a list(), but use it directly as a loop iterator. A little renaming of variables helps it be a bit more elegant I think ... def getgroups8(seq): groups = [] iseq = iter(xrange(len(seq))) for start in iseq: if seq[start] & 0x80: for stop in iseq: if seq[stop] & 0x80: groups.append(seq[start:stop]) start = stop groups.append(seq[start:]) return groups This passes all the tests and runs about the same speed. Cheers, Ron > > def gengroups7(seq): > iseq = iter(xrange(len(seq))) > start = 0 > for i in iseq: > if seq[i]&0x80: > start = i > break > else: > return > for i in iseq: > if seq[i]&0x80: > yield seq[start:i] > start = i > yield seq[start:] > > > def getgroups7(seq): > groups = [] > iseq = iter(xrange(len(seq))) > start = 0 > for i in iseq: > if seq[i]&0x80: > start = i > break > else: > return groups > for i in iseq: > if seq[i]&0x80: > groups.append(seq[start:i]) > start = i > groups.append(seq[start:]) > return groups > > > > > > From joncle at googlemail.com Sun Jul 29 18:14:02 2007 From: joncle at googlemail.com (Jon Clements) Date: Sun, 29 Jul 2007 15:14:02 -0700 Subject: Understanding mxODBC Insert Error In-Reply-To: References: Message-ID: <1185747242.265227.166930@g4g2000hsf.googlegroups.com> On 29 Jul, 17:41, Greg Corradini wrote: > Hello, > I'm trying to perform a simple insert statement into a table called > Parcel_Test (see code below). Yet, I get an error message that I've never > seen before (see traceback below). I've tried to put a semicolon at the end > of the sql statement, but with no luck. Any ideas from more experienced > mx.ODBC users? > > CODE > > >>> driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace > >>> conn = odbc.DriverConnect(driv) > >>> crs = conn.cursor() > >>> sql = "INSERT into Parcel_Test(NEAR_FID,NEAR_DIST) values > >>> ('0.000000','0.000000') where PIN_ID = '042822120008'" > >>> crs.execute(sql) > > TRACEBACK > Traceback (most recent call last): > File "", line 1, in ? > crs.execute(sql) > ProgrammingError: ('37000', -3516, '[Microsoft][ODBC Microsoft Access > Driver] Missing semicolon (;) at end of SQL statement.', 4612) > > -- > View this message in context:http://www.nabble.com/Understanding-mxODBC-Insert-Error-tf4166125.htm... > Sent from the Python - python-list mailing list archive at Nabble.com. Apart from what John Machin has said, your SQL also looks like it's half trying to be an insert with a subselect clause (looking at the 'where') rather than a values clause. Access might well be expecting a semicolon after the values statement, as the where might be starting another. Don't have mxODBC, so it's all untested - Just an idea. Jon. From __peter__ at web.de Tue Jul 24 18:40:35 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 25 Jul 2007 00:40:35 +0200 Subject: printing unicode strings References: <1185310571.173514.240940@r34g2000hsd.googlegroups.com> Message-ID: 7stud wrote: > Can anyone tell me why I can print out the individual variables in the > following code, but when I print them out combined into a single > string, I get an error? > > symbol = u'ibm' > price = u'4 \xbd' # 4 1/2 > > print "%s" % symbol > print "%s" % price.encode("utf-8") > print "%s %s" % (symbol, price.encode("utf-8") ) > > --output:-- > ibm > 4 1/2 > File "pythontest.py", line 6, in ? > print "%s %s" % (symbol, price.encode("utf-8") ) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position > 2: ordinal not in range(128) For format % args, if the format or any arg is a unicode string, the result will be unicode, too. This implies that byte strings have to be decoded, and for that process the default ascii codec is used. In your example > print "%s %s" % (symbol, price.encode("utf-8") ) symbol is a unicode, so python tries to decode "%s %s" and "4 \xc2\xbd" (the result of price.encode("utf8")). The latter contains non-ascii chars and fails. Solution: use unicode throughout and let the print statement do the encoding. >>> symbol = u"ibm" >>> price = u"4 \xbd" >>> print u"%s %s" % (symbol, price) ibm 4 ? Sometimes, e. g. if you redirect stdout, the above can fail. Here's a workaround that uses utf8 in such cases. import sys if sys.stdout.encoding is None: import codecs sys.stdout = codecs.lookup("utf8").streamwriter(sys.stdout) Peter From http Sun Jul 8 01:41:21 2007 From: http (Paul Rubin) Date: 07 Jul 2007 22:41:21 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <468c0827$0$22906$426a74cc@news.free.fr> <7x3b03lusa.fsf@ruckus.brouhaha.com> <468c18fc$0$26377$426a74cc@news.free.fr> Message-ID: <7xabu7e9ku.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > > Some users in fact recommend writing an explicit type signature for > > every Haskell function, which functions sort of like a unit test. > > Stop here. explicit type signature == declarative static typing != > unit test. The user-written signature is not a declaration that informs the compiler of the type. The compiler still figures out the type by inference, just as if the signature wasn't there. The user-written signature is more like an assertion about what type the compiler will infer. If the assertion is wrong, the compiler signals an error. In that sense it's like a unit test; it makes sure the function does what the user expects. > I have few "surprises" with typing in Python. Very few. Compared to > the flexibility and simplicity gained from a dynamism that couldn't > work with static typing - even using type inference -, I don't see it > a such a wonderful gain. At least in my day to day work. I'm going to keep an eye out for it in my day-to-day coding but I'm not so convinced that I'm gaining much from Python's dynamism. However, that may be a self-fulfilling prophecy since maybe I'm cultivating a coding style that doesn't use the dynamism, and I could be doing things differently. I do find since switching to Python 2.5 and using iterators more extensively, I use the class/object features a lot less. Data that I would have put into instance attributes on objects that get passed from one function to another, instead become local variables in functions that get run over sequences, etc. From JHoover at fbi.gov Mon Jul 23 23:23:46 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Mon, 23 Jul 2007 23:23:46 -0400 Subject: idiom for RE matching In-Reply-To: <1185157313.356112.159020@z24g2000prh.googlegroups.com> References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> <1185157313.356112.159020@z24g2000prh.googlegroups.com> Message-ID: <2f6dnUlUxd2_7TjbnZ2dnUVZ_qy3nZ2d@comcast.com> mik3l3374 at gmail.com wrote: > if your search is not overly complicated, i think regexp is not > needed. if you want, you can post a sample what you want to search, > and some sample input. I'm afraid it's pretty complicated :-). I'm doing analysis of hand histories that online poker sites leave for you. Here's one hand of a play money ring game: Full Tilt Poker Game #2042984473: Table Play Chip 344 - 10/20 - Limit Hold'em - 18:07:20 ET - 2007/03/22 Seat 1: grandmarambo (1,595) Seat 4: justnoldfoolm (2,430) Seat 5: rickrn (1,890) Seat 7: harlan312 (820) Seat 8: moi (335) justnoldfoolm posts the small blind of 5 rickrn posts the big blind of 10 The button is in seat #1 *** HOLE CARDS *** Dealt to moi [Jd 2c] harlan312 calls 10 moi folds grandmarambo calls 10 justnoldfoolm raises to 20 rickrn folds harlan312 calls 10 grandmarambo calls 10 *** FLOP *** [7s 8s 2s] justnoldfoolm bets 10 harlan312 raises to 20 grandmarambo calls 20 justnoldfoolm raises to 30 harlan312 calls 10 grandmarambo calls 10 *** TURN *** [7s 8s 2s] [3d] justnoldfoolm bets 20 harlan312 calls 20 grandmarambo calls 20 *** RIVER *** [7s 8s 2s 3d] [7h] justnoldfoolm bets 20 harlan312 folds grandmarambo folds Uncalled bet of 20 returned to justnoldfoolm justnoldfoolm mucks justnoldfoolm wins the pot (220) *** SUMMARY *** Total pot 220 | Rake 0 Board: [7s 8s 2s 3d 7h] Seat 1: grandmarambo (button) folded on the River Seat 4: justnoldfoolm (small blind) collected (220), mucked Seat 5: rickrn (big blind) folded before the Flop Seat 7: harlan312 folded on the River Seat 8: moi didn't bet (folded) So I'm picking out all kinds of info about my cards, my stack, my betting, my position, board cards, other people's cards, etc. For example, this pattern picks out which player bet and how much: betsRe = re.compile('^(.*) bets ([\d,]*)') I have 13 such patterns. The files I'm analyzing are just a session's worth of histories like this, separated by \n\n\n. All of this information needs to be organized by hand or by when it happened in a hand, so I can't just run patterns over the whole file or I'll lose context. (Of course, in theory I could write a single monster expression that would chop it all up properly and organize by context, but it would be next to impossible to write/debug/maintain.) From exarkun at divmod.com Wed Jul 11 07:25:15 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 11 Jul 2007 07:25:15 -0400 Subject: Python IRC bot using Twisted In-Reply-To: <1184151087.537830.40790@n60g2000hse.googlegroups.com> Message-ID: <20070711112515.4947.1480034088.divmod.quotient.10435@ohm> On Wed, 11 Jul 2007 03:51:27 -0700, ddtm wrote: >I have another problem with my IRC bot. There is privmsg(self, user, >channel, msg) function (this function handles the incoming IRC data) >in the code that was mentioned above. I have a special condition in >this function that if a user sends to bot a private message (in other >words: if channel == self.nickname) bot sends it to the main channel. >Everything works fine except sending message to the main channel (for >example #www). I write something like this: >if channel == self.nickname: > self.msg('www', msg) >This code doesn't work. But if try to send private message back to >user: >if channel == self.nickname: > self.msg(user, msg) >everything works fine. I really don't know what to do. > self.msg('www', msg) will send msg to the user named `www'. To send to channels, be sure to include the '#' prefix. Jean-Paul From manasd at gmail.com Mon Jul 16 14:16:07 2007 From: manasd at gmail.com (MD) Date: Mon, 16 Jul 2007 11:16:07 -0700 Subject: Accessing Python variables in an extension module In-Reply-To: <1i1c33r.1tle2a728vehlN%aleax@mac.com> References: <1184553584.757696.92630@g4g2000hsf.googlegroups.com> <1i1b7zw.64m7g071sk32N%aleax@mac.com> <1184591293.938223.105800@o61g2000hsh.googlegroups.com> <1i1c33r.1tle2a728vehlN%aleax@mac.com> Message-ID: <1184609767.983621.151500@o61g2000hsh.googlegroups.com> Hi Alex, Thanks for the answer. Are there any C defines (for e.g. STRING, BOOLEAN) corresponding to each Python type? Thanks, -Manas On Jul 16, 9:53 am, al... at mac.com (Alex Martelli) wrote: > MD wrote: > > Hi Alex, > > Thanks for your reply. It was exactly what I was looking for. Two > > additional questions > > 1) Is there anyway to find out which modules a variable belongs to > > when I have only its name (and its not qualified with the complete > > name like module.varname) > > Loop through all modules in sys.modules and you will find a set (which > may be empty) of modules which happen to have that name as an attribute. > It's a very peculiar thing to do (not clear what you expect to do based > on that information) but not difficult. > > > 2) Is there anyway to find the type of the object in C using something > > like a switch statement? I was looking for something like this > > switch type(object) { > > STRING: "This is a string object"; > > break; > > INTEGER: "This is an integer object"; > > break; > > BOOLEAN: "This is a boolean object"; > > ......... > > ......... > > } > > I don't want to run all the C Py***_Check functions on the object. > > Something like the switch statement above will lead to nice and clean > > code. > > Each Python object, in C, carries a pointer to its type object. Of > course there are unbounded numbers of types, but at least you can get > such information as the type's name and the module if any in which it > may have been defined, essentially like you'd do with type(somobj) if > you were working directly in Python. > > Alex From kasimmominov at gmail.com Fri Jul 6 16:49:53 2007 From: kasimmominov at gmail.com (kasim) Date: Fri, 06 Jul 2007 20:49:53 -0000 Subject: =?iso-8859-9?q?hi_everyone_if_you_want_to_be_come_a_member_please__follow_the_l=FDnk?= Message-ID: <1183754993.909964.121120@w3g2000hsg.googlegroups.com> Sample email Dear ______, I recently joined AGLOCO because of a friend recommended it to me. I am now promoting it to you because I like the idea and I want you to share in what I think will be an exciting new Internet concept. AGLOCO's story is simple: Do you realize how valuable you are? Advertisers, search providers and online retailers are paying billions to reach you while you surf. How much of that money are you making? NONE! AGLOCO thinks you deserve a piece of the action. AGLOCO collects money from those companies on behalf of its members. (For example, Google currently pays AOL 10 cents for every Google search by an AOL user. And Google still has enough profit to pay $1.6 billion dollars for YouTube, an 18-month old site full of content that YouTube's users did not get paid for! AGLOCO will work to get its Members their share of this and more. AGLOCO is building a new form of online community that they call an Economic Network. They are not only paying Members their fair share, but they're building a community that will generate the kind of fortune that YouTube made. But instead of that wealth making only a few people rich, the entire community will get its share. What's the catch? No catch - no spyware, no pop-ups and no spam - membership and software are free and AGLOCO is 100% member owned. Privacy is a core value and AGLOCO never sells or rents member information. So do both of us a favor: Sign up for AGLOCO right now! If you use this link to sign up, I automatically get credit for referring you and helping to build AGLOCO. http://www.agloco.com/r/BBFR2592 foll Thanks From mike.klaas at gmail.com Wed Jul 25 13:48:52 2007 From: mike.klaas at gmail.com (Klaas) Date: Wed, 25 Jul 2007 10:48:52 -0700 Subject: Closures / Blocks in Python In-Reply-To: <1185289112.771239.200260@n60g2000hse.googlegroups.com> References: <1185289112.771239.200260@n60g2000hse.googlegroups.com> Message-ID: <1185385732.292307.193320@g12g2000prg.googlegroups.com> On Jul 24, 7:58 am, treble54 wrote: > Does anyone know a way to use closures or blocks in python like those > used in Ruby? Particularly those used in the { } braces. Inner functions allow you to define closures and (named) blocks anywhere). Anonymous blocks must consist of a single expression. -Mike From rcdailey at gmail.com Fri Jul 27 19:15:26 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 27 Jul 2007 23:15:26 -0000 Subject: C++ Modules for python: How to? In-Reply-To: <1183768797.659079.17150@o11g2000prd.googlegroups.com> References: <1183750094.154566.248170@m36g2000hse.googlegroups.com> <5f7llqF3bfvstU1@mid.uni-berlin.de> <1183764388.576690.31740@n60g2000hse.googlegroups.com> <1183768797.659079.17150@o11g2000prd.googlegroups.com> Message-ID: <1185578126.072526.19550@d55g2000hsg.googlegroups.com> On Jul 6, 7:39 pm, John Machin wrote: > On Jul 7, 9:26 am,RobertDailey wrote: > > > > > On Jul 6, 3:06 pm, "Diez B. Roggisch" wrote: > > > >RobertDaileyschrieb: > > > > > Hi, > > > > > I'm interested in making a C++ library of mine usable through python. > > > > Python does a similar thing with Expat (the non-validating XML > > > > parser). I notice that with Expat, python is importing a C++ header > > > > file into a PY file and the interface is available to python. I've > > > > read through the python documentation as well as done a little bit of > > > > google research and I've not been able to find a tutorial of some sort > > > > on how to do this. Perhaps I just don't know the right words to search > > > > for. > > > > > If anyone could lead me in the right direction (possibly an article, > > > > tutorial, etc) I would greatly appreciate it. > > > > The best thing to do is to offer your C++-lib with a C-style interface. > > > Then you can use python's ctypes (included since python2.5) to access > > > the shared library. > > > > If you insist on using C++, you can expose the lib using several > > > available wrapper generators. I know of three: SIP, Swig & > > > Boost::Python. The first I've got some very good first-hand experience. > > > The second is somewhat primitive IHMO. The third I never used. > > > > Use these to google in this group, you'll find plenty of stuff. > > > > Diez > > > How do I install SIP? I can't seem to do this. I've downloaded the > > package and read the README file, but I don't see a way of installing > > it on windows. I ran the configure.py file but then it generates > > makefiles to run which can't be run on windows. I also attempted to > > download QT but it doesn't appear to be free (it's an evaluation and I > > don't feel like submitting my personal information to download it). > > > Am I missing something? > > Probably. > > "makefiles ... which can't be run on windows"??? Have you acquired a > make program [if necessary] and tried it? What happened? > > The free Borland compiler comes with a make.exe. If you plan to use > GCC, you will probably need this: > http://gnuwin32.sourceforge.net/packages/make.htm > I understand that if you have a Microsoft compiler, you should have an > nmake.exe. > > If all else fails, e-mail the package author, supplying some relevant > information, like what compiler you are using, what options you used > on the configure.py run, which "make" you are using, what happened > when you ran that make, ... The documentation is as follows: "The next step is to build SIP by running your platform's make command. For example: make" I ran "nmake" from the command line and it spammed: cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make cd sipgen make: Error code 194, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' make: Error code 255, while making 'all' I used 'python configure.py -p win32-msvc2005' Any idea why this is failing? From nis at superlativ.dk Mon Jul 2 05:29:36 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Mon, 02 Jul 2007 11:29:36 +0200 Subject: howto resend args and kwargs to other func? In-Reply-To: <4688a103$0$29642$426a34cc@news.free.fr> References: <1183279997.244378.105810@n60g2000hse.googlegroups.com> <1183280667.542964.175570@u2g2000hsc.googlegroups.com> <1183282733.179683.174350@c77g2000hse.googlegroups.com> <5er6doF31bulkU1@mid.individual.net> <4688a103$0$29642$426a34cc@news.free.fr> Message-ID: <4688C580.60804@superlativ.dk> Bruno Desthuilliers skrev: >> Why do people do this without posting what the actual solution is!!!! > > Probably because those people think usenet is a free help desk ? Usenet definitely isn't a help desk. You often get useful answers from usenet, from people who are not reading from a script. Nis From xah at xahlee.org Tue Jul 24 09:04:12 2007 From: xah at xahlee.org (Xah Lee) Date: Tue, 24 Jul 2007 06:04:12 -0700 Subject: The Modernization of Emacs: keyboard shortcuts pain In-Reply-To: <1184764620.778937.264760@m37g2000prh.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272678.877166.209640@j4g2000prf.googlegroups.com> <1184764620.778937.264760@m37g2000prh.googlegroups.com> Message-ID: <1185282252.520022.20780@z28g2000prd.googlegroups.com> Why Emacs's Keyboard Shortcuts Are Painful Xah Lee, 2007-07 A important aspect in designing keyboard shortcuts is to have keyboard shortcuts for those most frequently used commands, and, the most frequently used commands should have most easily-pressed keystrokes. For example, they should be on the home row. Emacs's keyboard shortcut set is very inefficient, largely because, Emacs's keyboard shortcuts are designed with a keyboard that practically has the Ctrl and Alt key positions swapped. [image: 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) ---------- This post is archived and updated at http://xahlee.org/emacs/emacs_kb_shortcuts_pain.html Xah xah at xahlee.org ? http://xahlee.org/ From steve at holdenweb.com Mon Jul 30 06:54:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Jul 2007 06:54:24 -0400 Subject: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why? In-Reply-To: <1185791793.141118.44080@x35g2000prf.googlegroups.com> References: <1185791793.141118.44080@x35g2000prf.googlegroups.com> Message-ID: <46ADC360.20209@holdenweb.com> Gilbert Fine wrote: > This is a very strange exception raised from somewhere in our program. > I have no idea how this happen. And don't know how to reproduce. It > just occurs from time to time. > > Can anyone give me some suggestion to fix this? > If it's raised from "somewhere in your program" the first this to do is disable the except clause that is apparently stopping you from getting a full traceback, then post that traceback with an appropriate code snippet. People on this list are good at guessing, but it's better to give then some hard information to work with. Otherwise you are calling the shop (garage?) and saying "My car doesn't work, can you tell me how to fix it, please?" 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 Tue Jul 17 18:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 17 Jul 2007 17:30:03 -0500 Subject: Embedding/Extending Python in/with C++: non-static members? References: <1184593533.995878.123010@k79g2000hse.googlegroups.com> <1184689489.343144.178550@g37g2000prf.googlegroups.com> Message-ID: dmoore wrote: > I've obviously spent too much time with dynamic languages. The problem > with what I'm trying to do is obvious: In C++ you simply can't pass > pointers to call a particular instance of a C++ class method so there > is no way to initialize the PyMethodDef with class methods instances. It is possible in theory. You can do what python does when it makes a bound method and build a custom function at run time with the instance and method built in. How you build that function is tricky - you've basically got to poke object code onto the heap which implements the method call to that particular instance. Looking at this page might give you some ideas http://gcc.gnu.org/onlinedocs/gccint/Trampolines.html This probably isn't a good approach in reality though as it is very architecture / compiler dependent! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From python-url at phaseit.net Mon Jul 16 07:05:36 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 16 Jul 2007 11:05:36 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jul 16) Message-ID: QOTW: "That's a property of open source projects. Features nobody really needs are not implemented." - Gregor Horvath http://groups.google.com/group/comp.lang.python/msg/1fcefd79c7aa4832 "I'm working in a Java shop, with eclipse - one of the most intimate IDE-lanaguage-relationships imaginable. I get all the auto-completion, refactoring and whatnot-suppopport. And I'd swap it for python + emacs every minute." Diez B. Roggisch How to properly add dynamic methods to classes and instances: http://groups.google.com/group/comp.lang.python/browse_thread/thread/cc04b8e480d4be62/ Enumerating efficiently the power set of a given set is not as easy as first thought: http://groups.google.com/group/comp.lang.python/browse_thread/thread/d9211cd6c65e1d3a/ A classic question revisited twice: Does Python pass parameters by reference or by value?, and a clear explanation by Ben Finney: http://groups.google.com/group/comp.lang.python/browse_thread/thread/45732106f147ac07/ http://groups.google.com/group/comp.lang.python/browse_thread/thread/56e7d62bf66a435c/ Still looking for a way to cleanly reraise an exception after modifying its message? Proves to be a hard task, this thread started a couple weeks ago: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ae351de24f72a834/ A subtle problem with disappearing processes when using os.wait and subprocess.Popen simultaneously: http://groups.google.com/group/comp.lang.python/browse_thread/thread/d8a302bdbfdbf5ef/ For someone coming from electronics and close to the hardware, it's hard to grasp some OOP concepts - but why should one care? (Plus some anecdotes from some '60s newbies...) http://groups.google.com/group/comp.lang.python/browse_thread/thread/916e1f2cfe390bbd/ Bools, their "misbehavior" as ints, and what will happen in Python 3000: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e0e07894a2aa42cb/ ======================================================================== 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. The Python Papers aims to publish "the efforts of Python enthusiats". http://pythonpapers.org/ Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From walterbyrd at iname.com Wed Jul 4 16:54:46 2007 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 04 Jul 2007 13:54:46 -0700 Subject: Does Python work with QuickBooks SDK? In-Reply-To: <1183580876.475984.92860@q69g2000hsb.googlegroups.com> References: <1183575085.446434.13410@z28g2000prd.googlegroups.com> <1183580876.475984.92860@q69g2000hsb.googlegroups.com> Message-ID: <1183582486.509913.172620@i13g2000prf.googlegroups.com> Thanks to Greg and Mike. I am not looking for specifics right now. I was just wondering if there was a practical way to do use python to integrate with intuit apps. Apparently, there is. From istvan.albert at gmail.com Thu Jul 26 22:15:39 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 27 Jul 2007 02:15:39 -0000 Subject: zip() function troubles In-Reply-To: <7xzm1ieils.fsf@ruckus.brouhaha.com> References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> <7xir86wx0p.fsf@ruckus.brouhaha.com> <1185499500.807041.60580@g4g2000hsf.googlegroups.com> <7xzm1ieils.fsf@ruckus.brouhaha.com> Message-ID: <1185502539.598349.159330@l70g2000hse.googlegroups.com> On Jul 26, 9:33 pm, Paul Rubin wrote: > Do a top or vmstat while that is happening and see if you are > swapping. You are allocating 10 million ints and 10 million tuple > nodes, = 20 million objects. Although, even at 100 bytes per object > that would be 1GB which would fit in your machine easily. Is it > a 64 bit cpu? we can safely drop the memory limit as being the cause and think about something else if you try it yourself you'll see that it is very easy to generate 10 million tuples, on my system it takes 3 (!!!) seconds to do the following: size = 10**7 data = [] for i in range(10): x = [ (0,1) ] * size data.append( x ) Now it takes over two minutes to do this: size = 10**7 a = [ 0 ] * size b = zip(a,a) the only explanation I can come up with is that the internal implementation of zip must have some flaws From harriegeertsNOSPAM at home.nl Sun Jul 29 14:10:42 2007 From: harriegeertsNOSPAM at home.nl (Harrie Geerts) Date: Sun, 29 Jul 2007 20:10:42 +0200 Subject: Understanding mxODBC Insert Error In-Reply-To: References: Message-ID: "Greg Corradini" schreef in bericht news:mailman.1310.1185727301.22759.python-list at python.org... > > Hello, > I'm trying to perform a simple insert statement into a table called > Parcel_Test (see code below). Yet, I get an error message that I've never > seen before (see traceback below). I've tried to put a semicolon at the > end > of the sql statement, but with no luck. Any ideas from more experienced > mx.ODBC users? > > CODE >>>> driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace #here a >>>> ; #!!!!!!!!!! >>>> conn = odbc.DriverConnect(driv) >>>> crs = conn.cursor() >>>> sql = "INSERT into Parcel_Test(NEAR_FID,NEAR_DIST) values >>>> ('0.000000','0.000000') where PIN_ID = '042822120008'" >>>> crs.execute(sql) > > TRACEBACK > Traceback (most recent call last): > File "", line 1, in ? > crs.execute(sql) > ProgrammingError: ('37000', -3516, '[Microsoft][ODBC Microsoft Access > Driver] Missing semicolon (;) at end of SQL statement.', 4612) > > > -- > View this message in context: > http://www.nabble.com/Understanding-mxODBC-Insert-Error-tf4166125.html#a11852950 > Sent from the Python - python-list mailing list archive at Nabble.com. > From hjp-usenet2 at hjp.at Wed Jul 4 02:27:33 2007 From: hjp-usenet2 at hjp.at (Peter J. Holzer) Date: Wed, 4 Jul 2007 08:27:33 +0200 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <138jml0ldeucf32@corp.supernews.com> Message-ID: On 2007-07-04 00:14, Dr.Ruud wrote: > Peter J. Holzer schreef: >> Since a day with a leap second has 86401 seconds (or 86399, but that >> hasn't happened yet) > > Many systems allow a seconds value of 0..61, so minutes (actually > months) with two leap seconds are foreseen. That comes from the ANSI C standard. It is unclear why the standard specifies 0..61 instead of 0..60. The most plausible explanation I've read is that it's the result of a misunderstanding: Up to two leap seconds in a year are expected, and somebody thought they would be applied both at the end of the year (instead of one at the end of each semester). > A leap second may be introduced at the end of any month, the preferred > dates are at the end of June and the end of December. > > At the estimated rate of decrease, the earth would lose about 1/2 day > after 4,000 years, and about two leap seconds a > month would be needed to keep UTC in step with Earth time, UT1. C is already ready for this, although I doubt that it's authors planned that far ahead. hp -- _ | Peter J. Holzer | I know I'd be respectful of a pirate |_|_) | Sysadmin WSR | with an emu on his shoulder. | | | hjp at hjp.at | __/ | http://www.hjp.at/ | -- Sam in "Freefall" From martin at see.sig.for.address Wed Jul 11 19:10:12 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Thu, 12 Jul 2007 00:10:12 +0100 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: Ilya Zakharevich wrote: > My point is that attributing something to SH due to it appearing in > ABHoT is like attributing it to you since it was mentioned in your > post... > OK, so who should it be attributed to? -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From deets at nospam.web.de Mon Jul 16 10:54:48 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 16 Jul 2007 16:54:48 +0200 Subject: Private functions and inheritance References: <1184596318.146981.242830@n60g2000hse.googlegroups.com> Message-ID: <5g1f5oF3elgciU1@mid.uni-berlin.de> Maciej Blizi?ski wrote: > Hello, > > I've come across something that I don't quite understand about > Python's inheritance. Consider the following code snippet: > > class A(object): > def call_bar(self): return self.bar() > def call___bar(self): return self.__bar() > def __bar(self): return "A::__bar()" > def bar(self): return "A::bar()" > > class B(A): > def __bar(self): return "B::__bar()" > def bar(self): return "B::bar()" > > b = B() > print "calling B::call_bar():", b.call_bar() > print "calling B::call___bar():", b.call___bar() > > The result is: > > calling B::call_bar(): B::bar() > calling B::call___bar(): A::__bar() > > In the latter case, it calls the base class' implementation. It > probably goes along with Python's spec, but I found it surprising. I > don't want to expose the __bar() function outside, but on the other > hand i want to defer its implementation to a subclass. It seems like I > need to make it public, doesn't it? Yep. Just use a single underscore, and that's it. The reason why this doesn't work as expected is that the name-mangling introduced by the leading double underscores is purely a lexical scope based mechanism. Diez From danb_83 at yahoo.com Tue Jul 17 23:54:13 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Tue, 17 Jul 2007 20:54:13 -0700 Subject: a=0100; print a ; 64 how to reverse this? In-Reply-To: <1184676038.231330.115220@e16g2000pri.googlegroups.com> References: <1184670575.205759.115360@i13g2000prf.googlegroups.com> <1184673934.660465.228280@i13g2000prf.googlegroups.com> <1184676038.231330.115220@e16g2000pri.googlegroups.com> Message-ID: <1184730853.521234.307760@o11g2000prd.googlegroups.com> On Jul 17, 7:40 am, mosi wrote: > Thank you, > this is great, > I thought that this should be standard in python 2.4 or 2.5 or in some > standard library (math ???) > Didn`t find anything. The bin() function is slated to be added to the next version of Python. Why there isn't a general itoa() function, I don't know. From hamish at cloud.net.au Tue Jul 10 18:37:49 2007 From: hamish at cloud.net.au (Hamish Moffatt) Date: Wed, 11 Jul 2007 08:37:49 +1000 Subject: SafeConfigParser can set unsafe values Message-ID: <46940a3e$0$18464$afc38c87@news.optusnet.com.au> SafeConfigParser is supposed to be safer than ConfigParser, but calling set with a string value containing '%' generates exceptions when you get() it back. Python 2.5.1 (r251:54863, Apr 25 2007, 21:31:46) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import configparser Traceback (most recent call last): File "", line 1, in ImportError: No module named configparser >>> import ConfigParser >>> >>> x=ConfigParser.SafeConfigParser() >>> x.add_section('test') >>> x.set('test', 'a', 'hi%there') >>> x.get('test', 'a') Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/ConfigParser.py", line 525, in get return self._interpolate(section, option, value, d) File "/usr/lib/python2.5/ConfigParser.py", line 593, in _interpolate self._interpolate_some(option, L, rawval, section, vars, 1) File "/usr/lib/python2.5/ConfigParser.py", line 634, in _interpolate_some "'%%' must be followed by '%%' or '(', found: %r" % (rest,)) ConfigParser.InterpolationSyntaxError: '%' must be followed by '%' or '(', found: '%there' ConfigParser does not do this: >>> y=ConfigParser.ConfigParser() >>> y.add_section('test') >>> y.set('test', 'a', 'hi%there') >>> y.get('test', 'a') 'hi%there' Should SafeConfigParser.set() be escaping automatically? Hamish From danb_83 at yahoo.com Thu Jul 26 20:20:29 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Thu, 26 Jul 2007 17:20:29 -0700 Subject: question about math module notation In-Reply-To: <7xejiukhjz.fsf@ruckus.brouhaha.com> References: <7xd4ye7vv9.fsf@ruckus.brouhaha.com> <7xejiukhjz.fsf@ruckus.brouhaha.com> Message-ID: <1185495629.464194.313300@57g2000hsv.googlegroups.com> On Jul 26, 3:59 pm, Paul Rubin wrote: > brad writes: > > Ah yes, that works too... thanks. I've settled on doing it this way: > > print int(math.pow(2,64)) > > I like the added parenthesis :) > > I was surprised to find that gives an exact (integer, not > floating-point) answer. Still, I think it's better to say 2**64 > which also works for (e.g.) 2**10000 where math.pow(2,10000) > raises an exception. It *is* binary floating point. Powers of 2 are exactly representable. Of course, it doesn't give an exact answer in general. >>> int(math.pow(10, 23)) 99999999999999991611392L From dwarnold45 at suddenlink.net Sat Jul 7 15:21:41 2007 From: dwarnold45 at suddenlink.net (David) Date: Sat, 07 Jul 2007 12:21:41 -0700 Subject: Timing a python program run Message-ID: <1183836101.040882.56080@i38g2000prf.googlegroups.com> Hi, In matlab, I'd calculate the time for a script named test.m to run with: >> tic, run, toc Is there some way to do this in python on a mac os x from the terminal window? Or whatever? From the.mindstorm.mailinglist at gmail.com Wed Jul 18 06:00:01 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Wed, 18 Jul 2007 03:00:01 -0700 Subject: how to find available classes in a file ? In-Reply-To: References: <2e302$469bf38f$d443bb3a$30036@news.speedlinq.nl> <1184627599.597658.267380@g4g2000hsf.googlegroups.com> Message-ID: <1184752801.010805.241490@e9g2000prf.googlegroups.com> On Jul 17, 4:41 am, "Gabriel Genellina" wrote: > En Mon, 16 Jul 2007 20:13:19 -0300, Alex Popescu > escribi?: > > > On Jul 17, 1:44 am, Stef Mientki > > wrote: > >> I want to have a (dynamically) list of all classes defined in a py-file. > >> Is there a way of getting this list, without manually parsing the file ? > > > I have written something that does something like this, but I am not > > sure it is the pythonic way. > > Bascially I am loading the module and then using dir() on the module > > object I am looking for > > attribute of the type classobj (for old style classes) and type type > > (for new style classes). > > There is also the pyclbr standard module > that does not load the > module (just reparses enough of it to get the info needed). So a broken > import, or any other initialization error, won't hurt. > > > I also heard of the inspect module, but I haven't checked it yet. > > inspect.getmembers(the_module, inspect.isclass) would do. But this > requires the module to be importable. > > -- > Gabriel Genellina I think I have found a difference between my dir(module) based implementation and the inspect.getmember(module, inspect.isclass) functionality. Mine is returning only the classes defined in the provided module, while the later is returning also the imported classes. Am I getting the results wrongly? (I don't seem to see this explanation in the inspect.getmembers doc or I am just misreading it). ./alex -- .w( the_mindstorm )p. From kay.schluehr at gmx.net Thu Jul 12 03:06:14 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 12 Jul 2007 00:06:14 -0700 Subject: PyCF_DONT_IMPLY_DEDENT Message-ID: <1184223974.156675.51660@57g2000hsv.googlegroups.com> I found this flag in codeop.py PyCF_DONT_IMPLY_DEDENT = 0x200 # Matches pythonrun.h It is apperantly a parser flag used in the PARSER_FLAGS define in pythonrun.c. Questions: what does it actually mean and why is this implementation detail exposed to Python code. I tried to change the value and it caused severe problems. When it is a constant anyway why does it have to be passed to the compile function in codeop.py as a variable? Thx From george.sakkis at gmail.com Wed Jul 18 17:17:08 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 18 Jul 2007 21:17:08 -0000 Subject: merge two ranges In-Reply-To: <1184693381.008061.116840@m37g2000prh.googlegroups.com> References: <1184693381.008061.116840@m37g2000prh.googlegroups.com> Message-ID: <1184793428.390366.232150@j4g2000prf.googlegroups.com> On Jul 17, 1:29 pm, anoweb wrote: > I have two ranges of numbers and I need to determine if they overlap > or adjacent and if so return a new range containing the values. The > values are low and high for each pair, such that the first value of > the tuple is always less than or equal to the second value in the > tuple. > > for example: > a = (0, 5) > b = (5, 10) > > print getAdjacent(a, b) # output: (0, 10) > print getAdjacent(b, a) # output: (0, 10) > print getOverlap(a, b) # output: None > print getOverlap(b, a) # output: None > > a = (0, 7) > b = (3, 10) > print getAdjacent(a, b) # output: None > print getAdjacent(b, a) # output: None > print getOverlap(a, b) # output: (0, 10) > print getOverlap(b, a) # output: (0, 10) > > a = (0, 90) > b = (5, 10) > print getAdjacent(a, b) # output: None > print getAdjacent(b, a) # output: None > print getOverlap(a, b) # output: (0, 90) > print getOverlap(b, a) # output: (0, 90) > > a = (0, 5) > b = (12, 20) > print getAdjacent(a, b) # output: None > print getAdjacent(b, a) # output: None > print getOverlap(a, b) # output:None > print getOverlap(b, a) # output: None > > any easy way of doing this? It's not really hard to come up with a quick and dirty solution; however if this isn't a homework or a toy program, take a look at the interval module (http://cheeseshop.python.org/pypi/interval/1.0.0) for a more thought-out design. HTH, George From wildemar at freakmail.de Tue Jul 10 10:13:44 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Tue, 10 Jul 2007 16:13:44 +0200 Subject: Distributing python apps In-Reply-To: <1184013896.006483.176970@w3g2000hsg.googlegroups.com> References: <1184011164.346200.9330@q75g2000hsh.googlegroups.com> <1184011429.403297.270560@n2g2000hse.googlegroups.com> <1184013896.006483.176970@w3g2000hsg.googlegroups.com> Message-ID: <46939418.4060600@freakmail.de> Robert Dailey wrote: > Thanks a ton guys. You both gave me the exact answers I was looking > for. > > Uhm, late entry here, but you might want to consider PyInstaller . Not sure if the project is still alive as I see no mention of Python 2.5 on their site but you never know. /W From stefan.behnel-n05pAM at web.de Thu Jul 26 08:20:43 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 26 Jul 2007 14:20:43 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? In-Reply-To: <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> Message-ID: <46A8919B.10906@web.de> Stefan Scholl wrote: > Well, http://docs.python.org/lib/module-xml.sax.html is missing > the fact, that I can't use Unicode with parseString(). > > This parseString() uses cStringIO. Well, Python unicode is not a valid *byte* encoding for XML. lxml.etree can parse unicode, if you really want, but otherwise, you should maybe stick to well-formed XML. Stefan From steve at REMOVE.THIS.cybersource.com.au Mon Jul 30 08:29:28 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 30 Jul 2007 22:29:28 +1000 Subject: Detecting __future__ features Message-ID: How would one tell at runtime if a particular feature has been enabled by the "from __future__ import thing" statement? For example, I can do this: if 1/2 == 0: print "classic division in use" else: print "true division in use" I could even do this: from keyword import keyword if keyword("with"): print "with statement enabled" else: print "with statement not enabled" (I don't especially care whether the feature in question has been enabled via an explicit call to import, or because it has become the default.) Is there any general mechanism? -- Steven. From p.c.j.kleiweg at rug.nl Sun Jul 22 11:44:51 2007 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Sun, 22 Jul 2007 17:44:51 +0200 Subject: split on NO-BREAK SPACE In-Reply-To: References: Message-ID: Carsten Haese schreef op de 22e dag van de hooimaand van het jaar 2007: > On Sun, 2007-07-22 at 17:15 +0200, Peter Kleiweg wrote: > > Is this a bug or a feature? > > > > > > Python 2.4.4 (#1, Oct 19 2006, 11:55:22) > > [GCC 2.95.3 20010315 (SuSE)] on linux2 > > > > >>> a = 'a b c\240d e' > > >>> a > > 'a b c\xa0d e' > > >>> a.split() > > ['a', 'b', 'c\xa0d', 'e'] > > >>> a = a.decode('latin-1') > > >>> a > > u'a b c\xa0d e' > > >>> a.split() > > [u'a', u'b', u'c', u'd', u'e'] > > It's a feature. See help(str.split): "If sep is not specified or is > None, any whitespace string is a separator." Define "any whitespace". Why is it different in and ? Why does split() split when it says NO-BREAK? -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/kleiweg/ls.html From artdent at freeshell.org Sun Jul 22 03:52:08 2007 From: artdent at freeshell.org (Jacob Lee) Date: Sun, 22 Jul 2007 07:52:08 +0000 (UTC) Subject: ANN: parley 0.3 Message-ID: Release Announcement: PARLEY version 0.3 PARLEY is a library for writing Python programs that implement the Actor model of distributed systems, in which lightweight concurrent processes communicate through asynchronous message-passing. Actor systems typically are easier to write and debug than traditional concurrent programs that use locks and shared memory. With version 0.3, PARLEY now supports the Greenlet execution model (http://codespeak.net/py/dist/greenlet.html). Greenlets are lightweight threads, similar to the tasklets supported by Stackless Python; unlike tasklets, they do not require a special version of Python. PARLEY also supports tasklets and traditional native threads, and it provides the ability to switch between these modes of execution without substantial code changes. Version 0.3 also includes various bug fixes, additional features, and documentation improvements. Code samples, documentation, and source code can be found at the PARLEY home page: http://osl.cs.uiuc.edu/parley/ PARLEY is licensed under the LGPL. -- Jacob Lee From DustanGroups at gmail.com Tue Jul 31 08:33:03 2007 From: DustanGroups at gmail.com (Dustan) Date: Tue, 31 Jul 2007 12:33:03 -0000 Subject: simple string backspace question In-Reply-To: <1185884227.491711.105160@x35g2000prf.googlegroups.com> References: <1185875052.153091.23300@19g2000hsx.googlegroups.com> <1185876068.755101.316320@b79g2000hse.googlegroups.com> <1185884227.491711.105160@x35g2000prf.googlegroups.com> Message-ID: <1185885183.303481.26120@19g2000hsx.googlegroups.com> On Jul 31, 7:17 am, John Machin wrote: > On Jul 31, 8:01 pm, vedrandeko... at v-programs.com wrote: > > > > > On 31 srp, 11:44, vedrandeko... at v-programs.com wrote: > > > > Hello, > > > > I have one simple string, backspace character question.Here is my > > > example: > > > > >>> text="Hello\bworld" > > > >>> print text > > > > "HelloBSworld" > > > > Should this character "\b" (backspace) in this text return this: > > > "Helloworld"? > > > > Regards, > > > Vedran > > > Hi, > > > If you mean on operating system then unfortunately Windows XP. > > Point (1) Works on Windows XP for me: > > C:\junk>ver > > Microsoft Windows XP [Version 5.1.2600] > > C:\junk>\python25\python > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. > > >>> text = "Hello\bworld" > >>> print text > Hellworld > > or, for mild amusement: > > >>> import sys, time > >>> for x in xrange(100): > > ... sys.stdout.write("|/-\\"[x & 3] + "\b") > ... time.sleep(0.1) > ... Now try it on IDLE. > > > 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 ... From exarkun at divmod.com Tue Jul 3 12:18:31 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 3 Jul 2007 12:18:31 -0400 Subject: Debugging "broken pipe" (in telnetlib) In-Reply-To: <1183478065.872544.88680@q69g2000hsb.googlegroups.com> Message-ID: <20070703161831.4947.127519884.divmod.quotient.6429@ohm> On Tue, 03 Jul 2007 08:54:25 -0700, Samuel wrote: >On Jul 3, 3:03 pm, Jean-Paul Calderone wrote: >> EPIPE results when writing to a socket for which writing has been shutdown. >> This most commonly occurs when the socket has closed. You need to handle >> this exception, since you can't absolutely prevent the socket from being >> closed. > >The exception is already caught and logged, but this is really not >good enough. By "handling this exception", do you mean that there is a >way to handle it such that the connection still works? I found some >code that attempts to retry when SIGPIPE was received, but this only >results in the same error all over again. No, the exception indicates the connection is gone. There is no way to continue to transfer data using it. >Why can this not be prevented (in the general case)? Unless something >fancy happened, what can cause the socket to close? Looking at the raw >data received by the connected host, the connection gets lost in mid- >stream; I can not see anything that might cause the remote side to >close the connection (in which case I'd expect a "connection reset by >peer" or something). It is the nature of TCP/IP that the connection might disappear at any moment. The reasons for this vary from someone explicitly calling the close or shutdown API to a wire being unplugged somewhere between the two communicating hosts to a traffic event which results in there being insufficient physical resources to satisfy your particular connection, and so on and so on. It may be the case that whatever is causing your connection to be dropped is entirely avoidable (I can't say, since I don't know what is causing your connection to be dropped), but all of these other causes are not avoidable, and your program might encounter one of them someday. > >> There might be some other change which would be appropriate, though, >> if it is the case that something your application is doing is causing the >> socket to be closed (for example, sending a message which the remote side >> decides is invalid and causing it to close the socket explicitly from its >> end). > >The program is doing the same thing repeatedly and it works 95% of the >time, so I am fairly sure that nothing special is sent. > >> It's difficult to make any specific suggestions in that area without >> knowing exactly what your program does. > >Unfortunately the application is rather complex and a simple test case >is not possible. I used to bother to spend days or weeks trying to track down a subtle bug in a complex system, but I don't anymore. ;) It's much better to spend that time simplifying the software which exhibits the problem until it is simple enough to understand and make the bug obvious. Unit testing and test-driven development have the advantage of pressuring you to write code which is already split into simple enough pieces that this is usually a relatively painless process. For systems not written with this in mind, it can be quite unpleasant to produce a simple example, but it's ultimately still worthwhile. > >Basically, it creates a number of daemon threads, each of which >creates a (thread local, non-shared) instance of telnetlib and >connects to a remote host. Are there any special conditions that must >be taken care of when opening a number of sockets in threads? (The >code runs on AIX 4.1, where Python supports native OS threads.) Oops. Threads. So there's a million possible bugs. Oops AIX, heh, that probably introduces another million. I don't know of anything specifically broken in Python tied to telnetlib and threading on AIX, no, but that just leaves you with the usual suspects. Since I don't have any further specific advice to give you in tracking down this problem, maybe I'll just recommend that you take a look at Twisted, which has a better (although probably somewhat harder to grasp) telnet library, and will let you manage numerous connections without threads. (Of course, if you have a large existing system then switching to something as drastically different as Twisted might not be an option, but it doesn't hurt to suggest it.) Jean-Paul From aleax at mac.com Wed Jul 4 21:41:09 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 4 Jul 2007 18:41:09 -0700 Subject: MethodType/FunctionType and decorators References: <1183589529.198694.109440@m36g2000hse.googlegroups.com> <1183591053.434640.119550@o61g2000hsh.googlegroups.com> Message-ID: <1i0qoq9.u1fu2g63fkmxN%aleax@mac.com> Alex Popescu wrote: ... > - when testing from outside the class definition, the function is > already attached to the class instance and this is the reason why its > type is instancemethod To be more precise: when you access any attribute of a class (or instance thereof), Python checks if that attribute is a descriptor (i.e. the attribute's type has a __get__ method -- there are finer distinctions based on whether it also has a __set__ method, i.e. is or isn't a "data descriptor", but they don't come into play here). A function does have in its type a __get__ method, IOW every (Python-coded) function is a descriptor (a non-data one, btw). So, when you access C.f where C is a class and f's type is Python-coded function, you get the results of calling __get__ on that f object itself. Those results are... the envelope, please!... ta-da: a newly minted method object (whose im_func is f). > - for decorators, my test is executed before the class is defined and > so at that moment the function is still a function; it will become a > methodinstance only after the class definition is closed The function object will never become a method object; it will remain a function object (and you can get at it with C.__dict__['f'] for example); but if you access that name as an attribute of C (or of an instance of C), e.g. as C.f or getattr(C, 'f'), f.__get__ will be called (and return a freshly minted method object whose im_func is f). > Is this correct or am I just fabulating here? You have roughly the right idea (as far as decorators are concerned), just a slightly skewed vision of the rapport between function objects and method objects, which I hoped I helped clarify. Here are a few toy-level examples of what I've been saying, I hope they can further help your understanding of function vs method issues: >>> def f(): pass ... >>> class C(object): pass ... >>> a=C.f Traceback (most recent call last): File "", line 1, in AttributeError: type object 'C' has no attribute 'f' >>> C.f = f >>> a=C.f >>> b=C.f >>> a == b True >>> a is b False >>> type(a), type(b) (, ) >>> a.im_func, b.im_func (, ) >>> a.im_func is f is b.im_func True >>> c=f.__get__(C) >>> type(c) >>> c.im_func >>> c.im_func is C.__dict__['f'] is f True Alex From noah at noah.org Mon Jul 2 12:38:19 2007 From: noah at noah.org (Noah) Date: Mon, 02 Jul 2007 09:38:19 -0700 Subject: Problem with PEXPECT in Python In-Reply-To: <1183258018.859050.241980@o11g2000prd.googlegroups.com> References: <1183251015.454174.261580@x35g2000prf.googlegroups.com> <1183258018.859050.241980@o11g2000prd.googlegroups.com> Message-ID: <1183394299.856452.48760@e16g2000pri.googlegroups.com> Kevin Erickson wrote: > On Jun 30, 5:50 pm, Kevin Erickson wrote: > > #Begin Code > > > > import sys > > import pexpect > > > > def GetServerData(self): > > foo = pexpect.spawn('scp u... at server.com:/home/config/ > > role{/file1,/files/file2,/files/file3} /tmp') > > foo.expect('.*password:*') > > foo.sendline('server_password') > > foo.interact() ... > I have found a work around for my problem. I replace the following line: > > foo.interact() > with > foo.expect(pexpect.EOF) That is correct. But why did you try using interact() method in the first place? I just want to know to see if I could improve the documentation. After you send the password the 'scp' command should finish quickly and exit, so there would be nothing for a human to interact with. You could also try using the run() function which is a simplified interface to pexpect. Something like this might work: pexpect.run ('scp u... at server.com:/home/config/role{/file1,/files/ file2,/files/file3} /tmp', events={'(?i)password': 'server_password'}) That's all there is to it. The run() function will run the given scp command. When it see 'password' in the output it will send the server_password. Yours, Noah Yours, Noah From pabloski at giochinternet.com Sun Jul 8 03:57:13 2007 From: pabloski at giochinternet.com (pabloski at giochinternet.com) Date: Sun, 08 Jul 2007 07:57:13 GMT Subject: Unicode problem References: <5f9t3tF3c8qopU2@mid.uni-berlin.de> <468FC59E.7010609@v.loewis.de> Message-ID: > > What software did you use to make that so? The Python codec certainly > never would do such a thing. > > Are you sure it was latin-1 and \x27, and not windows-1252 and \x92? > > Regards, > Martin you're right...the source of text are html pages and obviously webmasters have poor knowledge of encodings, so the meta declared the encoding as ISO-8859-1 but the real encoding is Windows-1252 and yes it uses \x92 as apostrophe, so the problem isn't Python From bj_666 at gmx.net Fri Jul 6 05:18:58 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Jul 2007 09:18:58 GMT Subject: Where is the syntax for the dict() constructor ?! References: <468D1D9D.6060002@gmail.com> <468D3445.2060408@gmail.com> <1183675552.466967.136360@i13g2000prf.googlegroups.com> Message-ID: <5f6fo1F3b25tsU1@mid.uni-berlin.de> On Fri, 06 Jul 2007 08:34:55 +0200, Hendrik van Rooyen wrote: > "John Machin" wrote: > >> >> I don't know what you mean by "requires more than one >> character of lookahead" -- any non-Mickey-Mouse implementation of a >> csv reader will use a finite state machine with about half-a-dozen >> states, and data structures no more complicated than (1) completed >> rows received so far (2) completed fields in current row (3) bytes in >> current field. When a new input byte arrives, what to do can be >> determined based on only that byte and the current state; no look- >> ahead into the input stream is required, nor is any look-back into >> those data structures. >> > > True. > > You can even do it more simply - by writing a GetField() that > scans for either the delimiter or end of line or end of file, and > returns the "field" found, along with the delimiter that caused > it to exit, and then writing a GetRecord() that repetitively calls > the GetField and assembles the row record until the delimiter > returned is either the end of line or the end of file, remembering > that the returned field may be empty, and handling the cases based > on the delimiter returned when it is. > > This also makes all the decisions based on the current character > read, no lookahead as far as I can see. > > Also no state variables, no switch statements... > > Is this the method that you would call "Mickey Mouse"? Maybe, because you've left out all handling of quoting and escape characters here. Consider this: erik,viking,"ham, spam and eggs","He said ""Ni!""","line one line two" That's 5 elements: 1: eric 2: viking 3: ham, spam and eggs 4: He said "Ni!" 5: line one line two Ciao, Marc 'BlackJack' Rintsch From http Thu Jul 26 16:43:26 2007 From: http (Paul Rubin) Date: 26 Jul 2007 13:43:26 -0700 Subject: I am giving up perl because of assholes on clpm -- switching to Python References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> Message-ID: <7x4pjq7v69.fsf@ruckus.brouhaha.com> M brad writes: > Out of the pan and into the fire. :) Welcome to the world of Ph.D's in > Computer Science. You think the Perl guys have attitude, just wait and > see what you're in for over here. I think you'll find attitudes in any > programming language... just different types. May God have mercy on > your soul! You'll be making a similar announcement in a few weeks when > you switch to Ruby :) The cold, cruel theoretical, lofty Python will > mercilessly crush you :) Come over to comp.lang.functional sometime. I thought I was hardcore but my brain is not big enough for that newsgroup. From samiullah.wahga at gmail.com Mon Jul 9 08:29:35 2007 From: samiullah.wahga at gmail.com (Allin Sex...) Date: Mon, 09 Jul 2007 05:29:35 -0700 Subject: Looking for a Scholarship for your studies?) Message-ID: <1183984175.635024.197690@k79g2000hse.googlegroups.com> Future Center for Students! its for all students looking for scholarships, Student visas for UK, USA, Australia, Get the List of the worlds best universties & so much more. Commited to give u golden opportunities.. Just visit us at: http://www.mixmasti.com/futurecentre/scholarships.asp From imageguy1206 at gmail.com Thu Jul 19 07:02:15 2007 From: imageguy1206 at gmail.com (imageguy) Date: Thu, 19 Jul 2007 11:02:15 -0000 Subject: Open HTML file in IE In-Reply-To: <1184739605.732844.321180@m37g2000prh.googlegroups.com> References: <1184739605.732844.321180@m37g2000prh.googlegroups.com> Message-ID: <1184842935.525390.307690@k79g2000hse.googlegroups.com> On Jul 18, 3:20 am, gravey wrote: > Hello. > > Apologies if this is a basic question, but I want to open a HTML > file from my local drive (is generated by another Python script) > in Internet Explorer. I've had a look at the webbrowser module and > this doesn't seem to be what I need. Any help much appreciated. check out the os module. os.startfile("your_htmlfile.html") should do it. From steven.klass at gmail.com Mon Jul 9 09:56:39 2007 From: steven.klass at gmail.com (rh0dium) Date: Mon, 09 Jul 2007 13:56:39 -0000 Subject: A clean way to program an interface In-Reply-To: <5feidnF3au460U1@mid.uni-berlin.de> References: <1183957402.819499.227350@o11g2000prd.googlegroups.com> <5feidnF3au460U1@mid.uni-berlin.de> Message-ID: <1183989399.366239.250850@g4g2000hsf.googlegroups.com> On Jul 9, 3:53 am, "Diez B. Roggisch" wrote: > THROW IT AWAY!!!! > > Seriously. That's one of the most convoluted, incomprehensible pieces of > python I've seen. Ever. > > All the sys._getframe()-stuff has to go. Really. There are about a dozen > pieces of code worldwide that are allowed to have that in them. Maybe two > dozen. > > And while I'm having difficulties grasping what you actually mean by " I > represent each function as a class or should I keep the code > I have below?", I've done my fair share of serial programming. And I would > say that having one class that exposes different methods for commands is > the way to go. > > But first - throw that code away. Fast. Faster. > > Diez Hi Diez, Totally understand your confusion with sys._getframe().f_code.co_name - that was borne out of the fact that I was creating a method for each serial function and it was repeating.. over and over.. So I got tired of changing the three items that differentiated each method so I simplified it a bit. Perhaps too much. So can I ask you to show or point me to a good interface example? I think we both can agree that fundamentally this is pretty simple but I want to do it right and an solid class example of interface programming would be nice. Thanks rh0dium From hniksic at xemacs.org Thu Jul 12 16:39:41 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 12 Jul 2007 22:39:41 +0200 Subject: os.wait() losing child? References: <4694903B.8000105@cosc.canterbury.ac.nz> <87fy3tg5zn.fsf@mulj.homelinux.net> Message-ID: <877ip5mk4y.fsf@mulj.homelinux.net> Nick Craig-Wood writes: >> This can still be a problem for applications that call wait in a >> dedicated thread, but the program can always ignore the processes >> it doesn't know anything about. > > Ignoring them isn't good enough because it means that the bit of > code which was waiting for that process to die with os.getpid() will > never get called, causing a deadlock in that bit of code. It won't deadlock, it will get an ECHILD or equivalent error because it's waiting for a PID that doesn't correspond to a running child process. I agree that this can be a problem if and when you use libraries that can call system. (In that case sleeping for SIGCHLD is probably a good solution.) > What is really required is a select() like interface to wait which > takes more than one pid. I don't think there is such a thing > though, so polling is your next best option. Except for the problems outlined in my previous message. And the fact that polling becomes very expensive (O(n) per check) once the number of processes becomes large. Unless one knows that a library can and does call system, wait is the preferred solution. From email at christoph-haas.de Sun Jul 22 12:34:54 2007 From: email at christoph-haas.de (Christoph Haas) Date: Sun, 22 Jul 2007 18:34:54 +0200 Subject: Lazy "for line in f" ? In-Reply-To: <1185120650.412694.314280@o61g2000hsh.googlegroups.com> References: <1185120650.412694.314280@o61g2000hsh.googlegroups.com> Message-ID: <20070722163454.GB27558@torf.workaround.org> On Sun, Jul 22, 2007 at 09:10:50AM -0700, Alexandre Ferrieux wrote: > I'm a total newbie in Python, but did give quite a try to the > documentation before coming here. > Sorry if I missed the obvious. > > The Tutorial says about the "for line in f" idiom that it is "space- > efficient". > Short of further explanation, I interpret this as "doesn't read the > whole file before spitting out lines". Correct. It reads one line at a time (as an "iterator") and returns it. > In other words, I would say "lazy". Which would be a Good Thing, a > much nicer idiom than the usual while loop calling readline()... The space-efficiency is similar. The faux pas would rather to read the whole file with readlines(). > But when I use it on the standard input, be it the tty or a pipe, it > seems to wait for EOF before yielding the first line. Standard input is a weird thing in Python. Try sending two EOFs (Ctrl-D). There is some internal magic with two loops checking for EOF. It's submitted as a bug report bug the developers denied a solution. Otherwise it's fine. In a pipe you shouldn't even notice. Christoph From Xin.Zheng at jpl.nasa.gov Fri Jul 13 19:52:09 2007 From: Xin.Zheng at jpl.nasa.gov (Jason Zheng) Date: Fri, 13 Jul 2007 16:52:09 -0700 Subject: os.wait() losing child? In-Reply-To: <87vecokzrp.fsf@mulj.homelinux.net> References: <4694903B.8000105@cosc.canterbury.ac.nz> <87bqehg5v1.fsf@mulj.homelinux.net> <873azsn6ca.fsf@mulj.homelinux.net> <87vecokzrp.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > Jason Zheng writes: >> I'm concerned about portability of my code. It will be run on >> multiple machines with mixed Python 2.4 and 2.5 environments. > > I don't think there is a really clean way to handle this. I think the following might just work, albeit not "clean": #!/usr/bin/python import os,subprocess from subprocess import Popen pids = {} counts = [0,0,0] def launch(i): p = Popen('sleep 1', shell=True, cwd='/home', stdout=file(os.devnull,'w')) pids[p.pid] = p, i if p in subprocess._active: subprocess._active.remove(p) print "Starting child process %d (%d)" % (i,p.pid) for i in xrange(3): launch(i) while (True): pid, ignored = os.wait() try: p, i = pids[pid] except KeyError: # not one of ours continue del pids[pid] counts[i] += 1 #terminate if count>10 if (counts[i]==10): print "Child Process %d terminated." % i if reduce(lambda x,y: x and (y>=10), counts): break continue print "Child Process %d terminated, restarting" % i launch(i) From aisaac at american.edu Sun Jul 1 22:23:10 2007 From: aisaac at american.edu (Alan Isaac) Date: Mon, 02 Jul 2007 02:23:10 GMT Subject: equality & comparison by default (was Re: Too many 'self' in python.That's a big flaw in this language.) In-Reply-To: References: <1182942154.185461.89620@e9g2000prf.googlegroups.com> <1i0cy8z.z94q5d1dxgexxN%aleax@mac.com> Message-ID: A.T.Hofkamp wrote: > Hmm, maybe numbers in sets are broken then? >>>>a = 12345 >>>>b = 12345 >>>>a == b > > True > >>>>a is b > > False > >>>>set([a,b]) > > set([12345]) > > Numbers and my Car2 objects behave the same w.r.t. '==' and 'is', yet I get a > set with 1 number, and a set with 2 cars. > Something is wrong here imho. > > The point I intended to make was that having a default __hash__ method on > objects give weird results that not everybody may be aware of. > In addition, to get useful behavior of objects in sets one should override > __hash__ anyway, so what is the point of having a default object.__hash__ ? The point is: let us have good default behavior. Generally, two equal numbers are two conceptual references to the same "thing". (Say, the Platonic form of the number.) So it is good that the hash value is determined by the number. Similarly for strings. Two equal numbers or strings are **also** identical, in the sense of having the same conceptual reference. In contrast, two "equal" cars are generally not identical in this sense. Of course you can make them so if you wish, but it is odd. So *nothing* is wrong here, imo. Btw: >>> a = 12 >>> b = 12 >>> a == b True >>> a is b True Cheers, Alan Isaac From cito at online.de Sun Jul 15 05:55:13 2007 From: cito at online.de (Christoph Zwerschke) Date: Sun, 15 Jul 2007 11:55:13 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: References: <1183863713.876365.111820@57g2000hsv.googlegroups.com> <1184239885.828717.271410@r34g2000hsd.googlegroups.com> <1184258925.321462.50270@k79g2000hse.googlegroups.com> <1184345588.791872.79010@d55g2000hsg.googlegroups.com> Message-ID: Christoph Zwerschke wrote: > Here is a simple solution, but it depends on the existence of the args > attribute that "will eventually be deprecated" according to the docs: Just found another amazingly simple solution that does neither use teh .args (docs: "will eventually be deprecated") attribute nor the dir() function (docs: "its detailed behavior may change across releases"). Instead it relies on the fact that the exception itselfs behaves like its args tuple (checked with Py 2.3, 2.4 and 2.5). As another twist, I set the wrapper exception module to the module of the original exception so that the output looks more like the output of the original exception (i.e. simply "UnicodeDecodeError" instead of "__main__.UnicodeDecodeError"). The code now looks like this: def PoliteException(e): E = e.__class__ class PoliteException(E): def __str__(self): return str(e) + ", sorry!" PoliteException.__name__ = E.__name__ PoliteException.__module__ = E.__module__ return PoliteException(*e) try: unicode('\xe4') except Exception, e: p = PoliteException(e) assert p.reason == e.reason raise p From xdicry at gmail.com Mon Jul 30 23:06:56 2007 From: xdicry at gmail.com (Evan) Date: Mon, 30 Jul 2007 20:06:56 -0700 Subject: Where can I get a complete user interface about pylibpcap? Message-ID: <1185851216.125392.27470@e9g2000prf.googlegroups.com> A web-link would do, becuase of I don't know how many parameters I need to use in function about pylibpcap. Or what kind of parameters I need to use/transfer? I'm very gratefully if you can help on this question. Thanks, From gabe at dragffy.com Fri Jul 27 04:45:30 2007 From: gabe at dragffy.com (Gabriel Dragffy) Date: Fri, 27 Jul 2007 09:45:30 +0100 Subject: slow emails Message-ID: <5A17E858-64B0-4D04-963B-CD1BC6C4F348@dragffy.com> Whenever I post to this list my email invariably takes ages to show up - perhaps two days or so. Often times not at all. Why is this? I am subscribed to Ubuntu mail list which is also high traffic, and my posts show up there within minutes. Thanks. Gabriel Dragffy gabe at dragffy.com From no at no.no Tue Jul 17 23:28:00 2007 From: no at no.no (Daniel) Date: Wed, 18 Jul 2007 06:28:00 +0300 Subject: accessing javascript variables within psp code References: <1184722167.222423.273040@z28g2000prd.googlegroups.com> Message-ID: On Wed, 18 Jul 2007 04:29:27 +0300, BAnderton wrote: > > Hello all, > > Question: Is there any way to access a javascript variable from > within psp code? > > > I'm aware of how to do the reverse of this (js_var='<%=psp_var%>'). > > > Here's a non-working example of what I'm trying to do: > > > - - - (begin example) - - - > > > function Test(txt) > { > a = confirm('Are you sure you want to delete '+txt+'?') > if (a) > { > //The problem is getting the value of js variable 'txt' recognized in > "psp space". > <% > os.remove( os.path.join(os.path.dirname(req.filename), '../notes/'+ > %>txt<%) ) > %> > > > } > } > > > - - - (end example) - - - > > FYI, I've already found a workaround for the above example (by placing > a "get" variable in the URL, reloading the page, and having psp check > for the existence of that variable before proceeding with deleting the > appropriate file) but I'd still like this general capability for > future projects. I've searched several forums, websites, etc. and > the > answer has aluded me for two days now. I'm new to apache, mod_python, > and javascript, so this may be ridiculously simple. > > Since this is my first post on google groups, I'd also appreciate any > helpful suggestions on how to best go about getting answers quickly > (so let me know if there's a more appropriate forum/method/etc.) > > Thanks for any help you can provide. > > > > (This is copied from a message I originally posted to the mod_python > group.) > Only with ajax. From steve at holdenweb.com Mon Jul 9 21:53:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 09 Jul 2007 21:53:28 -0400 Subject: highly einteractive editor for python In-Reply-To: References: Message-ID: Atul Bhingarde wrote: > Does anybody know an editor that facilitates, interactive python > development. Where GUI etc developed will be possible to see in real time > mode. > > Thanks > > Atul > > Wind IDE is great for debugging GUI-based programs - you can set breakpoints in event-handling routines and see them activate when your program responds to mouse clicks and so on. http://wingware.com/ 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 timr at probo.com Sat Jul 7 21:48:09 2007 From: timr at probo.com (Tim Roberts) Date: Sun, 08 Jul 2007 01:48:09 GMT Subject: what is wrong with that r"\" References: <27kr83lv67n38fmirvs5vvh5f80cr27joi@4ax.com> Message-ID: i3dmaster wrote: > >Then you can use other chars as the delimiter, r at a@b@ or r!a!b!, >etc... The import thing is so long as the interpreter doesn't get >confused on the data and the delimiter. That limits the number of valid delimiters to a relatively small set. You couldn't use any valid operator: x = r*a*b Is that a one character raw string appended to a string called "b", or is that to multiplications? >sed also allows for >arbitrary delimiters too as long as you maintain the integrity of the >original meaning... sed can do that because its commands are one character long. Whatever follows an "s" must a delimiter because it can't be anything else. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From p.lavarre at ieee.org Fri Jul 13 13:28:10 2007 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: Fri, 13 Jul 2007 10:28:10 -0700 Subject: CTypes FAQs - buffer memmove offsetof uchar ((void *) -1) etc. Message-ID: <1184347690.668221.166340@e16g2000pri.googlegroups.com> http://wiki.python.org/moin/ctypes now tries to answer: '''FAQ: How do I copy bytes to Python from a ctypes.Structure?''' '''FAQ: How do I copy bytes to a ctypes.Structure from Python?''' '''FAQ: Why should I fear using ctypes.memmove?''' '''FAQ: How do I change the byte length of a ctypes.Structure?''' '''FAQ: How do I say memcpy?''' '''FAQ: How do I say offsetof?''' '''FAQ: How do I say uchar?''' '''FAQ: How do I say ((void *) -1)?''' '''FAQ: How do I contribute to this CTypes FAQ?''' '''FAQ: How do I learn Python CTypes, after learning C and Python?''' From nospam at williamsdurkin.co.uk Sun Jul 1 07:09:40 2007 From: nospam at williamsdurkin.co.uk (Martin Durkin) Date: 1 Jul 2007 11:09:40 GMT Subject: Reversing a string References: <1182997438.541012.54100@o61g2000hsh.googlegroups.com> Message-ID: Duncan Booth wrote in news:Xns996067AFF71DDduncanbooth at 127.0.0.1: > Martin Durkin wrote: > >>>>>> def rev(x): >>> mylist = [] >>> for char in x: >>> mylist.append(char) >>> mylist.reverse() >>> for letter in mylist: >>> print letter >>> >>> However, compare the incredible difference in clarity and elegance >>> between that and: >>> >>>> >>> print "\n".join("spam"[::-1]) >>> >> >> OK, maybe I'm missing the point here as I'm new to Python. The first >> one seems clearer to me. What am I missing? >> > I think all you are missing is familarity with Python, but I too don't > like one-liners simply for their own sake. > I guess that's it. The first one reads more like a textbook example which is about where I am at. Is there any speed benefit from the one liner? thanks Martin From ptmcg at austin.rr.com Tue Jul 10 15:01:56 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 10 Jul 2007 12:01:56 -0700 Subject: Need Help In-Reply-To: <1184081285.869000.75460@i38g2000prf.googlegroups.com> References: <1184081285.869000.75460@i38g2000prf.googlegroups.com> Message-ID: <1184094116.352709.101230@k79g2000hse.googlegroups.com> On Jul 10, 10:28 am, pycraze wrote: > Hi , > > I need some info about the following snippet . > > ----------------------------------------------------------- > protocol = 'NTLMSSP\000' #name > type = '\001\000' #type 1 > zeros1 = '\000\000' > > zeros2 = '\000\000\000\000\000\000\000\000\000' > zeros3 = '\000\000\000\000\000\000\000\000\000\000\000' > smthg1 = '0\000\000\000\000\000\000\000' # something with > chr(48) length? > smthg2 = '0\000\000\000' # something with > chr(48) lenght? > > msg1 = protocol + type + zeros1 + flags + zeros2 + zeros3 + > smthg1 + smthg2 > msg1 = base64.encodestring(msg1) > msg1 = string.replace(msg1, '\012', '') > ------------------------------------------------------- > > In the above code what does " > 000\000\000\000\000\000\000\000\000 " signify ? Which form of > representation is this ? > > This code is from the NTLM APS python code from sourceforge 0.98 > version . I think redoing this code using the struct module would make the behavior and intent clearer, rather than trying to encode binary data directly into strings. -- Paul From info at fabis-site.net Tue Jul 17 12:19:58 2007 From: info at fabis-site.net (Fabian Steiner) Date: Tue, 17 Jul 2007 18:19:58 +0200 Subject: chmod directories recursively Message-ID: Hello! As far as I can see os.chmod() doesn't adjust permissions on directories recusively. Is there any other possibility to achieve this aim except for calling os.system('chmod -R /dir') directly? Thanks, Fabian From bdesth.quelquechose at free.quelquepart.fr Sun Jul 15 18:51:23 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 16 Jul 2007 00:51:23 +0200 Subject: Class decorators do not inherit properly In-Reply-To: <4cTli.12068$ya1.11048@news02.roc.ny> References: <46972b93$0$11779$426a74cc@news.free.fr> <4cTli.12068$ya1.11048@news02.roc.ny> Message-ID: <469be6a2$0$23468$426a74cc@news.free.fr> Lee Harr a ?crit : >>>I think the term "class decorator" is going to eventually >>>mean something other than what you are doing here. I'd >>>avoid the term for now. >>> >>> >>>When you decorate a class method, >>>the function you use >>>needs to be defined before the method definition. >> >>FWIW, the term "class method" has a >>definite meaning in Python. > > > > Certainly. But "class decorator" is being introduced in > Python 3000 with PEP 3129: > http://www.python.org/dev/peps/pep-3129/ > Certainly. But [1] "class methods" have been introduced in Python 2.2 !-) [1] IIRC - please someone correct me if I'm wrong From nospam.themindstorm at gmail.com Thu Jul 26 15:47:24 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Thu, 26 Jul 2007 19:47:24 +0000 (UTC) Subject: removing items from a dictionary ? References: <46A8EFF5.4060600@mailbox.kun.nl> Message-ID: Stef Mientki wrote in news:46A8EFF5.4060600 at mailbox.kun.nl: > hello, > > I want to remove some items from a dictionary, > so I would expect this should work: > > Nets = {} > ... fill the dictionary Nets > > for net in Nets: > if net.upper() in Eagle_Power_Nets : > del Nets [ net ] > > > But it gives me > Message File Name Line Position > Traceback > ? D:\data_to_test\JALsPy\Eagle_import.py 380 > RuntimeError: dictionary changed size during iteration > > > [snip...] > > > thanks, > Stef Mientki I think that you need to find a different iteration condition. Using for n in dict will iterate using an iterator which doesn't support "parallel" deletions. bests, ./alex -- .w( the_mindstorm )p. From musiccomposition at gmail.com Mon Jul 2 21:40:46 2007 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 03 Jul 2007 01:40:46 -0000 Subject: The file executing Message-ID: <1183426846.550981.11910@m36g2000hse.googlegroups.com> How does one get the path to the file currently executing (not the cwd). Thank you From erik at myemma.com Mon Jul 30 17:40:25 2007 From: erik at myemma.com (Erik Jones) Date: Mon, 30 Jul 2007 16:40:25 -0500 Subject: yield keyword usage In-Reply-To: <1185830034.713489.174640@r34g2000hsd.googlegroups.com> References: <1185830034.713489.174640@r34g2000hsd.googlegroups.com> Message-ID: <3DF2F614-EC0A-47F4-B622-DDC1D58D865F@myemma.com> On Jul 30, 2007, at 4:13 PM, Ehsan wrote: > hi > coulde any one show me the usage of "yield" keyword specially in this > example: > > > """Fibonacci sequences using generators > > This program is part of "Dive Into Python", a free Python book for > experienced programmers. Visit http://diveintopython.org/ for the > latest version. > """ > > __author__ = "Mark Pilgrim (mark at diveintopython.org)" > __version__ = "$Revision: 1.2 $" > __date__ = "$Date: 2004/05/05 21:57:19 $" > __copyright__ = "Copyright (c) 2004 Mark Pilgrim" > __license__ = "Python" > > def fibonacci(max): > a, b = 0, 1 > while a < max: > yield a > a, b = b, a+b > > for n in fibonacci(1000): > print n, As in how it works? Sure, when you use the yield statement in a function or method you turn it into a generator method that can then be used for iteration. What happens is that when fibonacci(1000) is called in the for loop statement it executes up to the yield statement where it "yields" the then current value of a to the calling context at which point n in the for loop is bound to that value and the for loop executes one iteration. Upon the beginning of the for loop's next iteration the fibonacci function continues execution from the yield statment until it either reaches another yield statement or ends. In this case, since the yield occured in a loop, it will be the same yield statement at which point it will "yield" the new value of a. It should be obvious now that this whole process will repeat until the condition a < max is not longer true in the fibonacci function at which point the function will return without yielding a value and the main loop (for n in ...) will terminate. 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 kyosohma at gmail.com Wed Jul 25 12:16:26 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 25 Jul 2007 09:16:26 -0700 Subject: Reading files, splitting on a delimiter and newlines. In-Reply-To: <1185378363.166434.172190@r34g2000hsd.googlegroups.com> References: <1185378363.166434.172190@r34g2000hsd.googlegroups.com> Message-ID: <1185380186.215288.83990@b79g2000hse.googlegroups.com> On Jul 25, 10:46 am, chris... at gmail.com wrote: > Hello, > > I have a situation where I have a file that contains text similar to: > > myValue1 = contents of value1 > myValue2 = contents of value2 but > with a new line here > myValue3 = contents of value3 > > My first approach was to open the file, use readlines to split the > lines on the "=" delimiter into a key/value pair (to be stored in a > dict). > > After processing a couple files I noticed its possible that a newline > can be present in the value as shown in myValue2. > > In this case its not an option to say remove the newlines if its a > "multi line" value as the value data needs to stay intact. > > I'm a bit confused as how to go about getting this to work. > > Any suggestions on an approach would be greatly appreciated! I'm confused. You don't want the newline to be present, but you can't remove it because the data has to stay intact? If you don't want to change it, then what's the problem? Mike From willmaier at ml1.net Thu Jul 19 17:56:32 2007 From: willmaier at ml1.net (Will Maier) Date: Thu, 19 Jul 2007 16:56:32 -0500 Subject: How to check if an item exist in a nested list In-Reply-To: <266557d0707191443h36eceddoca7bb626f0e0a022@mail.gmail.com> References: <266557d0707191443h36eceddoca7bb626f0e0a022@mail.gmail.com> Message-ID: <20070719215632.GD12728@lass.lfod.us> On Thu, Jul 19, 2007 at 02:43:13PM -0700, Arash Arfaee wrote: > One way is to check the length of each dimension. Does any body > know a simpler way? is there any way to check if "IndexError: list > index out of range" happened or going to happen and stop program > from terminating? If I understand what you're getting at, you could probably use a dictionary (indexed by (x, y) tuples), too. If you want to test if an item is in a list, use 'in': >>> dinner = ['spam', 'eggs', 'spam', 'spam'] >>> 'spam' in dinner True 'in' uses the __contains__() method implemented by lists. -- [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] From scott.daniels at acm.org Tue Jul 3 01:12:42 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 02 Jul 2007 22:12:42 -0700 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: <138jml0ldeucf32@corp.supernews.com> Peter J. Holzer wrote: > On 2007-06-22 20:33, James Harris wrote: >> I have a requirement to store timestamps in a database. Simple enough >> you might think but finding a suitably general format is not easy. The >> specifics are >> >> 1) subsecond resolution - milliseconds or, preferably, more detailed >> 2) not bounded by Unix timestamp 2038 limit >> 3) readable in Java >> 4) writable portably in Perl which seems to mean that 64-bit values >> are out >> 5) readable and writable in Python >> 6) storable in a free database - Postgresql/MySQL > > Stick to unix timestamps but store them as a double precision floating > point number. The 53 bit mantissa gives you currently a resolution of > about 200 ns, slowly deteriorating (you will hit ms resolution in about > 280,000 years, if I haven't miscalculated). Any language and database > should be able to handle double-precision FP numbers, so that's as > portable as it gets and conversion from/to system time should be > trivial. > > If you need to represent milliseconds exactly, you can just multiply the > timestamp with 1000 (and get java timestamps). > > hp TOPS-20 did an interesting format which suggest an interesting variant: Tops-20: 36-bit (the machine word size) fixed-bit representation of days since a given moment (the first Photographic plates of the sky). The "binary point" was at the middle of the word; the low order 18 bits were the time of day (GMT), the high-order 18 bits were the days-since date. Inspired format: Days since a some standard date (the TAI date may be a good such date) expressed as fixed point 64-bit (32-bit day part, 32-bit day-fraction part) or floating point (using Intel's double-precision, for example, gives you 26 bits each for day and day-fraction, though the binary point moves for particular stamps). Advantages of such a format: Using simple arithmetic for the difference between two such stamps is reasonably accurate even without knowing about when the leap seconds occur. Better resolution is available with leap-second aware software. A leap second affects the resolution only in intervals where there _are_ leap seconds, and ignoring them leaves you almost 5 digits of accuracy even when you naively ignore them. Disadvantages: time-of-day is not simple (but I maintain it shouldn't be). No external way to know if a stamp is leap-second aware or not; you'll just have to know for a whole group. Once you have done a naive difference, there is no way to correct it. --Scott David Daniels scott.daniels at acm.org From tjreedy at udel.edu Fri Jul 27 02:16:22 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Jul 2007 02:16:22 -0400 Subject: zip() function troubles References: <1185492336.850090.279190@b79g2000hse.googlegroups.com><7xir86wx0p.fsf@ruckus.brouhaha.com><1185499500.807041.60580@g4g2000hsf.googlegroups.com><7xzm1ieils.fsf@ruckus.brouhaha.com> <1185502539.598349.159330@l70g2000hse.googlegroups.com> Message-ID: "Istvan Albert" wrote in message news:1185502539.598349.159330 at l70g2000hse.googlegroups.com... || if you try it yourself you'll see that it is very easy to generate 10 | million tuples, No it is not on most machines. | on my system it takes 3 (!!!) seconds to do the following: | | size = 10**7 | data = [] | for i in range(10): | x = [ (0,1) ] * size x has 10**7 references (4 bytes each) to the same tuple. Use id() to check. 40 megs is manageable. | data.append( x ) | | Now it takes over two minutes to do this: | | size = 10**7 | a = [ 0 ] * size | b = zip(a,a) b has 40 megs that reference 10 meg *different* tuples. Each is 20 to 40, so 200-400 megs more. Try [(i,i) for i in xrange(5000000)] for comparison (it also makes 10000000 objects plus large list). | the only explanation I can come up with is that the internal | implementation of zip must have some flaws References are not objects. Terry Jan Reedy From ktglz at maine.rr.com Sun Jul 22 05:35:18 2007 From: ktglz at maine.rr.com (Evelyn Espinoza) Date: Sun, 22 Jul 2007 02:35:18 -0700 Subject: log Message-ID: <46A324D6.5050504@kchew.com> -------------- next part -------------- A non-text attachment was scrubbed... Name: log.pdf Type: application/pdf Size: 15721 bytes Desc: not available URL: From uymqlp502 at sneakemail.com Thu Jul 26 21:04:47 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Thu, 26 Jul 2007 18:04:47 -0700 Subject: automatic type conversion for comparison operators In-Reply-To: <1185492507.670637.294310@o61g2000hsh.googlegroups.com> References: <1185492177.836716.312390@q75g2000hsh.googlegroups.com> <1185492507.670637.294310@o61g2000hsh.googlegroups.com> Message-ID: <1185498287.179638.20390@w3g2000hsg.googlegroups.com> Dan Bishop wrote: > BTW, are you a former Pascal programmer? No. Why do you ask? [The code snippet I wrote was made up to get a point across. I did not actually use that function name in my code.] > > But Python > > somehow compares the function pointer with an integer without > > complaining. Unless there is a darn good reason for allowing > > comparisons of this type (and I can't think of one), I think > > Python should flag this as an Exception. > > IIRC, the reason is for backwards compatibility with a long-obsolete > version of Python in which it wasn't possible for __cmp__ to throw an > exception. That's not darn good, so this behavior is already slated > for removal in version 3.0. That's good to know. Thanks. From nospam.themindstorm at gmail.com Thu Jul 26 07:29:55 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Thu, 26 Jul 2007 11:29:55 +0000 (UTC) Subject: os.path.walk usage on WinXP References: Message-ID: Alex Popescu wrote in news:Xns997991CDF7710themindstorm at 80.91.229.5: > Hi all! > > I am trying to use the os.path.walk function, but I am getting a weird > error: > > def _walk(dir_name): > def selector(arg, dirname, fnames): > print "selector" > > os.path.walk(dir_name, selector, None) > > File "C:\zengarden\python\python25\lib\ntpath.py", line 325, in walk > names = os.listdir(top) > TypeError: coercing to Unicode: need string or buffer, list found > > After searching through the documentation the only thing that I've > found is the comment on os.listdir(path): > > [quote] > Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a > Unicode object, the result will be a list of Unicode objects. > [/quote] > > Unfortunately, I have no idea what to do next. > > TIA, > ./alex > -- > .w( the_mindstorm )p. > Apologies to everyone for the noise: the dir_name param proved to be a list and not a string as expected. ./alex -- .w( the_mindstorm )p. From jefishman at gmail.com Wed Jul 11 22:49:02 2007 From: jefishman at gmail.com (anethema) Date: Thu, 12 Jul 2007 02:49:02 -0000 Subject: lists and dictionaries In-Reply-To: <1184184582.330491.326600@e9g2000prf.googlegroups.com> References: <1184184582.330491.326600@e9g2000prf.googlegroups.com> Message-ID: <1184208542.948772.50700@w3g2000hsg.googlegroups.com> > li = [ {'index': 0, 'transport': 'udp', 'service_domain': > 'dp0.example.com'}, > {'index': 1, 'transport': 'udp', 'service_domain': > 'dp1.example.com'}, > {'index': 0, 'transport': 'tcp', 'service_domain': > 'dp0.example.com'}, > {'index': 1, 'transport': 'tcp', 'service_domain': > 'dp1.example.com'}] I like this solution: [{ 'transports' : [d['transport'] for d in li if d['service_domain'] == dom], 'service_domain': dom, } for dom in set(d2['service_domain'] for d2 in li)] merely because it takes one line. Humorously enough, it appears to be twice as efficient, at least when profiled on my computer, if speed is important in this problem. Not that this is the best way to do it either. Anyway, since the generator expression isn't very clear: def indexBasedToSDBased(li): newli = [] # For each service domain in the set read from the original list for sdom in set(d['service_domain'] for d in li): # Append a new dictionary mapping all transports for this domain newli.append({ 'service_domain': sdom, 'transports': [d['transport'] for d in li if d['service_domain'] == sdom] }) return newli (which is slower than the one-line generator :-D I love generator expressions) - Jeremy From deets at nospam.web.de Tue Jul 3 05:05:08 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 03 Jul 2007 11:05:08 +0200 Subject: try/finally in threads References: <1183430999.552755.83550@57g2000hsv.googlegroups.com> Message-ID: <5euhq4F3aje0iU1@mid.uni-berlin.de> George Sakkis wrote: > I posted this on the Pyro list but I'm not sure if it's related > specifically to Pyro. The "finally" clause below is not executed when > f() runs on on a (daemon) thread and the program exits. DAEMON here is > a global Pyro.code.Daemon instance. > > def f(): > try: DAEMON.requestLoop() > finally: > # nothing is printed if f() runs in a thread > print "i am here!!" > DAEMON.shutdown() > print "i am over!!" > > Is "finally" not guaranteed to be executed in a non-main thread or is > there something else going on ? Well, that's pretty much the idea behind daemon threads - that they are terminated immediately. If it were otherwise, a little endless-loop in that finally-statement of yours would cause the program termination to hang endlessly. Diez From cam.ac.uk at mh391.invalid Mon Jul 2 16:23:38 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 02 Jul 2007 21:23:38 +0100 Subject: Python compilation ?? In-Reply-To: References: Message-ID: Steve Holden wrote: > Evan Klitzke wrote: >> On 7/2/07, Cathy Murphy wrote: >>> Is python a compiler language or interpreted language. If it is >>> interpreter >>> , then why do we have to compile it? >> >> It's an interpreted language. It is compiled into bytecode (not >> machine code) the first time a script is run to speed up subsequent >> executions of a script. >> > While the flavor of this answer is correct, in strict point of fact > Python *doesn't* compile the scripts it executes, only the modules that > are imported. I think you mean that CPython doesn't save the results of the compilation of a script. The scripts are compiled every time they are run, as you go on to say. -- Michael Hoffman From dev-random at arcor.de Thu Jul 19 02:39:38 2007 From: dev-random at arcor.de (Lutz Horn) Date: Thu, 19 Jul 2007 08:39:38 +0200 Subject: CSV Issues References: <1184821164.289156.201060@z24g2000prh.googlegroups.com> Message-ID: Hi, On Thu, 19 Jul 2007 06:59:24 +0200, Rohan wrote: > When I run the script for the second time after a certain period of > time the results should appear next to the results of the last run, > I'm unable to make a new column when the script is run after the first > time. > Ideally I would like to have an output which looks like this. > 1/20 1/27 > we.py we.py > gh.py gj.py <- Indicating tht the file has changed > fg.py fg.py Try something like this: >>> import csv >>> f = open("/tmp/data.csv", "rb") >>> reader = csv.reader(f) >>> headings = reader.next() >>> headings ['1/20'] >>> rows = [] >>> for row in reader: ... rows.append(row) ... >>> rows [['we.py'], ['gh.py'], ['fg.py']] >>> f.close() >>> headings.append("1/27") >>> rows[0].append("we.py") >>> rows[1].append("gj.py") >>> rows[2].append("fg.py") >>> f = open("/tmp/data.csv", "wb") >>> writer = csv.writer(f) >>> writer.writerow(headings) >>> writer.writerows(rows) >>> f.close() Regards Lutz From robinsiebler at gmail.com Fri Jul 20 15:47:56 2007 From: robinsiebler at gmail.com (robinsiebler at gmail.com) Date: Fri, 20 Jul 2007 12:47:56 -0700 Subject: Weird errors when trying to access a dictionary key In-Reply-To: <1184959634.927653.158530@i13g2000prf.googlegroups.com> References: <1184956573.702959.96400@d30g2000prg.googlegroups.com> <1184959634.927653.158530@i13g2000prf.googlegroups.com> Message-ID: <1184960876.686411.124970@x40g2000prg.googlegroups.com> Ignore my previous response. :p I figured out what my problem was. I had [song].keys() when I really meant song.keys() and really needed str(song.keys()). I just got a little too bracket happy. :p From paltman at gmail.com Fri Jul 20 23:22:07 2007 From: paltman at gmail.com (Patrick Altman) Date: Sat, 21 Jul 2007 03:22:07 -0000 Subject: Python in Nashville Message-ID: <1184988127.644107.64420@22g2000hsm.googlegroups.com> Anyone on this group writing Python code in Nashville, TN? From martin at v.loewis.de Tue Jul 3 01:57:08 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 03 Jul 2007 07:57:08 +0200 Subject: object references/memory access In-Reply-To: <1183417108.245203.158830@x35g2000prf.googlegroups.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1183407411.397142.304790@e16g2000pri.googlegroups.com> <1183417108.245203.158830@x35g2000prf.googlegroups.com> Message-ID: <4689e535$0$23896$9b622d9e@news.freenet.de> >>> I have found the stop-and-go between two processes on the same machine >>> leads to very poor throughput. By stop-and-go, I mean the producer and >>> consumer are constantly getting on and off of the CPU since the pipe >>> gets full (or empty for consumer). Note that a producer can't run at >>> its top speed as the scheduler will pull it out since it's output pipe >>> got filled up. > > On a single core CPU when only one process can be running, the > producer must get off the CPU so that the consumer may start the > draining process. It's still not clear why you say that the producer can run "at its top speed". You seem to be suggesting that in such a setup, the CPU would be idle, i.e. not 100% loaded. Assuming that the consumer won't block for something else, then both processes will run at their "top speed". Of course, for two processes running at a single CPU, the top speed won't be the MIPs of a single processor, as they have to share the CPU. So when you say it leads to very poor throughput, I ask: compared to what alternative? Regards, Martin From johnmfisher at comcast.net Fri Jul 20 20:59:30 2007 From: johnmfisher at comcast.net (John Fisher) Date: Fri, 20 Jul 2007 17:59:30 -0700 Subject: converting 64-bit fixed-point to float Message-ID: <1i1k9cc.1hyy4zm1ybovgwN%johnmfisher@comcast.net> Hi Group, troubles with converting signed 32.32, little-endian, 2's complement back to floating point. I have been trying to brew it myself. I am running Python 2.5 on a Mac. Here is the C-code I have been trying to leverage: double FPuint8ArrayToFPDouble(uint8 *buffer, int startIndex) { uint32 resultDec = 0; uint32 resultWh = 0; int i; for(i = 0; i < 4; i++) { resultDec += (uint32)buffer[startIndex + i] * pow(2, (i*8)); resultWh += (uint32)buffer[startIndex + i + 4] * pow(2, (i*8)); } return ( (double)((int)resultWh) + (double)(resultDec)/4294967296.0 ); } Here is my version in Python, with some test code built in: from ctypes import * def conv64(input): input1=[0]*8 input1[0]=c_ushort(input[0]) input1[1]=c_ushort(input[1]) input1[2]=c_ushort(input[2]) input1[3]=c_ushort(input[3]) input1[4]=c_ushort(input[4]) input1[5]=c_ushort(input[5]) input1[6]=c_ushort(input[6]) input1[7]=c_ushort(input[7]) #print input1[0].value, input1[1].value,input1[2].value,input1[3].value #print input1[4].value,input1[5].value,input1[6].value,input1[7].value #print resultDec=c_ulong(0) resultWh=c_ulong(0) for i in range(4): dec_c=c_ulong(input1[i].value) Wh_c=c_ulong(input1[i+4].value) resultDec.value=resultDec.value+dec_c.value*2**(i*8) resultWh.value=resultWh.value+Wh_c.value*2**(i*8) conval=float(int(resultWh.value))+float(resultDec.value)/4294967296.0 #print conval return conval #tabs got messed up bringing this into MacSoup #these are 64-bit fixed point format (signed 32.32, little-endian, 2's complement) #should be -1 conv64_0=[0, 0, 0, 255, 255, 255, 255, 255] #should be 0 conv64_1=[0, 0, 0, 0, 0, 0, 0, 0] #should be 0.20000 conv64_1_2=[51, 51, 51, 51, 0, 0, 0, 0] #should be 1 conv64_2=[0, 0, 0, 0, 1, 0, 0, 0] #should be 2 conv64_3=[0, 0, 0, 0, 2, 0, 0, 0] #should be 298.15 conv64_4=[102, 102, 102, 38, 42, 1, 0, 0] #should be -0.2 conv64_5=[205,204,204,204,255,255,255,255] output0=conv64(conv64_0) print "output should be -1 is "+str(output0) output1=conv64(conv64_1) print "output should be 0 is "+str(output1) output1_2=conv64(conv64_1_2) print "output should be 0.2 is "+str(output1_2) output2=conv64(conv64_2) print "output should be 1 is "+str(output2) output3=conv64(conv64_3) print "output should be 2 is "+str(output3) output4=conv64(conv64_4) print "output should be 298.15 is "+str(output4) output5=conv64(conv64_5) print "output should be -0.2 is "+str(output5) Finally, here is the output I get from my code: >>> output should be -1 is 4294967296.0 output should be 0 is 0.0 output should be 0.2 is 0.199999999953 output should be 1 is 1.0 output should be 2 is 2.0 output should be 298.15 is 298.15 output should be -0.2 is 4294967295.8 Thanks for any light you can shed on my ignorance. wave_man From aboudouvas at panafonet.gr Mon Jul 30 11:42:08 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Mon, 30 Jul 2007 08:42:08 -0700 Subject: Replacing overloaded functions with closures. In-Reply-To: References: <1185807536.021216.278500@22g2000hsm.googlegroups.com> Message-ID: <1185810128.237758.17550@k79g2000hse.googlegroups.com> > The closures discussed in the article are not a solution for > function overloading. They are a solution for function > composition. Hmmm.... > > Python generally has no need for function name overloading--if > you really want it you must do it manually using runtime type > checking. > > def func(obj): > if isinstance(obj, bool): > return not obj > elif isinstance(obj, int): > return obj * 2 > elif isinstance(obj, basestring): > return obj + obj > else: > raise NotImplementedError('type %r not supported' % type(obj)) I have already come up with that solution but i was a little excited from that article that i can do the same thing with closures...And get rid of the isinstance commands. > I'm not sure what the author was getting at, exactly. May be that point confused me too! Thanks Neil! From hniksic at xemacs.org Mon Jul 9 09:41:30 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 09 Jul 2007 15:41:30 +0200 Subject: Per thread data References: <469230a0$0$5856$da0feed9@news.zen.co.uk> Message-ID: <87ps311yph.fsf@mulj.homelinux.net> Will McGugan writes: > Is there a canonical way of storing per-thread data in Python? mydata = threading.local() mydata.x = 1 ... http://docs.python.org/lib/module-threading.html From steve at REMOVE.THIS.cybersource.com.au Fri Jul 27 20:43:17 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Jul 2007 10:43:17 +1000 Subject: removing items from a dictionary ? References: <46a8f836$0$28175$9a622dc7@news.kpnplanet.nl> Message-ID: On Thu, 26 Jul 2007 21:38:31 +0200, martyw wrote: > Remoing elements from a dict is done with del, try this; > >>> d = {'a' : 1,'b' : 2} > >>> del d['a'] > >>> print d > {'b': 2} > >>> > > maybe you can post a working snippet to demonstrate your problem Wow. This wins my award for the least helpful, while still being technically correct, reply ever. Did you even read the Original Poster's post? He already knows that you delete items from a dictionary with del, and he posted code and the traceback he gets when he runs it. -- Steven. From zyzhu2000 at gmail.com Tue Jul 31 11:56:09 2007 From: zyzhu2000 at gmail.com (beginner) Date: Tue, 31 Jul 2007 15:56:09 -0000 Subject: What is the "functional" way of doing this? In-Reply-To: <1185835690.530367.66600@m37g2000prh.googlegroups.com> References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> Message-ID: <1185897369.881599.205260@x35g2000prf.googlegroups.com> On Jul 30, 5:48 pm, beginner wrote: > 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. > > Thanks, > beginner I see. It is interesting (and not surprisingly) that recursion or yield are required. Thanks for everyone's help. From jeff at jmcneil.net Thu Jul 5 14:34:24 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 5 Jul 2007 14:34:24 -0400 Subject: SMTP server w/o using Twisted framework In-Reply-To: <1183659790.338100.199900@g4g2000hsf.googlegroups.com> References: <1183659790.338100.199900@g4g2000hsf.googlegroups.com> Message-ID: <82d28c40707051134q5c32a13br33f38a2520129c16@mail.gmail.com> If you just want to send mail, you should be able to use the standard smtplib module (http://docs.python.org/lib/module-smtplib.html). If your recipients are on the Internet, you would need to handle MX resolution yourself. I know you said you want to avoid a relay server, but it's probably the best bet unless you control the SMTP infrastructure or are simply sending messages locally. Otherwise, you'll probably need to also implement queuing and retry logic (depending on your requirements). There are also some warning lights that may go off and flag your mail as spam if you're using a method like that... -Jeff On 7/5/07, _spitFIRE wrote: > Is it possible to run a SMTP server that sends mail to recipients > using standard libraries, without using twisted framework, and also > without using any relay server? > > -- > http://mail.python.org/mailman/listinfo/python-list > From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 13 04:04:35 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 13 Jul 2007 10:04:35 +0200 Subject: How to create new files? In-Reply-To: <1184274877.612434.26870@k79g2000hse.googlegroups.com> References: <1184274877.612434.26870@k79g2000hse.googlegroups.com> Message-ID: <469731ea$0$18333$426a74cc@news.free.fr> Robert Dailey a ?crit : > Hi, > > I'm trying to create a Python equivalent of the C++ "ifstream" class, > with slight behavior changes. > > Basically, I want to have a "filestream" object that will allow you to > overload the '<<' and '>>' operators to stream out and stream in data, > respectively. So far this is what I have: > > class filestream: class Filestream(object): > def __init__( self, filename ): > self.m_file = open( filename, "rwb" ) You don't need this C++ 'm_' prefix here - since the use of self is mandatory, it's already quite clear that it's an attribute. > # def __del__( self ): > # self.m_file.close() > > def __lshift__( self, data ): > self.m_file.write( data ) > > def __rshift__( self, data ): > self.m_file.read( data ) > > > So far, I've found that unlike with the C++ version of fopen(), the > Python 'open()' call does not create the file for you when opened > using the mode 'w'. It does. But you're not using 'w', but 'rw'. > I get an exception saying that the file doesn't > exist. Which is what happens when trying to open an inexistant file in read mode. > I expected it would create the file for me. Is there a way to > make open() create the file if it doesn't exist yes : open it in write mode. def __init__( self, filename ): try: self._file = open( filename, "rwb" ) except IOError: # looks like filename doesn't exist f = open(filename, 'w') f.close() self._file = open( filename, "rwb" ) Or you can first test with os.path.exists: def __init__( self, filename ): if not os.path.exists(filename): # looks like filename doesn't exist f = open(filename, 'w') f.close() self._file = open( filename, "rwb" ) HTH From zyzhu2000 at gmail.com Tue Jul 31 23:53:11 2007 From: zyzhu2000 at gmail.com (beginner) Date: Tue, 31 Jul 2007 20:53:11 -0700 Subject: Python end of file marker similar to perl's __END__ Message-ID: <1185940391.135261.130950@i38g2000prf.googlegroups.com> 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 From arkanes at gmail.com Fri Jul 27 12:02:37 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 27 Jul 2007 11:02:37 -0500 Subject: zip() function troubles In-Reply-To: <1185542664.266274.72370@w3g2000hsg.googlegroups.com> References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> <1185502539.598349.159330@l70g2000hse.googlegroups.com> <1185542664.266274.72370@w3g2000hsg.googlegroups.com> Message-ID: <4866bea60707270902o3675964cye0c82065da16eda7@mail.gmail.com> On 7/27/07, Istvan Albert wrote: > On Jul 27, 2:16 am, "Terry Reedy" wrote: > > > References are not objects. > > yes this a valid objection, > > but in all fairness the example in the original post operates on > comparably sized objects and also exhibited unexpected performance > degradation > > as it turns out the garbage collection is the culprit, I never used to > have to care about gc (and that's great!), but now that I'm that I'm > shuffling 1Gb chunks I have to be more careful. > You might be interested in the gc.set_threshold function. From http Mon Jul 2 22:53:10 2007 From: http (Paul Rubin) Date: 02 Jul 2007 19:53:10 -0700 Subject: Tiny/small/minimalist Python? References: <1183332951.122782.212720@o11g2000prd.googlegroups.com> <7xved3satm.fsf@ruckus.brouhaha.com> <1183389420.175712.59460@z28g2000prd.googlegroups.com> <7xmyyeizf8.fsf@ruckus.brouhaha.com> <468997c7$0$327$e4fe514c@news.xs4all.nl> Message-ID: <7xir9219m1.fsf@ruckus.brouhaha.com> Irmen de Jong writes: > Back in the days my port of Python to the Commodore Amiga machine ran > quite comfortably on a 50 mhz CPU with 4 Mb of RAM. (ok ok it was > Python 1.5.2, that has to be said). Even that sounds way too slow. Kyoto Common Lisp started in a few seconds on a Microvax-class machine, and an Alpha running Vax emulation should be at least as fast as that. Python shouldn't have especially worse startup overhead than KCL unless it's doing something silly. I'd try running Python under a profiler and figure out what's slowing it down. I don't understand the point of developing something in Lua on a Unix system. Lua is a cute scripting language that's easier to embed and sandbox than Python and is smaller, but the language itself is not nearly as nice to code in. I suggested Lua because I was imagining some kind of memory-limited embedded application that needed a lightweight extension language without too much of an OS interface, and Lua is good for that. Using it to write a compiler sounds masochistic. If there's an obstacle to using Python, I'd even consider using KCL (or its current incarnation), which has its own compiler (compiles Lisp to C code) among other things. It does need several MB of memory. From pyro-users-bounces at pyrorobotics.org Tue Jul 10 05:23:45 2007 From: pyro-users-bounces at pyrorobotics.org (pyro-users-bounces at pyrorobotics.org) Date: Tue, 10 Jul 2007 05:23:45 -0400 Subject: Your message to Pyro-users awaits moderator approval Message-ID: Your mail to 'Pyro-users' with the subject test 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://emergent.brynmawr.edu/mailman/confirm/pyro-users/b516bf2af8963d4ecb9bf5598ad61f36f94235f3 From bj_666 at gmx.net Wed Jul 4 10:00:50 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Jul 2007 14:00:50 GMT Subject: ignoring a part of returned tuples References: <1183536536.324939.236910@c77g2000hse.googlegroups.com> <468b5a9d$0$2228$426a74cc@news.free.fr> <1183551901.590528.225940@n2g2000hse.googlegroups.com> Message-ID: <5f1ngiF3a62csU2@mid.uni-berlin.de> On Wed, 04 Jul 2007 05:25:01 -0700, noamtm wrote: > On Jul 4, 11:29 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > >> A common idiom is to use '_' for unused values, ie: >> >> for (dirpath, _, filenames) in os.walk(...): > > That's what I need - this avoids PyLint telling me that I have an > unused variable, and also makes it clear that this value is not used. Pylint also "allows" the name `dummy` without complaining. That makes it even clearer and doesn't clash with the meaning of `_` when `gettext` is used. It's possible to configure many checks in Pylint. For this check it's possible to give a regular expression for names you don't care if they are unused. Ciao, Marc 'BlackJack' Rintsch From stefan.behnel-n05pAM at web.de Fri Jul 27 05:10:33 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 27 Jul 2007 11:10:33 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? In-Reply-To: <2T49f13tIf2oNv8%stesch@parsec.no-spoon.de> References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> <0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de> <5gtjeeF3i0lfsU2@mid.uni-berlin.de> <2T49f13tIf2oNv8%stesch@parsec.no-spoon.de> Message-ID: <46A9B689.7020508@web.de> Stefan Scholl schrieb: > Marc 'BlackJack' Rintsch wrote: >> On Fri, 27 Jul 2007 06:47:48 +0200, Stefan Scholl wrote: >> >>> Chris Mellon wrote: >>>> XML is not a string. It's a specific type of bytestream. If you want >>>> to work with XML, then generate well-formed XML in the correct >>>> encoding. There's no reason you should have an XML document (as >>>> opposed to values extracted from that document) in unicode objects at >>>> all. >>> The affected method in xml.sax is called parseString() >> Exactly. It's *not* called `parseUnicode()`. > > Semantics. > > >>> u"".__class__.__base__ > > >>> "".__class__.__base__ > > And it's not called "parseBasestring" either. Stefan From sjdevnull at yahoo.com Thu Jul 5 10:46:39 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Thu, 05 Jul 2007 07:46:39 -0700 Subject: The best platform and editor for Python In-Reply-To: <1183630730.251890.238900@m36g2000hse.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> Message-ID: <1183646799.400176.144570@k79g2000hse.googlegroups.com> Kay Schluehr wrote: > On Jul 3, 8:12 pm, cla... at lairds.us (Cameron Laird) wrote: > > > Python is simply easier than C++; you might > > well find that a debugger, for example, doesn't feel as essential > > as it is for you with C++. > > That's what I love most about the Python community. Whenever there is > just a non-standard, platform-dependent or crappy implementation of a > feature you get told that you don't need it. A fairly nice debugger is standard and built-in to the regular Python distribution on all platforms. But 95% of what a debugger is used for IME is getting a stack trace-- in Python (or Java or Ruby or most modern languages) you get that automatically, and the debugger is nowhere near as useful as it is in C or C++. From picioslug at gmail.com Tue Jul 3 10:08:19 2007 From: picioslug at gmail.com (Picio) Date: Tue, 03 Jul 2007 14:08:19 -0000 Subject: MySQL -->Python-->XML for JSviz Message-ID: <1183471699.214828.251570@w5g2000hsg.googlegroups.com> Hello all, I need some advice to choose an xml generator for jsviz a tool in javascript to create some wonderful graphs (SnowFlake or Force directed). Starting from a SQL table (mysql) I need to create a XML file with a structure like this: Where nodes attributes are the MySQL table fields (the PK will be the attribute). I know there are a lot of good tools to do this in pyhton (some maybe is already shipped with pyton itself), but since I need a lot of flexibility for the future I'd like to use an Object relational mapper like SQLAlchemy or SQLObject todo the job. When I say flexibility, I have in mind a solution to have multiple formats coming outside of the ORM: json, csv, plain text etc... Am I wrong? Can someone advice something? From python at jayloden.com Sat Jul 14 11:31:30 2007 From: python at jayloden.com (Jay Loden) Date: Sat, 14 Jul 2007 11:31:30 -0400 Subject: Access Denied while trying to delete file from python script In-Reply-To: <1184420358.061236.150000@22g2000hsm.googlegroups.com> References: <1184402387.265806.322680@z28g2000prd.googlegroups.com> <1184420358.061236.150000@22g2000hsm.googlegroups.com> Message-ID: <4698EC52.70909@jayloden.com> kyosohma at gmail.com wrote: > On Jul 14, 3:39 am, "Viewer T." wrote: >> I am trying to write a script that deletes certain files based on >> certain criteria. >> >> What I am trying to do is to automate the process of deleting certain >> malware files that disguise themselves as system files and hidden >> files. When I use os.remove() after importing the os module is raises >> a Windows Error: Access denied probably because the files have >> disguised themselves as system files. Is there anway to get adequate >> privileges under windows to be able to delete system files from within >> a python script. I know it is probably a windows security feature but >> is there anyway to gain such privileges. > > You'll need to use the PyWin32 package (AKA win32all). There's a > win32security module. These links might help: > > http://mail.python.org/pipermail/python-list/2006-February/367441.html > http://www.thescripts.com/forum/thread28850.html > http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/pywin32/Windows_NT_Files_.2d.2d_Locking.html > > Sometimes you can beat windows over the head using its own delete > commands: > > os.system('DEL /F /S /Q "%s"' % item) > os.system(r'RD /S /Q "%s"' % item) > > I know there's a cookbook recipe on it, but I can't seem to find it > right now. Hopefully this will help you some though. I think what you want is this one: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303343 I wrote/maintain an Win32 antivirus tool written in C and it uses the same Win32 functions to unset any hidden/system attributes on files before attempting to delete them. In the same vein, you'll find that some files are locked and unable to be deleted, so you're probably want to look into the following also: * killing processes to remove currently running files http://www.answermysearches.com/how-to-kill-a-process-by-name-in-python/57/ * scheduling files for removal on reboot using MoveFileEx (you'd have to use win32 extensions to access the MoveFileEx function) http://msdn2.microsoft.com/En-US/library/aa365240.aspx Hope that helps, -Jay From http Wed Jul 4 16:22:12 2007 From: http (Paul Rubin) Date: 04 Jul 2007 13:22:12 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> Message-ID: <7xzm2budfv.fsf@ruckus.brouhaha.com> John Nagle writes: > This has been tried. Original K&R C had non-enforced static typing. > All "struct" pointers were equivalent. It wasn't pretty. > > It takes strict programmer discipline to make non-enforced static > typing work. I've seen it work in an aerospace company, but the Python > crowd probably doesn't want that level of engineering discipline. I think even enforced static types wouldn't cure what I see as the looseness in Python. There is not enough composability of small snippets of code. For example, the "for" statement clobbers its index variable and then leaks it to the outside of the loop. That may be more of a culprit than dynamic types. Perl and C++ both fix this with syntax like for (my $i in ...) ... (perl) or for (int i = 0; i < n; i++) ... (C++, Java) making a temporary scope for the index variable. Python even leaks the index variable of list comprehensions (I've mostly stopped using them because of this), though that's a recognized wart and is due to be fixed. Python would be helped a lot by some way to introduce temporary scopes. We had some discussion of this recently, concluding that there should be a compiler warning message if a variable in a temporary scope shadows one from a surrounding scope. From steve at holdenweb.com Wed Jul 25 17:55:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Jul 2007 17:55:39 -0400 Subject: Why PHP is so much more popular for web-development In-Reply-To: <82d28c40707251158ibae2f9u70889f01ac45a9f6@mail.gmail.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <82d28c40707251158ibae2f9u70889f01ac45a9f6@mail.gmail.com> Message-ID: Jeff McNeil wrote: > Unfortunately, I also find that PHP programmers are usually more > plentiful than their Python counterparts. When thinking of staffing > an organization, it's common to target a skill set that's cheaper to > employ and easier to replace down the road if need be. > Right, that's why hospitals are replacing their surgeons with butchers. There are so many more of them available. It's only cutting meat, after all. > Also, larger hosting shops are hesitant to run things such as TG and > Rails that require an additional server process. The name of the game > is density. Sure, it may be easy to manage and run a TG project, but > it's a pain to set one up on a shared hosting server. > Virtualization will solve that problem. > Lastly, I personally think it has something to do with the fact that > so many of the popular, free, web applications are PHP based. It's > easy for the average Web Administrator to get started with your > standard PHP package. From there, picking up the language is the next > logical step. > There's some justice to 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 ironfroggy at gmail.com Wed Jul 18 08:44:18 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Wed, 18 Jul 2007 08:44:18 -0400 Subject: Charlotte Python Group Message-ID: <76fd5acf0707180544y497bfd42t6b699b8f62b6b4e5@mail.gmail.com> I am looking to start a meetup in or near Charlotte. I already have a couple people interested, and I see some folks subscribing to new python groups on meetup. If I can find a few more people, it could be worth it. Is anyone in the area and interested in a group? Anyone who might want to do a talk, about anything interesting? Does anyone have suggestions of a good place in Charlotte to meet, maybe at a cafe with enough room? I'm from up in the Kannapolis/Concord area myself, so I'm not familiar with many places in the city proper, but I see a few possibilities at Google Maps. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From cito at online.de Fri Jul 13 01:45:20 2007 From: cito at online.de (Christoph Zwerschke) Date: Fri, 13 Jul 2007 07:45:20 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: <1184258925.321462.50270@k79g2000hse.googlegroups.com> References: <1183863713.876365.111820@57g2000hsv.googlegroups.com> <1184239885.828717.271410@r34g2000hsd.googlegroups.com> <1184258925.321462.50270@k79g2000hse.googlegroups.com> Message-ID: samwyse wrote: > TypeError: __class__ must be set to a class > > Excpt ceratinly appears to be a class. Does anyone smarter than me > know what's going on here? Not that I want to appear smarter, but I think the problem here is that exceptions are new-style classes now, whereas Empty is an old-style class. But even if you define Empty as a new-style class, it will not work, you get: TypeError: __class__ assignment: only for heap types This tells us that we cannot change the attributes of a built-in exception. If it would be possible, I simply would have overridden the __str__ method of the original exception in the first place. -- Chris From bignose+hates-spam at benfinney.id.au Tue Jul 17 03:20:13 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 17 Jul 2007 17:20:13 +1000 Subject: how to find available classes in a file ? References: <2e302$469bf38f$d443bb3a$30036@news.speedlinq.nl> Message-ID: <873aznh4ya.fsf@benfinney.id.au> Stef Mientki writes: > I want to have a (dynamically) list of all classes defined in a py-file. > Is there a way of getting this list, without manually parsing the file ? >>> import random >>> for name in dir(random): ... obj = getattr(random, name) ... if isinstance(obj, type): ... print "%(name)s is a type" % locals() ... Random is a type SystemRandom is a type WichmannHill is a type _BuiltinMethodType is a type _MethodType is a type >>> And, since you asked for just getting the list, here's the list of names: >>> [name for (name, obj) in ... [(name, getattr(random, name)) for name in dir(random)] ... if isinstance(obj, type)] ['Random', 'SystemRandom', 'WichmannHill', '_BuiltinMethodType', '_MethodType'] Or the list of type objects themselves: >>> [obj for obj in ... [getattr(random, name) for name in dir(random)] ... if isinstance(obj, type)] [, , , , ] -- \ "Pinky, are you pondering what I'm pondering?" "Well, I think | `\ so, Brain, but I can't memorize a whole opera in Yiddish." -- | _o__) _Pinky and The Brain_ | Ben Finney From software at ginstrom.com Mon Jul 16 23:43:46 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Tue, 17 Jul 2007 12:43:46 +0900 Subject: testing with coverage.py problem In-Reply-To: References: Message-ID: <018e01c7c824$af1d4f60$0203a8c0@MOUSE> > On Behalf Of Piotr Hrebieniuk > I've spent few hours and found nothing, so here's my question: > How can i run tests wrote by myself on a module, using coverage.py ? > Let's assume i have a module mymod.py which i want to test > with tests from file mytest.py (i.e. class inherited from > unittest.TestCase). How to do that with coverage.py? Where i > should put the code that runs the tests? The easiest way is probably by using nose http://somethingaboutorange.com/mrl/projects/nose/ In particular, check out the "--with-coverage" flag. Regards, Ryan Ginstrom From samwyse at gmail.com Fri Jul 13 07:58:21 2007 From: samwyse at gmail.com (samwyse) Date: Fri, 13 Jul 2007 11:58:21 -0000 Subject: Assignments to __class_ broken in Python 2.5? In-Reply-To: <1184306170.262648.289910@22g2000hsm.googlegroups.com> References: <1183863713.876365.111820@57g2000hsv.googlegroups.com> <1184239885.828717.271410@r34g2000hsd.googlegroups.com> <1184258925.321462.50270@k79g2000hse.googlegroups.com> <1184306170.262648.289910@22g2000hsm.googlegroups.com> Message-ID: <1184327901.112991.33770@n60g2000hse.googlegroups.com> (Yes, I probably should have said CPython in my subject, not Python. Sorry.) On Jul 13, 12:56 am, samwyse wrote: > OK, in classobject.h, we find this: > > #define PyClass_Check(op) ((op)->ob_type == &PyClass_Type) > > That seems straightforward enough. And the relevant message appears > in classobject.c here: > > static int > instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v) > [...] > if (strcmp(sname, "__class__") == 0) { > if (v == NULL || !PyClass_Check(v)) { > PyErr_SetString(PyExc_TypeError, > "__class__ must be set to a class"); > return -1; > } > > Back in our test code, we got these: > > > Empty = > > Excpt = > > The first class (Empty) passes the PyClass_Check macro, the second one > (Excpt) evidently fails. I'll need to dig deeper. Meanwhile, I still > have to wonder why the code doesn't allow __class_ to be assigned a > type instead of a class. Why can't we do this in the C code (assuming > the appropriate PyType_Check macro): > > if (v == NULL || !(PyClass_Check(v) || PyType_Check(v))) { After a good night's sleep, I can see that Empty is a "real" class; i.e. its repr() is handled by class_repr() in classobject.c. Excpt, on the other hand, is a type; i.e. its repr is handled by type_repr() in typeobject.c. (You can tell because class_repr() returns a value formatted as "" whereas type_repr returns a value formatted as "<%s '%s.%s'>", where the first %s gets filled with either "type" or "class".) This is looking more and more like a failure to abide by PEP 252/253. I think that the patch is simple, but I'm unusre of the ramifications. I also haven't looked at the 2.4 source to see how things used to work. Still, I think that I've got a work-around for OP's problem, I just need to test it under both 2.4 and 2.5. From S.Mientki-nospam at mailbox.kun.nl Wed Jul 25 14:44:20 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 25 Jul 2007 20:44:20 +0200 Subject: wxGlade: Who knows how to drive this application? In-Reply-To: References: Message-ID: <73447$46a79894$d443bb3a$28145@news.speedlinq.nl> Roel Schroeven wrote: > Steve Holden schreef: >> I've been trying to use wxGlade recently and I am finding it something >> of a challenge. Is there any user who finds the user interface >> satisfactory and the operation of the program predictable? > > I haven't used it much, but it always seems to be a pain to use the > interface. I actually thought it was just me; I'm glad to see that at > least one other person has problems with it too. > count me too, I didn't even got it to work ;-) Stef From steve at holdenweb.com Wed Jul 11 21:36:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 11 Jul 2007 21:36:18 -0400 Subject: bool behavior in Python 3000? In-Reply-To: References: <5ficp9F3cram2U2@mid.individual.net><469472f4$0$1293$9b622d9e@news.freenet.de> Message-ID: Terry Reedy wrote: > "Ed Leafe" wrote in message > news:C5AEB4C0-273B-411F-B14E-2B45E0881549 at leafe.com... > | I think that the assignability to the names 'True' and 'False' is > | incorrect, or at the very least subject to all sorts of odd results. > > It is necessary for 2.x to not break older code. I believe they will > somehow be reserved, like None, in 3.0. > But of course None was assignable until (?) 2.3 and then became formally constant, so it was no longer possible to assign to it or even shadow it in a local namespace. So much for that kind of backward compatibility! 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_Dexter at msn.com Fri Jul 13 20:12:48 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Fri, 13 Jul 2007 17:12:48 -0700 Subject: Right tool and method to strip off html files (python, sed, awk?) In-Reply-To: <1184371665.105931.125000@r34g2000hsd.googlegroups.com> References: <1184353058.660535.140110@m3g2000hsh.googlegroups.com> <1184371665.105931.125000@r34g2000hsd.googlegroups.com> Message-ID: <1184371968.971633.251990@k79g2000hse.googlegroups.com> On Jul 13, 7:07 pm, "Eric_Dex... at msn.com" wrote: > On Jul 13, 1:57 pm, seb... at gmail.com wrote: > > > > > > > Hi, > > > I'm in the process of refactoring a lot of HTML documents and I'm > > using html tidy to do a part of this > > work. (clean up, change to xhtml and remove font and center tags) > > > Now, Tidy will just do a part of the work I need to > > do, I have to remove all the presentational tags and attributes from > > the pages (in other words rip off the pages) including the tables that > > are used for disposition of content (how to differentiate?). > > > I thought about doing that with python (for which I'm in process of > > learning), but maybe an other tool (like sed?) would be better suited > > for this job. > > > I kind of know generally what I need to do: > > > 1- Find all html files in the folders (sub-folders ...) > > 2- Do some file I/O and feed Sed or Python or what else with the file. > > 3- Apply recursively some regular expression on the file to do the > > things a want. (delete when it encounters certain tags, certain > > attributes) > > 4- Write the changed file, and go through all the files like that. > > > But I don't know how to do it for real, the syntax and everything. I > > also want to pick-up the tool that's the easiest for this job. I heard > > about BeautifulSoup and lxml for Python, but I don't know if those > > modules would help. > > > Now, I know I'm not a the best place to ask if python is the right > > choice (anyways even my little finger tells me it is), but if I can do > > the same thing more simply with another tool it would be good to know. > > > An other argument for the other tools is that I know how to use the > > find unix program to find the files and feed them to grep or sed, but > > I still don't know what's the syntax with python (fetch files, change > > them than write them) and I don't know if I should read the files and > > treat them as a whole or just line by line. Of course I could mix > > commands with some python, find command to my program's standard > > input, and my command's standard output to the original file. But I do > > I control STDIN and STDOUT with python? > > > Sorry if that's a lot of questions in one, and I will probably get a > > lot of RTFM (which I'm doing btw), but I feel I little lost in all > > that right now. > > > Any help would be really appreciated. > > Thanks > > You might find a text editor is the way to go.. you can use autoit > either through python or by itself to control the text editor you > use.. I just downloaded pspad and it looks like it will do that. It > may be a pain to script though. > > http://sourceforge.net/projects/dex-tracker/- Hide quoted text - > > - Show quoted text - let me add to that it may be a pain to script with autoit and I am not doing more of an example because it won't insert a textfile at a location like mdipad will. From brotherjenos at gmail.com Wed Jul 18 11:12:24 2007 From: brotherjenos at gmail.com (Walker Lindley) Date: Wed, 18 Jul 2007 08:12:24 -0700 Subject: Pickled objects over the network In-Reply-To: References: <9c8d48280707171457p4448fdf3of40562bf62a18fc6@mail.gmail.com> Message-ID: <9c8d48280707180812q4343bcbaodbc803e9c9a92acb@mail.gmail.com> Thanks for all the help, I tried sending the length and then the string and that appears to work, so I'll take a look at Pyro, too. -Walker On 7/18/07, Nick Craig-Wood wrote: > > Jean-Paul Calderone wrote: > > On Tue, 17 Jul 2007 14:57:16 -0700, Walker Lindley < > brotherjenos at gmail.com> wrote: > > >I'm working on a distributed computing program and need to send Python > > >objects over a TCP socket. > [snip] > > >Hopefully I'm doing something obviously wrong, but if anyone can help > based > > >on that description or if you need to see the source, please let me > know > > >(it's GPL'd). Thank you so much for any help. > > > > The obvious thing you're doing wrong is using pickle over a network. ;) > > > > http://jcalderone.livejournal.com/15864.html > > I'd say the obvious thing being done wrong is re-inventing the wheel. > Use pyro instead... > > http://pyro.sourceforge.net/ > > Pyro does use pickle to serialise objects by default. It can use XML > instead for an exploit free RPC at the cost of a bit of speed. > > http://pyro.sourceforge.net/manual/9-security.html#pickle > > -- > Nick Craig-Wood -- http://www.craig-wood.com/nick > -- > http://mail.python.org/mailman/listinfo/python-list > -- 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: From nicolasg at gmail.com Tue Jul 24 04:18:11 2007 From: nicolasg at gmail.com (NicolasG) Date: Tue, 24 Jul 2007 08:18:11 -0000 Subject: Where do they tech Python officialy ? In-Reply-To: <7xveca4ajp.fsf@ruckus.brouhaha.com> References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> Message-ID: <1185265091.276958.239910@r34g2000hsd.googlegroups.com> > If you have a good programming background in other languages, you > should easily be able to pick up Python by reading the manual. > Dear all, thank you for your info. I forgot to mention that I already know how to program in Python (basic), my knowledge derives from a very good level of C (University level) and I have use python to build some pages in Zope plus some minor programs I created.. 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. From tkondal at gmail.com Tue Jul 17 14:21:21 2007 From: tkondal at gmail.com (tkondal at gmail.com) Date: Tue, 17 Jul 2007 11:21:21 -0700 Subject: Deleting files and folders used by other processes on Windows Message-ID: <1184696481.970075.232530@m37g2000prh.googlegroups.com> Hi, I have been looking into making my file cleaning script more intelligent. The goal of the script is to delete everything on a drive except for a couple of folders which are skipped by the script. Recently, I noticed that some files where not being deleted because a process was using them. Is there a recipe (needs to run on Windows XP/ 2003) for doing the following (more specifically, I need a way to determine which process is holding a lock on my file): file=GetFilename(); bLock = IsThereAFileLockOnFile(file) If (bLock) { process = GetLockingProcess(file); TerminateProcess(process); } DeleteFile(file); Thanks. From jstroud at mbi.ucla.edu Tue Jul 24 17:31:34 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 24 Jul 2007 14:31:34 -0700 Subject: Cleaning up a string In-Reply-To: References: Message-ID: Peter Otten wrote: > unicode.translate() supports this kind of replacement... > and re.compile(...).sub() accepts a function: Thanks Peter! -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From samper.d at gmail.com Fri Jul 13 17:15:49 2007 From: samper.d at gmail.com (Dave Sampson) Date: Fri, 13 Jul 2007 17:15:49 -0400 Subject: Python Subprocess module Message-ID: <4697EB85.6070302@gmail.com> hey folks, A simple question hopefully. despite all my searching I have not found a satisfactory response. The goal. Interact with a command line program. Simple enough, but the key is INTERACT. I tried the shell and comand approaches but that initiates, it does not allow interaction with the programs. So then I went with Popen and such... which then led to the subprocess module. I can create the object and read a few lines of output. but if I go too far then the program hangs. the number of lines will differ depandening on many function including the format of an input file so I can;t hardcode how many lines to read. I want to read all of STDOUT without failing because I went out of range. next I want to read the final line of the output because it tells me what is required for the next line of input. I am supposed to be able to entre 'y' and return for the program to continue if I agree with what I see in the stdout. A problem exists though that I have tried 'y' 'y\n' 'y\r' and nothing seems to get the program going again for I still cant; read past the same point in the standard output. then I have to kill and start over. So the next approach included looking at Pexpect, which got realy confusing realy fast and despite running fedora core and python 2.4.4 I would like my application to be cross platform and there is no Pexpect for Windows That I can see. I have checked out many mailing lists and posts and tutorials but they all admit to not be samples of complex interactivity. I guess I am having that special case. ASPN Python cookbok provided some code for a new Popen Class that allows for interaction but I don't think I need to go that root.... I am essentialy trying to build and Python wrapper for a coomand line program that i want to build a GUI around. Any links or suggestions would be great. Unfortunaetly I don't understand that abstract concepts in the manual reference. I am fresh in the python world and find examples better than technical abstracts. Cheers From the.mindstorm.mailinglist at gmail.com Thu Jul 5 18:13:33 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Thu, 05 Jul 2007 15:13:33 -0700 Subject: The best platform and editor for Python In-Reply-To: <1183646799.400176.144570@k79g2000hse.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183646799.400176.144570@k79g2000hse.googlegroups.com> Message-ID: <1183673613.113448.75000@o61g2000hsh.googlegroups.com> On Jul 5, 5:46 pm, "sjdevn... at yahoo.com" wrote: > Kay Schluehr wrote: > > On Jul 3, 8:12 pm, cla... at lairds.us (Cameron Laird) wrote: > > > > Python is simply easier than C++; you might > > > well find that a debugger, for example, doesn't feel as essential > > > as it is for you with C++. > > > That's what I love most about the Python community. Whenever there is > > just a non-standard, platform-dependent or crappy implementation of a > > feature you get told that you don't need it. > > A fairly nice debugger is standard and built-in to the regular Python > distribution on all platforms. > > But 95% of what a debugger is used for IME is getting a stack trace-- > in Python (or Java or Ruby or most modern languages) you get that > automatically, and the debugger is nowhere near as useful as it is in > C or C++. I am a Python newbie, but unfortunately I don't agree with that. For me having a debugger helped understand very quickly the flow in the libraries for which otherwise I would have had to navigate through code (which once again is not always easy without a good IDE). But this is just a newbie opinion :-), ./alex -- .w( the_mindstorm )p. From mail at microcorp.co.za Fri Jul 20 03:32:17 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 20 Jul 2007 09:32:17 +0200 Subject: Pickled objects over the network References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com> Message-ID: <011401c7caa0$3e3e5900$03000080@hendrik> Walker Lindley wrote: >Right, I could use Pyro, but I don't need RPC, I just wanted an easy way to send objects across the network. I'm sure >both Pyro and Yami can do that and I may end up using one of them. For the initial version pickle will work because we >have the networking issues figured out with it, just not the security problem. So we may end up just sending strings back >and forth that will let us fill out an object's member variables on the other end. It's much less cool, but it seems like it'd >be more secure. > This passing of a pickled structure is so handy for simple things like lists of parameters, and so on, that I wonder if it would not be worth while to somehow beef up the security of the pickle stuff. One heretical way I can think of would involve strict "typing" at the receiving end - if you expect say a dict, then you should somehow specify that anything else should fail... as dict my_received_dict = cpickle.loads(data_from_network) or, better without a new "as" keyword: my_received_dict=cpickle.loads(data_from_network,type=dict) Is this at all feasible? - Hendrik From aisaac at american.edu Wed Jul 11 09:05:15 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 11 Jul 2007 13:05:15 GMT Subject: bool behavior in Python 3000? In-Reply-To: References: Message-ID: Since it is seemingly ignored in most of the comments on this thread, I just want to remind that PEP 285 http://www.python.org/dev/peps/pep-0285/ says this: In an ideal world, bool might be better implemented as a separate integer type that knows how to perform mixed-mode arithmetic. I mentioned Python 3000 since that is an opportunity for an ideal world. Cheers, Alan Isaac From jeffmess at gmail.com Fri Jul 27 07:55:16 2007 From: jeffmess at gmail.com (jeffmess at gmail.com) Date: Fri, 27 Jul 2007 11:55:16 -0000 Subject: <> vs != In-Reply-To: References: <8a6b8e350707261228x234b7da0g17d43736e45e67ca@mail.gmail.com> Message-ID: <1185537316.344728.265130@r34g2000hsd.googlegroups.com> On Jul 27, 1:08 pm, "Simon Brunning" wrote: > On 7/26/07, James Matthews wrote: > > > What is the difference between <> and != > > <> is deprecated, != isn't. Other than that, nothing AFAIK. > > -- > Cheers, > Simon B. > si... at brunningonline.nethttp://www.brunningonline.net/simon/blog/ > GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues I believe Guido doesn't like '<>' and decided to enforce != instead. Guess it's his language :). From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 27 06:00:24 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 27 Jul 2007 12:00:24 +0200 Subject: Factory pattern again In-Reply-To: References: Message-ID: <46a9c21f$0$18765$426a74cc@news.free.fr> Mike Howarth a ?crit : > Hi > > I was wondering whether anyone could help me, I'm pretty new to python > coming from a PHP background and I'm having a few products in getting my > head round how to write the factory pattern within python. > > I'm currently looking to try to return values from a db and load up the > relevant objects, values returned are product type (I,S) and product code > (123). > > At the moment I've adapted some code I've found illustrating the factory > method but ideally I would like to use the type to load up the relevant > object. > > Another issue I've found is that I don't seem to be able to access to the > price attribute of each of the object. I'm sure these are very > straightforward issues however I seem to have tied myself in knots over this > and could do with a fresh set of 'pythonic' eyes to help me out. > > registry = {} > > class MetaBase(type): > def __init__(cls, name, bases, dict): > registry[name] = cls > > class Product(object): > __metaclass__ = MetaBase > > class Item(Product): > def __init__(self, *args, **kw): > self.price = 1 > > class Set(Product): > def __init__(self, *args, **kw): > self.price = 2 > > def factory(kind, *args, **kw): > return registry[kind](*args, **kw) > > > item = registry['Item'] This returns the Item *class*, not an instance of... So the following: > print item.price cannot work, since price is an instance attribute, not a class attribute. What you want is: item = factory('Item') print item.price HTH From pepebuslo at gmail.com Sun Jul 29 15:40:28 2007 From: pepebuslo at gmail.com (pepebuslo at gmail.com) Date: Sun, 29 Jul 2007 12:40:28 -0700 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1185727058.306635.203130@b79g2000hse.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> <1184458002.961657.267830@x35g2000prf.googlegroups.com> <1184466882.446791.127670@x35g2000prf.googlegroups.com> <1185658013.859359.47700@57g2000hsv.googlegroups.com> <1185703671.241103.124780@g12g2000prg.googlegroups.com> <1185727058.306635.203130@b79g2000hse.googlegroups.com> Message-ID: <1185738028.905572.179600@b79g2000hse.googlegroups.com> www.pylonshq.com, www.pythonpaste.org you may find these easier than mod_python. From conradoplg at gmail.com Wed Jul 25 16:32:46 2007 From: conradoplg at gmail.com (Conrado PLG) Date: Wed, 25 Jul 2007 13:32:46 -0700 Subject: Bug in cPickle with packages and 'object' inherited class Message-ID: <1185395566.665326.310600@d55g2000hsg.googlegroups.com> Say you have this structure: pna/ __init__.py model.py __init__.py is empty. model.py is: import cPickle as pickle class A(object): pass def serialize(): pickle.dump(A(), open('temp.dat', 'wb')) Now open a python interpreter on the root directory of that structure and type: import pna.model pna.model.serialize() The following exception is thrown: Traceback (most recent call last): File "test.py", line 2, in pna.model.serialize() File "...\pna\model.py", line 7, in serialize pickle.dump(A(), open('temp.dat', 'wb')) cPickle.PicklingError: Can't pickle : import of module pna.model failed If you use 'pickle' instead of 'cPickle', it works. If you don't inherit from 'object' in 'A', it works. I'm using Python 2.5.1 on Windows XP. I've tested in Python 2.4.4 on Linux and it works. Any ideas of what is going on? Thanks, Conrado From gagsl-py2 at yahoo.com.ar Mon Jul 23 02:21:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Jul 2007 03:21:44 -0300 Subject: importing a module from a specific directory References: <20070722120343.GA4759@gmail.com> Message-ID: En Sun, 22 Jul 2007 09:03:43 -0300, O.R.Senthil Kumaran escribi?: >> I would like to organize them into directory structure in >> which there is a 'main' directory, and under it directories for >> specific sub-tasks, or sub-experiments, I'm running (let's call them >> 'A', 'B', 'C'). >> Is there a neat clean way of achieving the code organization? >> > > This is a kind of a frequently asked question at c.l.p and every > programmer I > guess has to go through this problem. > If you look around c.l.p you will find that one of the good ways to > solve this > problem with the python interpretor <2.5 is: > >>>> import sys >>>> sys.path.append(os.path.abspath(os.pardir)) I would write it as sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - or certainly split it into two lines, because the current directory may not be the directory containing the script. > But, if you are using Python 2.5, you are saved. > > > Starting with Python 2.5, in addition to the implicit relative imports > described above, you can write explicit relative imports with the from > module > import name form of import statement. These explicit relative imports use > leading dots to indicate the current and parent packages involved in the > relative import. From the surround module for example, you might use: Note that this only applies to *packages*, not alone modules. And if you already have a package, it's better to put the driver/test/demo code out of the package itself, this way it must import the package the same way as any other client code. I usually place them in the directory containing the package (so "import package" just works). Other people prefer a different layout; search for some recent posts on this subject. -- Gabriel Genellina From infocat at earthlink.net Sun Jul 1 22:11:47 2007 From: infocat at earthlink.net (Frank Swarbrick) Date: Sun, 01 Jul 2007 20:11:47 -0600 Subject: Reversing a string In-Reply-To: <1i0kjpx.wjw44j15np22dN%aleax@mac.com> References: <1182997438.541012.54100@o61g2000hsh.googlegroups.com> <1i0kjpx.wjw44j15np22dN%aleax@mac.com> Message-ID: <5er575F39ucfaU1@mid.individual.net> Alex Martelli wrote: > Martin Durkin wrote: > ... >>>>>>>>> print "\n".join("spam"[::-1]) > ... >>>> OK, maybe I'm missing the point here as I'm new to Python. The first >>>> one seems clearer to me. What am I missing? >>>> >>> I think all you are missing is familarity with Python, but I too don't >>> like one-liners simply for their own sake. >> I guess that's it. The first one reads more like a textbook example which >> is about where I am at. Is there any speed benefit from the one liner? > > The first example reads "excruciatingly low-level" to me: its autor is > thinking in terms of what the machine is doing, mapped into pretty > elementary low-level constructs. > > The second example depends first of all on knowledge of extended-slicing > (specifically the fact that x[::-1] is a reversal, because of the > negative -1 "step" aka "stride"). If you don't know about extended > slicing, you're unlikely to just "get it from context", because it uses > a syntax based on punctuation rather than readable words whose meaning > you might guess at. Python has a modest amount of such "punctuation > syntax" -- about the same amount as C but definitely more than Cobol > (where one would typically write "ADD a TO b" to avoid shocking totally > clueless readers with "mysterious punctuation" such as "a + b"...!!!-). > Punctuation is often very concise but not "intrinsically obvious" unless > you've been exposed to it already;-). Since you mentioned Cobol I couldn't resist... move "spam" to spam Display Function Reverse(spam) There's also slicing (known in Cobol as "reference modification") move mystring(5:3) to my-newstring * moves 3 characters starting with character 5 No "negative" slicing, though it could be simulated with Function Reverse() and ref.mod. Frank From the.mindstorm.mailinglist at gmail.com Mon Jul 9 13:09:40 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Mon, 09 Jul 2007 10:09:40 -0700 Subject: execute script in certain directory In-Reply-To: References: Message-ID: <1184000980.796505.93380@r34g2000hsd.googlegroups.com> On Jul 9, 6:31 pm, brad wrote: > When I use idle or a shell to execute a python script, the script > executes in the directory it is currently in (in this case, my desktop). > However, when using GNOME and right clicking the py script and selecting > 'open with python', the execution occurs in my home directory, not my > desktop. > > Is there a way to force py scripts to always run within the directory > that they reside in? > > Thanks > > Brad > > /home/brad/Desktop/output - python from shell > /home/brad/Desktop/output - python from idle > /home/brad/output - python from Gnome 'right click' open with menu Interesting. I was wondering about the opposit: being in the parent dir, how can I run a module from a package. (the current behavior when running python dir_name\module.py is to consider the dir_name the current dir and this breaks all imports). I am pretty sure this is answered somewhere, but I must confess that so far I haven't been able to find it :-(. TIA, ./alex -- .w( the_mindstorm )p. From banaouas.medialog at wanadoo.fr Wed Jul 4 05:14:14 2007 From: banaouas.medialog at wanadoo.fr (m.banaouas) Date: Wed, 04 Jul 2007 11:14:14 +0200 Subject: windows cetificates Message-ID: <468b6509$0$27375$ba4acef3@news.orange.fr> hi, is there any way to decrypt an email (already read with poplib, so available on client side) with python using a window certificate (those we can see on ie/internet options/content/certificates) ? the purpose is to decrypt an email sent and crypted by the sender with both his own certificate and the recipient one. thanks for any help. From pabloski at giochinternet.com Sat Jul 7 12:06:03 2007 From: pabloski at giochinternet.com (pabloski at giochinternet.com) Date: Sat, 07 Jul 2007 16:06:03 GMT Subject: Unicode problem Message-ID: Hi to all, I have a little problem with unicode handling under Python. I have this code s = u'A unicode string with this damn apostrophe \x2019' outf = codecs.open('filename.txt', 'w', 'iso-8859-15') outf.write(s) what I obtain is a UnicodeEncodeError that says me that character \x2019 maps to undefined. But the character \x2019 is the apostrophe and in the unicode table it has \x0027 as an equivalent, so the codecs should convert \x2019 to \x27 ( as defined in iso-8859-15 ).... The problem is that my software deals with italian strings that has a lot of apostrophe and other similar simbols mapped between 2000 and 206F Have can I resolve this issue? Should I prepocess the unicode strings or is there a way to instruct Python to do the conversion? From BjornSteinarFjeldPettersen at gmail.com Mon Jul 23 05:27:49 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Mon, 23 Jul 2007 09:27:49 -0000 Subject: Catching a key press In-Reply-To: <1185174340.795377.13800@r34g2000hsd.googlegroups.com> References: <1185173730.345615.284940@q75g2000hsh.googlegroups.com> <1185174340.795377.13800@r34g2000hsd.googlegroups.com> Message-ID: <1185182869.893136.139870@k79g2000hse.googlegroups.com> On Jul 23, 9:05 am, westymatt wrote: > This is without a gui toolkit. This is going to be implemented on > console i/o If you're on windows, you'll need the kbhit() and getch() functions in the msvcrt module. The up arrow returns two separate "keyboard- hits" (with ordinal value 224 and 72). -- bjorn From bonnie at macbird.com Sun Jul 15 03:47:20 2007 From: bonnie at macbird.com (bonnie at macbird.com) Date: Sun, 15 Jul 2007 07:47:20 -0000 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: <4697d9f0$0$7614$426a74cc@news.free.fr> Message-ID: <1184485640.495801.194200@z28g2000prd.googlegroups.com> On Jul 13, 3:20 pm, Wayne Brehaut wrote: > On Sat, 14 Jul 2007 06:01:56 +0200, Bruno Desthuilliers > > wrote: > >Chris Carlen a ?crit : > >> Hi: > > >> From what I've read of OOP, I don't get it. I have also found some > >> articles profoundly critical of OOP. I tend to relate to these articles. > > === 8< === > > > > >> Hence, being a hardware designer rather than a computer scientist, I am > >> conditioned to think like a machine. I think this is the main reason > >> why OOP has always repelled me. > > >OTOH, OO is about machines - at least as conceveid by Alan Key, who > >invented the term and most of the concept. According to him, each object > >is a (simulation of) a small machine. > > Oh you young'uns, not versed in The Ancient Lore, but filled with > self-serving propaganda from Xerox PARC,Alan Kay, and Smalltalk > adherents everywhere! > > As a few more enlightened have noted in more than one thread here, the > Mother of All OOP was Simula (then known as SIMULA 67). AllAlan Kay > did was define "OOPL", but then didn't notice (apparently--though this > may have been a "convenient oversight") that Simula satisfied all the > criteria so was actually the first OOPL--and at least 10 years earlier > than Smalltalk! > > So Kay actually invented NONE of the concepts that make a PL an OOPL. > He only stated the concepts concisely and named the result OOP, and > invented yet another implementation of the concepts-- based on a > LISP-like functional syntax instead of an Algol-60 procedural syntax, > and using message-passing for communication amongst objects (and > assumed a GUI-based IDE) (and introduced some new terminology, > especially use of the term "method" to distinguish class and instance > procedures and functions, which Simula hadn't done) . > > As Randy Gest notes onhttp://www.smalltalk.org/alankay.html, "The > major ideas in Smalltalk are generally credited toAlan Kaywith many > roots in Simula, LISP and SketchPad." Too many seem to assume that > some of these other "features" of Smalltalk are part of the definition > of an OOP, and so are misled into believing the claim that it was the > first OOPL. Or they claim that certain deficiencies in Simula's object > model--as compared to Smalltalk's--somehow disqualifies it as a "true > OOPL", even though it satisfies all the criteria as stated by Kay in > his definition. Seehttp://en.wikipedia.org/wiki/Simulaand related > pages, and "The History of Programming Languages I (HOPL I)", for > more details. > > Under a claim of Academic Impunity (or was that "Immunity"), here's > another historical tid-bit. In a previous empolyment we once had a > faculty applicant from CalTech who knew we were using Simula as our > introductory and core language in our CS program, so he visited Xerox > PARC before coming for his inteview. His estimate ofAlan Kayand > Smalltalk at that time (early 80s) was that "They wanted to implement > Simula but didn't understand it--so they invented Smalltalk and now > don't understand _it_!" > > wwwayne > > === 8< === A couple of notes on this post. Alan Kay has always publicly credited Simula as the direct inspiration for Smalltalk, and if you know the man and his work, this implication of taking credit for the first OOP language is not true, it is a credit assigned to him by others, and one which he usually rights when confronted with it. You may be confused with the fact that "object oriented programming"was a term which I believe was first used by Alan and his group at PARC, so perhaps the coining of the term is what is being referenced by others. Perhaps I'm mistaken, but the tone of your post conveys an animosity that did not exist between the original Smalltalk and Simula inventors; Nygard and Kay were good friends, and admired each others' work very much. Bonnie MacBird From carsten at uniqsys.com Tue Jul 24 13:57:20 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 24 Jul 2007 13:57:20 -0400 Subject: Any python module for Traversing HTML files In-Reply-To: <1185298581.322910.311720@w3g2000hsg.googlegroups.com> References: <1185297135.542235.55290@r34g2000hsd.googlegroups.com> <1185298581.322910.311720@w3g2000hsg.googlegroups.com> Message-ID: <1185299840.3370.28.camel@dot.uniqsys.com> On Tue, 2007-07-24 at 17:36 +0000, Clement wrote: > On Jul 24, 10:12 pm, johnny wrote: > > Any python module for navigating and selecting, parsing HTML files? > > try beautyfulshop Failing that, try BeautifulSoup. -- Carsten Haese http://informixdb.sourceforge.net From steve at REMOVE.THIS.cybersource.com.au Thu Jul 5 04:06:11 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 05 Jul 2007 18:06:11 +1000 Subject: Proposal: s1.intersects(s2) References: <5f1pldF3a62csU5@mid.uni-berlin.de> Message-ID: On Wed, 04 Jul 2007 23:53:15 -0400, David Abrahams wrote: > > on Wed Jul 04 2007, "Steven D'Aprano" wrote: > >> On Wed, 04 Jul 2007 14:37:34 +0000, Marc 'BlackJack' Rintsch wrote: >> >>> On Wed, 04 Jul 2007 09:59:24 -0400, David Abrahams wrote: >>> >>>> Here's an implementation of the functionality I propose, as a >>>> free-standing function: >>>> >>>> def intersects(s1,s2): >>>> if len(s1) < len(s2): >>>> for x in s1: >>>> if x in s2: return True >>>> else: >>>> for x in s2: >>>> if x in s1 return True >>>> return False >>> >>> In Python 2.5 this can be written a bit more concise: >>> >>> def intersects(set_a, set_b): >>> if len(set_a) < len(set_b): >>> set_a, set_b = set_b, set_a >>> return any(item in set_a for item in set_b) >> >> >> I'd rather see sets gain an method "isintersect()" > > And why is that a good name? It's not even grammatical. Neither is "It's not even grammatical", but all but purists use it regardless. A common Python convention is to have test functions named something like "isfoo", e.g. str.isdigit(), isspace(), islower() etc. They're not exactly grammatical either, e.g. isdigit() should actually be "contains one or more digits, and nothing but digits". (Presumably the pedantically correct name was rejected as being too long.) I was just following that convention. My main feeling is that any such function should be a set method rather than a built-in function like len(). The name change was comparatively unimportant. >> with the functionality than the language to gain a built-in >> function. > > How is a method on sets not a built-in function? Anyway, such a > method is what I'm proposing. Although they are similar, methods are not identical to functions, even if many of us, myself included, often use the terms interchangeably. len() is a built-in function. str.lower() is a method of strings. I'd prefer to see intersects() be a method of sets than a built-in function, and I think you'd have a much better chance of getting it approved as a method than as a function, but I could be wrong. >> However, there's a very subtle flaw in the idea. While "the intersection" >> of two sets is well-defined, "these two sets intersect" is (surprisingly!) >> _not_ well-defined. > > Depends how you define it. Exactly my point. > I define it as "has a non-empty intersection," which is pretty obviously > solid. I didn't say it was a bad choice, only that it isn't the only choice. -- Steven. From steve at holdenweb.com Sun Jul 22 13:06:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 22 Jul 2007 13:06:53 -0400 Subject: problem with exec In-Reply-To: References: <1185099810.772825.284620@m3g2000hsh.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Sun, 22 Jul 2007 09:12:21 -0400, Steve Holden wrote: > > >>> Steve Holden was playing silly games. You can't use { } for indentation. >>> You have to use indentation. >>> >> I wasn't playing silly games at all, and I did prefix that part ofmy >> answer with "I'm afraid I don't understand this question". The OP is >> writing a program to "translate" a Python-like language that uses >> non-English keywords into Python. Since the application is transforming >> its input, it could transform braces into indentation. Of course >> *Python* doesn't use braces, but the question was how to write >> "pseudo-Python" without using indentation to indicate grouping. > > Then I have misunderstood you, and I apologize. > Thanks. I was hoping that was the case. 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 Tue Jul 31 10:43:26 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 31 Jul 2007 11:43:26 -0300 Subject: What is the "functional" way of doing this? In-Reply-To: <1185839713.412656.242950@i13g2000prf.googlegroups.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> Message-ID: <46AF4A8E.8030806@bigfoot.com> Kept testing (just in case). There was this other version of lists2.py (see below). So I created lists3.py and lists4.py. The resulting times are lists1.py : 11.4529998302 lists2.py : 16.1410000324 lists3.py : 3.17199993134 lists4.py : 20.9839999676 lists3.py is by far the better time, but it does not generate a list but a generator object, as soon as you make it into a list (lists4.py) times go up (I don't know why do they go up that much). Apparently the way you use the conversion to a list, in the function(lists2.py) or in the loop (lists4.py), makes a big difference. Anyway lists1.py is still the best of the list generating times, and (in my view) the most elegant and easy to understand expression of the algorithm. ------------------------------------------------ lists1.py : def f(n): if n > 0: return ([n%26] + f(n/26)) else: return [] import time start = time.time() for x in range(1,1000000): f(2100000000) end = time.time() print end - start ----------------------------------------------- lists2.py : def f(n): def mseq(n): while n > 0: n,a = divmod(n, 26) yield a return list(mseq(n)) import time start = time.time() for x in range(1,1000000): f(2100000000) end = time.time() print end - start ------------------------------------------------ lists3.py def f(n): if n>0: yield n%26 for i in f(n/26): yield i import time start = time.time() for x in range(1,1000000): f(2100000000) end = time.time() print end - start ------------------------------------------------ lists4.py def f(n): if n>0: yield n%26 for i in f(n/26): yield i import time start = time.time() for x in range(1,1000000): list(f(2100000000)) end = time.time() print end - start ---------------------------------------------------- From bsneddon at yahoo.com Thu Jul 12 21:13:24 2007 From: bsneddon at yahoo.com (bsneddon) Date: Thu, 12 Jul 2007 18:13:24 -0700 Subject: Fastest way to convert a byte of integer into a list In-Reply-To: <1184287796.252097.46660@x35g2000prf.googlegroups.com> References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> <1184284461.506663.75500@g12g2000prg.googlegroups.com> <1184284861.695430.99300@e9g2000prf.googlegroups.com> <7xr6ndtae7.fsf@ruckus.brouhaha.com> <1184287796.252097.46660@x35g2000prf.googlegroups.com> Message-ID: <1184289204.494179.244820@w3g2000hsg.googlegroups.com> On Jul 12, 8:49 pm, John Machin wrote: > On Jul 13, 10:28 am, Paul Rubin wrote: > > > Godzilla writes: > > > > num = 255 > > > > numlist = [num >> i & 1 for i in range(8)] > > > > Thanks matimus! I will look into it... > > > numlist = lookup_table[num] > > > where lookup_table is a precomputed list of lists. > > Ummm ... didn't the OP say he had 32-bit numbers??? List comprehension would be faster, lookup would be even faster but would have to generate list or dictionary ahead of time but this will work on any length int up 2 limit of int does not pad with zeros on most significant end to word length. n=input() l=[] while(n>0): l.append(str(n&1)); n=n>>1 I posted this here http://www.uselesspython.com/download.php?script_id=222 a while back. From captainpoutine at gmail.com Thu Jul 5 14:19:24 2007 From: captainpoutine at gmail.com (Captain Poutine) Date: Thu, 05 Jul 2007 14:19:24 -0400 Subject: Where is the syntax for the dict() constructor ?! In-Reply-To: References: <468D1D9D.6060002@gmail.com> Message-ID: <468D362C.2@gmail.com> Peter Otten wrote: > Neil Cerutti wrote: > >> On 2007-07-05, Captain Poutine wrote: >>> I'm simply trying to read a CSV into a dictionary. >>> >>> (if it matters, it's ZIP codes and time zones, i.e., >>> 35983,CT >>> 39161,CT >>> 47240,EST >>> >>> >>> >>> Apparently the way to do this is: >>> >>> import csv >>> >>> dictZipZones = {} >>> >>> reader = csv.reader(open("some.csv", "rb")) >>> for row in reader: >>> # Add the row to the dictionary >> In addition to Chris's answer, the csv module can read and write >> dictionaries directly. Look up csv.DictReader and csv.DictWriter. > > DictReader gives one dict per row, with field names as keys. The OP is more > likely to want > > dict(csv.reader(open("some.csv", "rb"))) > > which produces a dict that maps ZIP codes to time zones. > > Peter > Thanks Peter, that basically works, even if I don't understand it. What does "rb" mean? (read binary?) Why are the keys turned into strings (they are not quoted in the .csv file)? From tylerca at jeld-wen.com Tue Jul 31 13:41:32 2007 From: tylerca at jeld-wen.com (Azazello) Date: Tue, 31 Jul 2007 17:41:32 -0000 Subject: Encryption recommendation In-Reply-To: References: Message-ID: <1185903692.138145.42210@z28g2000prd.googlegroups.com> On Jul 31, 10:19 am, "JS" wrote: > Can someone help me find the proper way to do AES encryption/decryption > using Python? > > Thanks! I did a quick look around the internet and found this seemingly good link AES in general. Might be a good start. http://msdn.microsoft.com/msdnmag/issues/03/11/AES/#S4 Looks like you'll need some matrix manipulations modules, and hopefully you'll be able to utilize Python's indexing and data strengths to keep things simple! From vedrandekovic at v-programs.com Sun Jul 1 12:04:33 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Sun, 01 Jul 2007 09:04:33 -0700 Subject: how to send files via bluetooth with python to a mobile In-Reply-To: <1183294323.556314.293860@m36g2000hse.googlegroups.com> References: <1183294323.556314.293860@m36g2000hse.googlegroups.com> Message-ID: <1183305873.736724.116680@c77g2000hse.googlegroups.com> Drex je napisao/la: > Hi, > > I have been looking on the internet for some info about sending files > from PC to a mobile phone (I have a nokia 6288) but I was not able to > find anything. > > there is a lot of info how to transfer files from a symbian phone to a > pc, but nothing about sending them in the oposite direction. > > would anybody point me to some resources on the topic? > > thanks, regards > dz Hi, I'm not sure but try this: ( py_s60 ) http://sourceforge.net/projects/pyed/ regards, vedran From jjl at pobox.com Tue Jul 10 19:31:40 2007 From: jjl at pobox.com (John J. Lee) Date: Tue, 10 Jul 2007 23:31:40 GMT Subject: Tool for finding external dependencies References: <1183945183.147231.120180@z28g2000prd.googlegroups.com> Message-ID: <87y7hnesyr.fsf@pobox.com> Rob Cakebread writes: > Hi, > > I need to find external dependencies for modules (not Python standard > library imports). > > Currently I use pylint and manually scan the output, which is very > nice, or use pylint's --ext-import-graph option to create a .dot file > and extract the info from it, but either way can take a very long > time. > > I'm aware of Python's modulefinder.py, but it doesn't find external > dependencies (or at least I don't know how to make it do them). Try looking at py2exe and pyinstaller. They may have useful ideas. John From steve at holdenweb.com Mon Jul 2 18:03:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Jul 2007 18:03:29 -0400 Subject: Python compilation ?? In-Reply-To: <20070702202448.4947.2088004513.divmod.quotient.6059@ohm> References: <20070702202448.4947.2088004513.divmod.quotient.6059@ohm> Message-ID: <46897631.8020102@holdenweb.com> Jean-Paul Calderone wrote: > On Mon, 02 Jul 2007 16:14:41 -0400, Steve Holden wrote: >> Evan Klitzke wrote: >>> On 7/2/07, Cathy Murphy wrote: >>>> Is python a compiler language or interpreted language. If it is interpreter >>>> , then why do we have to compile it? >>> It's an interpreted language. It is compiled into bytecode (not >>> machine code) the first time a script is run to speed up subsequent >>> executions of a script. >>> >> While the flavor of this answer is correct, in strict point of fact >> Python *doesn't* compile the scripts it executes, only the modules that >> are imported. >> >> That's why you will occasionally see a very small Python program that >> just calls functions imported from much larger modules. This avoids >> spending the time that would otherwise have to be spent recompiling a >> large script at each execution. > > Hey Steve, > > To nit pick :) Wouldn't you say it is more accurate to say that it > does compile the scripts (by which we mean the "main" file - either > the one passed as an argument to the interpreter on the command line, > or the one with a #! at the top which gets respected, or the .py file > on Windows which is associated with python.exe as its interpreter), > but that it doesn't save the results of this compilation to a file to > be used next time? > > Jean-Paul Absolutely. I should, of course, have said that only imported modules have the results of the compilation stored as a .pyc file. One must presume this is to save the file write time during development when the program is almost always different fro the last time you ran 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 ChrisEdgemon at gmail.com Thu Jul 12 17:41:10 2007 From: ChrisEdgemon at gmail.com (ChrisEdgemon at gmail.com) Date: Thu, 12 Jul 2007 14:41:10 -0700 Subject: Where does str class represent its data? In-Reply-To: <%Egli.5395$rL1.3818@newssvr19.news.prodigy.net> References: <1184196082.903895.176020@n60g2000hse.googlegroups.com> <%Egli.5395$rL1.3818@newssvr19.news.prodigy.net> Message-ID: <1184276470.733520.265990@n2g2000hse.googlegroups.com> On Jul 11, 9:49 pm, James Stroud wrote: > ChrisEdge... at gmail.com wrote: > > I'd like to implement a subclass of string that works like this: > > >>>>m = MyString('mail') > >>>>m == 'fail' > > > True > > >>>>m == 'mail' > > > False > > >>>>m in ['fail', hail'] > > > True > > > My best attempt for something like this is: > > > class MyString(str): > > def __init__(self, seq): > > if self == self.clean(seq): pass > > else: self = MyString(self.clean(seq)) > > > def clean(self, seq): > > seq = seq.replace("m", "f") > > > but this doesn't work. Nothing gets changed. > > > I understand that I could just remove the clean function from the > > class and call it every time, but I use this class in several > > locations, and I think it would be much safer to have it do the > > cleaning itself. > > The "flat is better than nested" philosophy suggests that clean should > be module level and you should initialize a MyString like such: > > m = MyString(clean(s)) > > Where clean is > > def clean(astr): > return astr.replace('m', 'f') > > Although it appears compulsory to call clean each time you instantiate > MyString, note that you do it anyway when you check in your __init__. > Here, you are explicit. Such an approach also eliminates the obligation > to clean the string under conditions where you know it will already be > clean--such as deserialization. Initially, I tried simply calling a clean function on a regular string, without any of this messy subclassing. However, I would end up accidentally cleaning it more than once, and transforming the string was just very messy. I thought that it would be much easier to just clean the string once, and then add methods that would give me the various transformations that I wanted from the cleaned string. Using __new__ seems to be the solution I was looking for. > > Also, you don't return anything from clean above, so you assign None to > self here: > > self = MyString(self.clean(seq)) > > Additionally, it has been suggested that you use __new__. E.g.: > > py> class MyString(str): > ... def __new__(cls, astr): > ... astr = astr.replace('m', 'f') > ... return super(MyString, cls).__new__(cls, astr) > ... > py> MyString('mail') > 'fail' > > But this is an abuse of the str class if you intend to populate your > subclasses with self-modifying methods such as your clean method. In > this case, you might consider composition, wherein you access an > instance of str as an attribute of class instances. The python standard > library make this easy with the UserString class and the ability to add > custom methods to its subclasses: What constitutes an abuse of the str class? Is there some performance decrement that results from subclassing str like this? (Unfortunately my implementation seems to have a pretty large memory footprint, 400mb for about 400,000 files.) Or do you just mean from a philsophical standpoint? I guess I don't understand what benefits come from using UserString instead of just str. Thanks for the help, Chris > > py> from UserString import UserString as UserString > py> class MyClass(UserString): > ... def __init__(self, astr): > ... self.data = self.clean(astr) > ... def clean(self, astr): > ... return astr.replace('m', 'f') > ... > py> MyClass('mail') > 'fail' > py> type(_) > > > This class is much slower than str, but you can always access an > instance's data attribute directly if you want fast read-only behavior. > > py> astr = MyClass('mail').data > py> astr > 'fail' > > But now you are back to a built-in type, which is actually the > point--not everything needs to be in a class. This isn't java. > > James > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ From cito at online.de Sat Jul 7 05:17:14 2007 From: cito at online.de (Christoph Zwerschke) Date: Sat, 07 Jul 2007 11:17:14 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: <1183731180.023370.240820@c77g2000hse.googlegroups.com> References: <1183731180.023370.240820@c77g2000hse.googlegroups.com> Message-ID: Gerard Flanagan wrote: > Would a decorator work here? Depends on how you want to use that functionality. In my use case I only need to catch the excpetion once. Note that in your code the exception has not the right type which is what I targeted in my last posting. I.e. the following will raise an Exception if function is decorated: try: print funktion() except ArithmeticError: pass -- Chris From http Thu Jul 26 19:44:22 2007 From: http (Paul Rubin) Date: 26 Jul 2007 16:44:22 -0700 Subject: zip() function troubles References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> Message-ID: <7xir86wx0p.fsf@ruckus.brouhaha.com> Istvan Albert writes: > exceeded 10 million the zip function slowed to a crawl. Note that > there was memory available to store over 100 million items. How many bytes is that? Maybe the items (heap-allocated boxed integers in your code example) are bigger than you expect. From hongyuan1306 at gmail.com Thu Jul 26 00:10:16 2007 From: hongyuan1306 at gmail.com (Yuan HOng) Date: Thu, 26 Jul 2007 12:10:16 +0800 Subject: Locale-specific string comparasion Message-ID: <91320d220707252110s57dddd8fv78f7b8908f6d353f@mail.gmail.com> Hi, The locale modules privides a strcoll function that can perform locale specific string comparision, and based on this, we can design custom comparision function for the sorting. However, this is quite cumbersome, for we have to derive custom classes from from the string / unicode objects, and provide comparision function to use locale.strcoll. Is there a way to 'install' a system wide LC_COLLATE function, so that string and unicode objects will automatically use the locale for their comparision? -- Hong Yuan ????????? ??????????? http://www.homemaster.cn From nis at superlativ.dk Mon Jul 2 05:30:06 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Mon, 02 Jul 2007 11:30:06 +0200 Subject: howto resend args and kwargs to other func? In-Reply-To: <4688a103$0$29642$426a34cc@news.free.fr> References: <1183279997.244378.105810@n60g2000hse.googlegroups.com> <1183280667.542964.175570@u2g2000hsc.googlegroups.com> <1183282733.179683.174350@c77g2000hse.googlegroups.com> <5er6doF31bulkU1@mid.individual.net> <4688a103$0$29642$426a34cc@news.free.fr> Message-ID: <4688C59E.4020303@superlativ.dk> Bruno Desthuilliers skrev: >> Why do people do this without posting what the actual solution is!!!! > > Probably because those people think usenet is a free help desk ? Usenet definitely isn't a help desk. You often get useful answers from usenet, from people who are not reading from a script. Nis From cito at online.de Thu Jul 5 17:56:15 2007 From: cito at online.de (Christoph Zwerschke) Date: Thu, 05 Jul 2007 23:56:15 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: References: Message-ID: Seems that no simple solution exists, so for now, I will be using something like this: class PoliteException(Exception): def __init__(self, e): self._e = e def __getattr__(self, name): return getattr(self._e, name) def __str__(self): if isinstance(self._e, PoliteException): return str(self._e) else: return '\n%s: %s, I am sorry!' % ( self._e.__class__.__name__, str(self._e)) try: unicode('\xe4') except Exception, e: raise PoliteException(e) From vedrandekovic at v-programs.com Sun Jul 22 06:23:30 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Sun, 22 Jul 2007 03:23:30 -0700 Subject: problem with exec In-Reply-To: References: Message-ID: <1185099810.772825.284620@m3g2000hsh.googlegroups.com> On 21 srp, 22:31, Steve Holden wrote: > ...:::JA:::... wrote: > > Hello, > > > After my program read and translate this code: > > > koristi os,sys; > > ispisi 'bok kaj ima'; > > > into the: > > > import os,sys; > > print 'bok kaj ima'; > > > and when it run this code with "exec", I always get error like this, but I > > still dont't know what is a problem: > > > Traceback (most recent call last): > > File "C:\Python24\Lib\site-packages\VL\__init__.py", line 188, in > > kompajlati > > kompajlati_proces() > > File "C:\Python24\Lib\site-packages\VL\__init__.py", line 183, in > > kompajlati_proces > > h2=Konzola() > > File "C:\Python24\Lib\site-packages\VL\__init__.py", line 158, in __init__ > > k=kod(ZTextCtrl.GetLabel()) > > File "C:\Python24\Lib\site-packages\VL\__init__.py", line 83, in kod > > exec(str_ngh) > > File "", line 1 > > import os ,sys ; > > ^ > > SyntaxError: invalid syntax > > This is almost certainly because the code contains embedded carriage > returns: > > >>> code = """import os,sys;\nprint 'bok kaj ima';""" > >>> exec code > bok kaj ima > >>> code = """import os,sys;\r\nprint 'bok kaj ima';""" > >>> exec code > Traceback (most recent call last): > File "", line 1, in > File "", line 1 > import os,sys; > ^ > SyntaxError: invalid syntax > >>> > > > PS: How can I change when user write script with my program to he don't need > > aspirate the lines of his source code > > e.g. > > import os,sys > > n=90 > > if n==90:print "OK" > > else:print "No" > > I'm afraid I don't understand this question. If you are talking about > the indentation of the code, if you don't want indentation you will have > to use braces - { and } - to indicate the nesting structure of your program. > > 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 ------------- Hello, Thanks for everything previously, but just to I ask about code indentation,this with { and } doesn't employed, here is my example how can I solve this about code indentation: >>> n=90 >>> if n==90: {print "bok kjai ma'} File "", line 2 {print "bok kjai ma'} ^ SyntaxError: invalid syntax Thanks!!!!!!! Regards,Vedran From orl at gmx.de Sat Jul 14 19:04:21 2007 From: orl at gmx.de (=?iso-8859-1?Q?=22Orlando_D=F6hring=22?=) Date: Sun, 15 Jul 2007 01:04:21 +0200 Subject: Marshalling big objects Message-ID: <20070714230421.213010@gmx.net> Dear community, I want to marshal objects: - http://docs.python.org/lib/module-marshal.html where I have problems with a bigger objects, e.g. self.contiguousSurfaceResidues, see below. I was writing the object to file: fDump1 = open('dump_13PK_C.dat','wb') marshal.dump(self.contiguousSurfaceResidues, fDump1) fDump1.close() loading it again: fDump1 = open('dump_13PK_C.dat','rb') self.contiguousSurfaceResidues = marshal.load(fDump1) fDump1.close() which yields nonsense as output, i.e. square-symbols etc. How to handle large objects? Thanks. Yours, Orlando -- self.contiguousSurfaceResidues = [[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 1. 1. 0. 0. 0. 0. 0. 1. 1. 1. 1. 1. 0. 0. 1. 1. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] ... [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1. 1. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 1. 0.]] -- -- Psssst! Schon vom neuen GMX MultiMessenger geh?rt? Der kanns mit allen: http://www.gmx.net/de/go/multimessenger From nagle at animats.com Sat Jul 21 14:43:11 2007 From: nagle at animats.com (John Nagle) Date: Sat, 21 Jul 2007 18:43:11 GMT Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xvecdr5rf.fsf@ruckus.brouhaha.com> References: <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <7x8x9lwka9.fsf@ruckus.brouhaha.com> <7xbqe7ox9n.fsf@ruckus.brouhaha.com> <1185040314.501879.266230@22g2000hsm.googlegroups.com> <7xvecdr5rf.fsf@ruckus.brouhaha.com> Message-ID: <3tsoi.50945$5j1.31830@newssvr21.news.prodigy.net> Paul Rubin wrote: > Kay Schluehr writes: > >>When I remember correctly the FDIV bug was due to a wrongly filled >>lookup table and occurred only for certain bitpattern in the divisor. >>I'm not sure how a formal proof on the structure of the algorithm >>could help here? Intel repaired the table i.e. the data not the >>algorithm that acted upon it. No, Intel had assumed a symmetry that wasn't actually true. > I would expect the table contents to be part of the stuff being > proved. I hear that they do use formal proofs for their floating > point stuff now, as does AMD. AMD apparently uses ACL2 (a theorem > prover written in Common Lisp, info about AMD is from the ACL2 web > site) but I don't know what Intel uses. I've figured that the FDIV > problem was one of the motivations for this but I'm not certain of it. Yes, here's two of the papers describing proofs of AMD floating point unit correctness. Division: "http://citeseer.ist.psu.edu/53148.html" Square root: "http://portal.acm.org/citation.cfm?id=607571" A longer paper: http://www.computationallogic.com/news/amd.html This stuff is hard to do, but notice that AMD hasn't had any recalls for floating point problems. John Nagle From http Mon Jul 16 01:37:02 2007 From: http (Paul Rubin) Date: 15 Jul 2007 22:37:02 -0700 Subject: how to implementation latent semantic indexing in python.. References: <1i1bczv.b60cm8y6ygowN%aleax@mac.com> Message-ID: <7xwsx0kiyp.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > You may get more responses (as in, >0!-) if you give some URL about what > this algorithm is supposed to do. http://en.wikipedia.org/wiki/Latent_semantic_analysis Very cool stuff. From http Thu Jul 26 06:58:20 2007 From: http (Paul Rubin) Date: 26 Jul 2007 03:58:20 -0700 Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> Message-ID: <7xzm1jl9df.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > Propose: > 123 456 789 => 123456789 > 123.456 789 => 123.456789 +1 From jstroud at mbi.ucla.edu Mon Jul 16 19:05:30 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 16 Jul 2007 16:05:30 -0700 Subject: Break up list into groups In-Reply-To: <7x644kyo09.fsf@ruckus.brouhaha.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> <7x644kyo09.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > See: > > http://groups.google.com/group/comp.lang.python/msg/2410c95c7f3b3654 Groupby is damn slow as far as I can tell (the Bates numbering in the above link assumes more than the OP intended, I assume). It looks like the author's original algorithm is the fastest python way as it bypasses a lot of lookup, etc. Here's the output from the script below (doit2 => groupby way): doit 11.96 usec/pass doit2 87.14 usec/pass James # timer script from itertools import groupby from timeit import Timer alist = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, 13, 0xF0, 14, 0xF1, 15] def doit(alist): ary = [] for i in alist: if 0xf0 & i: ary.append([i]) else: ary[-1].append(i) return [x for x in ary if x] def c(x): return 0xf0 & x def doit2(alist): i = (list(g) for k,g in groupby(alist, c)) return [k for k in [j + i.next() for j in i] if len(k)>1] print doit(alist) print 'doit' t = Timer('doit(alist)', 'from __main__ import groupby, doit, alist, c') print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) print 'doit2' t = Timer('doit2(alist)', 'from __main__ import groupby, doit2, alist, c') print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From clemesha at gmail.com Tue Jul 10 05:00:13 2007 From: clemesha at gmail.com (agc) Date: Tue, 10 Jul 2007 09:00:13 -0000 Subject: trouble controlling vim with subprocess on windows machine In-Reply-To: <5qFki.19733$2v1.4163@newssvr14.news.prodigy.net> References: <1183970186.663847.4380@o61g2000hsh.googlegroups.com> <1184023825.646120.251060@d55g2000hsg.googlegroups.com> <5qFki.19733$2v1.4163@newssvr14.news.prodigy.net> Message-ID: <1184058013.324624.220540@i38g2000prf.googlegroups.com> Hi Josiah, > >> This recipe for asynchronous communication usingsubprocesscould be > >> used to write an expect-like tool: > >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 I have played with the above recipe and it is excellent, but could you please go into some more detail about what is needed to make a cross platform [p]expect like (non-pty based) tool? Specifically, could you describe how you would connect to *another* interactive Python process with your subclass of subprocess.Popen? i.e: a = Popen('python', stdin=?, stdout=?, stderr=?) #now run an interactive session with 'a' I have tried several combinations of the above and I seem to be stuck on the fact that python is interacting with a 'tty', not 'std*'. Maybe I'm missing a basic piece? Thanks for any input, Alex > >> It works on both Windows and *nix. > > >> - Josiah > > > I had the original dir work but when I tried to trade it out with vim > > it isn't clear > > how I should call it.. vim filename and it doesn't find filename for > > some reason. > > I called it pipe and then > > > inport pipe > > > def load_instrument3(instr_name, csd_name): > > if sys.platform == 'win32': > > shell, commands, tail = ('gvim' + csd_name, (csd_name, > > csd_name), '\r\n') > > else: > > shell, commands, tail = ('sh', ('ls', 'echo HELLO WORLD'), > > '\n') > > > a = pipe.Popen(shell, stdin=pipe.PIPE, stdout=pipe.PIPE) > > print pipe.recv_some(a), > > for cmd in commands: > > pipe.send_all(a, csd_name) > > print pipe.recv_some(a), > > pipe.send_all(a, csd_name) > > print pipe.recv_some(a, e=0) > > a.wait() > > The example uses a platform-specific shell in order to use the > environment variable PATH to discover the executable to run. If you > know the exact path to your binary ('gvim' for you), it should work. > As-is, your program would require a binary with the name 'gvim'+csd_name > in the same path as the script you are executing. > > - Josiah From mshiltonj at gmail.com Sun Jul 8 15:11:05 2007 From: mshiltonj at gmail.com (mshiltonj) Date: Sun, 08 Jul 2007 19:11:05 -0000 Subject: accessing an object instance by only having one of its attribute values In-Reply-To: <1183918727.033724.213010@22g2000hsm.googlegroups.com> References: <1183918727.033724.213010@22g2000hsm.googlegroups.com> Message-ID: <1183921865.879071.172730@n2g2000hse.googlegroups.com> On Jul 8, 2:18 pm, feli... at gmail.com wrote: > Hello all, > > Imaybe someone can help me with this question. > Is there a direct way of accessing an object instance, if all I know > is the value of one of its attributes? > The object is part of a list of objects, and I would like to pick the > object directly by using this attribute value, instead of going > through the list and checking if each objects attribute value is the > one I am looking for. > > Thank you in advance I'd set up a dict as a lookup table, assuming the attribute values are unique per object. list_of_objects = (obj1, obj2, obj3, obj4); obj_lookup_by_attr = {}; for obj in list_of_objects: obj_lookup_by_attr.set(obj.attr, obj) [...] obj = obj_lookup_by_attr.get(attr_val, None); if (obj): [...] From leena_kirank at yahoo.com Wed Jul 11 17:11:51 2007 From: leena_kirank at yahoo.com (Kan) Date: Wed, 11 Jul 2007 14:11:51 -0700 Subject: Direct Client - Sr.Soft Engineer-Python and Linux Message-ID: <1184188311.998170.263830@m37g2000prh.googlegroups.com> Hello, We have requirement for Sr.Software Engineer in San Jose CA with very strong experinece in PYTHON AND LINUX . If your skills and experience matches with the same, send me your resume asap with contact # and rate. Locals only pls apply The details of the openings are:- Strong in Python and Linux Good in Java C++ Kan BTech Inc Recruiter 510-438-6834 www.tbiinc.org From deets at nospam.web.de Sun Jul 1 14:12:31 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 01 Jul 2007 20:12:31 +0200 Subject: how to send files via bluetooth with python to a mobile In-Reply-To: <1183310919.771396.268760@q69g2000hsb.googlegroups.com> References: <1183294323.556314.293860@m36g2000hse.googlegroups.com> <1183305873.736724.116680@c77g2000hse.googlegroups.com> <1183306850.712226.313800@m36g2000hse.googlegroups.com> <1183310919.771396.268760@q69g2000hsb.googlegroups.com> Message-ID: <5eq94iF3a5b8bU1@mid.uni-berlin.de> Drex schrieb: > Hey, > >>> I'm not sure but try this: ( py_s60 ) >>> http://sourceforge.net/projects/pyed/ > >> and also try this: >> >> http://sourceforge.net/projects/pys60 > > thanks, but I am affraid this is not what I was looking for. I need to > have some library on my pc (linux) that would allow me to transfer a > file to a bluetooth mobile phone (the mine doesn't have symbian). I > have some programs that allow to do that like for ex. obex_client but > I would like to write something similar using python. Wrap this http://www.zuckschwerdt.org/apidocs/ using ctypes. Diez From jakub.pola at gmail.com Thu Jul 12 05:48:09 2007 From: jakub.pola at gmail.com (stainboy) Date: Thu, 12 Jul 2007 02:48:09 -0700 Subject: Samodzielny program pod linuksem Message-ID: <1184233689.085729.254850@g4g2000hsf.googlegroups.com> Witam. Zastanawiam si? w jaki spos?b mog? stworzy? samodzielny program pod linuksem napisany w pythonie, aby mo?na go by?o uruchomi? bez instalacji bibliotek pythona, chodzi mi o co? takiego jak py2exe pod Windowsa. Pozdrawiam JP From raims at dot.com Mon Jul 16 08:41:43 2007 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 16 Jul 2007 14:41:43 +0200 Subject: Dynamic method References: <46939ba9$0$32159$426a74cc@news.free.fr> <46949c19$0$23164$426a34cc@news.free.fr> Message-ID: <1i1clx6.1qpf4ykihdj1oN%raims@dot.com> Bruno Desthuilliers wrote: > > I agree that in general the solution explained by Alex and you is better. > > They are not "better" - they are correct. Another way is to use the 'types' module: In [1]: class T(object): ...: pass ...: In [2]: t = T() In [3]: import types In [5]: types.MethodType? Type: type Base Class: String Form: Namespace: Interactive Docstring: instancemethod(function, instance, class) Create an instance method object. In [10]: m = types.MethodType(lambda self: 3, t, T) In [11]: t.m = m In [12]: t.m() Out[12]: 3 -- 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 James.w.Howard at gmail.com Tue Jul 24 15:21:54 2007 From: James.w.Howard at gmail.com (JamesHoward) Date: Tue, 24 Jul 2007 19:21:54 -0000 Subject: Good String Tokenizer Message-ID: <1185304914.344369.275770@q75g2000hsh.googlegroups.com> I have searched the board and noticed that there isn't really any sort of good implementation of a string tokenizer that will tokenize based on a custom set of tokens and return both the tokens and the parts between the tokens. For example, if I have the string: "Hello, World! How are you?" And my splitting points are comma, and exclamation point then I would expect to get back. ["Hello", ",", " World", "!", " How are you?"] Does anyone know of a tokenizer that will allow for this sort of use? Thanks in advance, Jim Howard From steve at holdenweb.com Mon Jul 30 13:23:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Jul 2007 13:23:54 -0400 Subject: Database objects? Persistence? Sql Server woes In-Reply-To: <11866779.post@talk.nabble.com> References: <11866779.post@talk.nabble.com> Message-ID: Mike Howarth wrote: > I've been having a few problems with connecting to SQL Server, initially I > was using dblib however found some problems with returning text fields > whereby all text fields were ignored and it bawked at multiline sql > statements. > > Having found these major stumbling blocks I've started using pymssql which > seems less flaky. One problem I've stumbled across is that I seem to reach > my max connections on the database fairly easily (given how my script was > written) and therefore have used the singleton pattern on my database > object. > > Great problem solved, or so I thought. > > Using the following code I'm finding that the Set is now also being enforced > as a singleton as well. > > class Set(Database,Product): > > def __init__(self, *args, **kw): > > Database.__init__(self) > Product.__init__(self) > > def dosomething(self): > cu = self.c.cursor() > > Having sat back and thought about it, its easy to understand why this is > occurring given I'm indicating that Set belongs to Database and therefore > this is a singleton as well. > > Being relatively new to Python I'm unsure on how to then go about using a > database object between each class. Can anyone advise me on how they > approach this, and whether there is a common approach to this? > If you want to share a database object between (instances of) several classes there are two easy ways. The absolute easiest is to create a database connection that's global to the module. References to the connection inside you other objects will then reference the global database connection. e.g.: conn = pymssql.connect(...) class Set: ... def dosomething(self): self.cu = conn.cursor() The other way is to pass the connection in to the object's __init__() method and save it as an instance variable so it can be used inside the instance's methods. e.g.: conn = pymssql.connect(...) class Set: def __init__(self, conn, ...): self.conn = conn ... def dosomething(self): self.cu = self.conn.cursor() 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 martin at see.sig.for.address Tue Jul 10 18:49:59 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Tue, 10 Jul 2007 23:49:59 +0100 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <1183665370.643503.157060@m36g2000hse.googlegroups.com> <5fh0imF3cjte7U1@mid.individual.net> Message-ID: Ilya Zakharevich wrote: > [A complimentary Cc of this posting was sent to > greg > ], who wrote in article <5fh0imF3cjte7U1 at mid.individual.net>: >> Ilya Zakharevich wrote: >>> In pedantic mode: negative timestamps make sense with Big Bang as the >>> epoch as well. (AFAIU, the current way of thinking is that it was >>> "just too hot" before the big bang, it is not that "there was >>> nothing".) >> If Stephen Hawking is right, the shape of the universe >> is such that there isn't any time "before" the big bang >> at all. It's like asking what's north of the North Pole. > > I do not remember any statement like this - even from 70s... Could > you provide a reference? There were conjectures about "initial > singularity", but I do not recollect them related to SH. > Its in "A Short History of Time". Sorry I can't quote chapter or page, but a friend borrowed my copy and lent me Dawkins "Climbing Mount Improbable" before vanishing, never to be seen since. Not an equal exchange: I preferred ASHOT to CMI. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From nospam.themindstorm at gmail.com Sat Jul 28 07:52:48 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Sat, 28 Jul 2007 11:52:48 +0000 (UTC) Subject: Pythonic way for missing dict keys References: <1185041243.323915.161230@x40g2000prg.googlegroups.com> <87lkd0eprj.fsf@pobox.com> Message-ID: jjl at pobox.com (John J. Lee) wrote in news:87lkd0eprj.fsf at pobox.com: > Alex Popescu writes: > >> Zentrader wrote in >> news:1185041243.323915.161230 @x40g2000prg.googlegroups.com: >> >>> On Jul 21, 7:48 am, Duncan Booth >>> wrote: >>> >>> [snip...] >>> >>> >>>>From the 2.6 PEP #361 (looks like dict.has_key is deprecated) >>> Python 3.0 compatability: ['compatibility'-->someone should use a >>> spell-checker for 'official' releases] >>> - warnings were added for the following builtins which no >>> longer exist in 3.0: >>> apply, callable, coerce, dict.has_key, execfile, >>> reduce, >>> reload >>> >> >> I see... what that document doesn't describe is the alternatives to >> be used. And I see in that list a couple of functions that are >> probably used a lot nowadays (callable, reduce, etc.). > > callable and reduce are rarely used, at least in code I've seen. I thought G would be using that function a lot. 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). > Certainly has_key will be > the most common of those listed above (but trivial to fix). dict.has_key(key) becomes key in dict (correct?) > apply > will be common in old code from the time of Python 1.5.2. I think there were some advises to not use apply. > execfile is > perhaps more common that callable (?) but again is really a "maybe 1 > call in a big program" sort of thing. What is the replacement for this one? tia, ./alex -- .w( the_mindstorm )p. From kyosohma at gmail.com Tue Jul 24 13:35:24 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 24 Jul 2007 10:35:24 -0700 Subject: wxPython - How to add sorting to a ListCtrl? In-Reply-To: <1185294074.410142.214140@22g2000hsm.googlegroups.com> References: <1185294074.410142.214140@22g2000hsm.googlegroups.com> Message-ID: <1185298524.840066.29250@o61g2000hsh.googlegroups.com> On Jul 24, 11:21 am, Robert Dailey wrote: > Hi, > > I have 3 columns in my list control, each with a different "type" of > data (for example, one column has names, the other has dates, etc). > Can anyone reference a tutorial for solving this issue? I've done my > share of googling to no avail. I need the user to be able to click any > of the column headers and sort the rows of data by that column in > ascending or descending order. > > Thanks for your time. Look at the wxPython demo. If you look at the list control's demo code, you'll see they're using a mixin called "ColumnSorterMixin" that will do what you need. The demo can be found here: http://www.wxpython.org/download.php Mike From a_jtim at bellsouth.net Fri Jul 27 12:04:35 2007 From: a_jtim at bellsouth.net (Tim Arnold) Date: Fri, 27 Jul 2007 09:04:35 -0700 Subject: encoding misunderstanding Message-ID: <1185552275.012403.85030@w3g2000hsg.googlegroups.com> Hi, I'm beginning to understand the encode/decode string methods, but I'd like confirmation that I'm still thinking in the right direction: I have a file of latin1 encoded text. Let's say I put one line of that file into a string variable 'tocline', as follows: tocline = 'Ficha Datos de p\xe9rdida AND acci\xf3n' import codecs tocFile = codecs.open('mytoc.htm','wb',encoding='utf8',errors='replace') tocline = tocline.decode('latin1','replace') tocFile.write(tocline) tocFile.close() What I think is that tocFile is wrapped to insure that anything written to it is in utf8 I decode the latin1 string into python's internal unicode encoding and that gets written out as utf8. Questions: what exactly is the tocline when it's read in with that \xe9 and \xed in the string? A latin1 encoded string? Is my method the right way to write such a line out to a file with utf8 encoding? If I read in the latin1 file using codecs.open(filename,encoding='latin1') and write out the utf8 file by opening with codecs.open(othername,encoding='utf8'), would I no longer have a problem -- I could just read in latin1 and write out utf8 with no more worries about encoding? thanks, --Tim p.s. sorry if you see this twice--my newsreader is flaky right now. From info at thegrantinstitute.com Sat Jul 21 03:45:29 2007 From: info at thegrantinstitute.com (Anthony Jones) Date: 21 Jul 2007 00:45:29 -0700 Subject: Professional Grant Proposal Writing Workshop (September 2007: Simon Fraser University) Message-ID: <20070721004528.A6208DECFDB28664@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jul 9 12:21:37 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 09 Jul 2007 18:21:37 +0200 Subject: list.append not working? In-Reply-To: <1183652223.493657.274290@g4g2000hsf.googlegroups.com> References: <1183651138.209079.37620@q75g2000hsh.googlegroups.com> <1183651638.584640.300240@a26g2000pre.googlegroups.com> <1183652223.493657.274290@g4g2000hsf.googlegroups.com> Message-ID: <4692607f$0$21721$426a34cc@news.free.fr> Hardy a ?crit : > On 5 Jul., 18:07, infidel wrote: >> On Jul 5, 8:58 am, Hardy wrote: >> >> >> >>> I experience a problem with append(). This is a part of my code: >>> for entity in temp: >>> md['module']= entity.addr.get('module') >>> md['id']=entity.addr.get('id') >>> md['type']=entity.addr.get('type') >>> #print md >>> mbusentities.append(md) >>> #print mbusentities >>> I want something like: [{'module': 'home', 'id': 123, 'type': 'core'}, >>> {'module': 'work', 'id': 456, 'type': 'core'}] >>> md is always correct, BUT:mbusentities is wrong. Length of >>> mbusentities is same of temp, so it appended everything. BUT: >>> mbusentities only shows the values of the last append: [{'module': >>> 'work', 'id': 456, 'type': 'core'}, {'module': 'work', 'id': 456, >>> 'type': 'core'}] >>> What's wrong? >> You're reusing the same "md" dictionary over and over, appending the >> same object to the list each time. So what you have is a list of >> references to the same dictionary. You need to set md = {} first >> thing each iteration. > > Thanks, that was my mistake, should take a break, getting code-blind :D > append = mbusentities.append for entity in temp: get = entity.addr.get append(dict((k, get(k)) for k in ('module', 'id', 'type'))) From bignose+hates-spam at benfinney.id.au Tue Jul 24 19:59:32 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 25 Jul 2007 09:59:32 +1000 Subject: datetime.time() class - How to pass it a time string? References: <1185297087.998644.53940@r34g2000hsd.googlegroups.com> Message-ID: <87hcntjqu3.fsf@benfinney.id.au> Neil Cerutti writes: > On 2007-07-24, Robert Dailey wrote: > > Hi, > > > > I have a string in the following format: > > > > "00:00:25.886411" > > > > I would like to pass this string into the datetime.time() class > > and have it parse the string and use the values. However, the > > __init__() method only takes integers (which means I'd be > > forced to parse the string myself). Does anyone know of a way I > > can make it use the string? Thanks. > > Consult the documentation about time.strptime (to start) and then > datetime.strptime (which refers back to the time.strptime docs, > in a rather unfortunate manner). Unfortunately 'strptime' also only seems to parse the components as integers: >>> import datetime >>> time_format = "%H:%M:%S" >>> time_value = datetime.datetime.strptime("09:45:31.064371", time_format) Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/_strptime.py", line 334, in strptime data_string[found.end():]) ValueError: unconverted data remains: .064371 The same thing happens with 'time.strptime'. So this isn't yet a solution for the OP. -- \ "Whatever you do will be insignificant, but it is very | `\ important that you do it." -- Mahatma Gandhi | _o__) | Ben Finney From wangyingqi at gmail.com Mon Jul 2 01:02:19 2007 From: wangyingqi at gmail.com (wang yingqi) Date: Mon, 2 Jul 2007 13:02:19 +0800 Subject: Is there a hadoop read/write module? Message-ID: <3233dd550707012202n30cc2e05ga898db4afbfc19e0@mail.gmail.com> hi all anyone knows? is there a hadoop read/write client module for python yet?or any projects in developing? thanks all. -- Regards. wangyingqi -------------- next part -------------- An HTML attachment was scrubbed... URL: From brfwk at turbomeca.fr Mon Jul 16 05:20:59 2007 From: brfwk at turbomeca.fr (Cox Lily) Date: Mon, 16 Jul 2007 11:20:59 +0200 Subject: Fwd: Message-ID: <469B387B.6010603@sti.com.br> -------------- next part -------------- A non-text attachment was scrubbed... Name: mail.pdf Type: application/pdf Size: 14083 bytes Desc: not available URL: From aafshar at gmail.com Wed Jul 25 07:38:37 2007 From: aafshar at gmail.com (Ali) Date: Wed, 25 Jul 2007 11:38:37 -0000 Subject: How to create a single executable of a Python program In-Reply-To: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> References: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> Message-ID: <1185363517.090457.205480@b79g2000hse.googlegroups.com> On Jul 25, 7:34 am, NicolasG wrote: > Dear fellows, > > I'm trying to create a executable file using py2exe . Unfortunately > along with the python executable file it also creates some other files > that are needed in order to the executable be able to run in a system > that doesn't have Python installed. Can some one guide me on how can I > merge all this files created by py2exe in a single exe file ? If I > have a python program that uses an image file I don't want this image > file to be exposed in the folder but only to be accessible through the > program flow.. > > Regards, > Nicolas. Hi, I know this is not exactly what you asked for, but if you want a single exe installer, then take a look at something like Inno Setup. http://www.jrsoftware.org/isinfo.php It will package all that stuff into a single exe which Windows users seem happy to click-and-install. I blogged the process I use here: http://unpythonic.blogspot.com/2007/07/pygtk-py2exe-and-inno-setup-for-single.html (though this has some PyGTK specifics) Ali From martin at v.loewis.de Fri Jul 6 04:51:07 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 06 Jul 2007 10:51:07 +0200 Subject: Writing a read only attribute In-Reply-To: References: Message-ID: <468E027B.4010107@v.loewis.de> > root = Tk() > > # save call address > original_tk_call = root.tk.call > > # disable tcl command execution (this is the read-only attribute) > root.tk.call = tk_dummy_call > > ... some code ... > > # restore tcl command execution > root.tk.call = original_tk_call > > > My goal is to make instances of Tkinter widgets without the effects of > commands directed to the tcl interpreter but preserving all effects at > python level. You can try to put in a fake Tk object into root.tk, as root.tk is not read-only. However, I would expect you run into other problems trying to do so. To change root.tk.call, you need to modify the implementation of the _tkinter module. Regards, Martin From no at spam.com Thu Jul 26 21:18:38 2007 From: no at spam.com (Farshid Lashkari) Date: Thu, 26 Jul 2007 18:18:38 -0700 Subject: Another C API Question In-Reply-To: <1185498383.333248.225360@19g2000hsx.googlegroups.com> References: <1185498383.333248.225360@19g2000hsx.googlegroups.com> Message-ID: beginner wrote: > I know obj is a number, but I do not know the exact type. How can I > convert it to double without writing a giant switch() that exhausts > every single type of number? Try using the PyFloat_AsDouble(...) function, it should be able to convert an object to a double, as long as the object implements the __float__ method. From theller at ctypes.org Thu Jul 5 07:59:02 2007 From: theller at ctypes.org (Thomas Heller) Date: Thu, 05 Jul 2007 13:59:02 +0200 Subject: The best platform and editor for Python In-Reply-To: References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> Message-ID: QOTW? Gregor Horvath schrieb: > That's a property of open source projects. > Features nobody really needs are not implemented. > > Gregor From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jul 16 03:55:35 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 16 Jul 2007 09:55:35 +0200 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: <4697d9f0$0$7614$426a74cc@news.free.fr> Message-ID: <469b2477$0$11769$426a74cc@news.free.fr> Wayne Brehaut a ?crit : > On Sat, 14 Jul 2007 06:01:56 +0200, Bruno Desthuilliers > wrote: > >> Chris Carlen a ?crit : >>> Hi: >>> >>> From what I've read of OOP, I don't get it. I have also found some >>> articles profoundly critical of OOP. I tend to relate to these articles. >>> > > === 8< === > >>> Hence, being a hardware designer rather than a computer scientist, I am >>> conditioned to think like a machine. I think this is the main reason >>> why OOP has always repelled me. >> OTOH, OO is about machines - at least as conceveid by Alan Key, who >> invented the term and most of the concept. According to him, each object >> is a (simulation of) a small machine. > > Oh you young'uns, not versed in The Ancient Lore, but filled with > self-serving propaganda from Xerox PARC, Alan Kay, and Smalltalk > adherents everywhere! Not feeling concerned. (snip pro-simula/anti-Xerox propaganda). From ivlenin at gmail.com Sun Jul 22 18:47:14 2007 From: ivlenin at gmail.com (I V) Date: Sun, 22 Jul 2007 22:47:14 GMT Subject: split on NO-BREAK SPACE References: Message-ID: On Sun, 22 Jul 2007 21:13:02 +0200, Peter Kleiweg wrote: > Here is another "space": > > >>> u'\uFEFF'.isspace() > False > > isspace() is inconsistent Well, U+00A0 is in the category "Separator, Space" while U+FEFF is in the category "Other, Format", so it doesn't seem unreasonable that one is treated as a space and the other isn't. From NikitaTheSpider at gmail.com Wed Jul 11 16:35:25 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Wed, 11 Jul 2007 16:35:25 -0400 Subject: Problem with Python's "robots.txt" file parser in module robotparser References: <0T7li.5316$rL1.2716@newssvr19.news.prodigy.net> Message-ID: In article <0T7li.5316$rL1.2716 at newssvr19.news.prodigy.net>, John Nagle wrote: > Python's "robots.txt" file parser may be misinterpreting a > special case. Given a robots.txt file like this: > > User-agent: * > Disallow: // > Disallow: /account/registration > Disallow: /account/mypro > Disallow: /account/myint > ... > > the python library "robotparser.RobotFileParser()" considers all pages of the > site to be disallowed. Apparently "Disallow: //" is being interpreted as > "Disallow: /". Even the home page of the site is locked out. This may be > incorrect. > > This is the robots.txt file for "http://ibm.com". Hi John, Are you sure you're not confusing your sites? The robots.txt file at www.ibm.com contains the double slashed path. The robots.txt file at ibm.com is different and contains this which would explain why you think all URLs are denied: User-agent: * Disallow: / I don't see the bug to which you're referring: >>> import robotparser >>> r = robotparser.RobotFileParser() >>> r.set_url("http://www.ibm.com/robots.txt") >>> r.read() >>> r.can_fetch("WhateverBot", "http://www.ibm.com/foo.html") 1 >>> r.can_fetch("WhateverBot", "http://www.ibm.com//foo.html") 0 >>> I'll use this opportunity to shamelessly plug an alternate robots.txt parser that I wrote to address some small bugs in the parser in the standard library. http://NikitaTheSpider.com/python/rerp/ Cheers -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From dw at botanicus.net Sat Jul 28 18:57:15 2007 From: dw at botanicus.net (David Wilson) Date: Sat, 28 Jul 2007 23:57:15 +0100 Subject: this must be a stupid question ... In-Reply-To: <849ad$46abb218$d443bb3a$21452@news.speedlinq.nl> References: <849ad$46abb218$d443bb3a$21452@news.speedlinq.nl> Message-ID: <98edab2e0707281557s7062dbbidcd07c7aeab59956@mail.gmail.com> On 28/07/07, Stef Mientki wrote: > but I can;t find the answer ;-) > > As searching for the '$' sign doesn't work well in the help files, > I can not find out, where is the '$' sign used for. > > If I try to use it in names, > I get a compiler error, > so it probably has some special meaning. Hi Stef, It has no special meaning in the Python language, beyond being invalid for use in identifiers. I believe there is a new string formatting module which interprets it when it is part of a format string, but nothing in the core language. If you look at the language grammar, you can see why this is an error http://docs.python.org/ref/identifiers.html David. > > thanks, > Stef Mientki > -- > http://mail.python.org/mailman/listinfo/python-list > From uclamathguy at gmail.com Wed Jul 25 19:54:23 2007 From: uclamathguy at gmail.com (StatsJunkie) Date: Wed, 25 Jul 2007 16:54:23 -0700 (PDT) Subject: Reading a Directory of Emails - Problems In-Reply-To: References: <72fc09510707241038s367aaa3bqd6a221074291d3d@mail.gmail.com> Message-ID: <11801990.post@talk.nabble.com> Thanks. I tried that, but absolutely nothing is printed to the screen. This is the code I am trying to use. mbox = mailbox.MHMailbox("stat_inbox.mbox/Messages",email.message_from_file) for msg in mbox: print(msg) #just to see if anything is happening Which mailbox type did you use? Perhaps MHMailbox in the wrong one...? Joshua J. Kugler-2 wrote: > > On Tuesday 24 July 2007 09:38, Ryan Rosario wrote: > >> Hi, >> >> I have a directory that contains a bunch of email messages and I would >> like to parse them using the email and mailbox packages. The emails were >> exported from Apple Mail. From what I gather, I need to use MHMailbox, >> but >> I can't get it to do anything useful and I cannot find any examples of >> how >> to use this particular mailbox type. >> > >> >> I get an error. AttributeError: MHMailbox instance has no attribute >> 'keys'. Yet this works when using PortableUnixMailbox (on an mbox file, >> not a directory of emails). > > I fought with this a while back. It seems it is nested one level lower. > You might have to get at the message by doing something like > > real_message = msg[0] > > Instead of print msg.keys(), just do a 'print msg' and see what data > structure is returned. That will tell you a lot. > > 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 > -- View this message in context: http://www.nabble.com/Reading-a-Directory-of-Emails---Problems-tf4137576.html#a11801990 Sent from the Python - python-list mailing list archive at Nabble.com. From steve at holdenweb.com Fri Jul 27 20:26:32 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 27 Jul 2007 20:26:32 -0400 Subject: Factory pattern again In-Reply-To: <1185559449.103726.75520@e9g2000prf.googlegroups.com> References: <11825158.post@talk.nabble.com> <46a9c21f$0$18765$426a74cc@news.free.fr> <1185559449.103726.75520@e9g2000prf.googlegroups.com> Message-ID: cunheise at yahoo.com.cn wrote: > first you need find the bottleneck of your script db or function > if the bottleneck is db > 1. which db do you use do you optimize the db from read > 2. the sql you write do not use any index "maybe select code, type > from products where type = 'I' or type = 'S' will help" and you need > create index on type field maybe you need set limit 2000 to sql depend > on your requirement > Whether a relational database is indexed or not the SQL to retrieve information from it will be exactly the same - the whole point if indexing is that it represents a change to the physical schema that improves retrieval efficiency without altering the logical schema. Mike stated quite clearly "the db is normalized and indexes exist". 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 Jul 9 10:54:56 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 09 Jul 2007 07:54:56 -0700 Subject: Tool for finding external dependencies In-Reply-To: <1183991251.354349.326520@e16g2000pri.googlegroups.com> References: <1183945183.147231.120180@z28g2000prd.googlegroups.com> <1183990671.337753.106370@k79g2000hse.googlegroups.com> <1183991251.354349.326520@e16g2000pri.googlegroups.com> Message-ID: <1183992896.381070.62280@n60g2000hse.googlegroups.com> On Jul 9, 9:27 am, Rob Cakebread wrote: > On Jul 9, 7:17 am, kyoso... at gmail.com wrote: > > > > > Recently I ran into some debugging issues and the freeware app > > "Dependency Walker" was suggested to me. I still haven't used it much > > since I only got it last Friday, but it looks promising:http://www.dependencywalker.com > > > Mike > > Thanks Mike, but I'm just trying to determine Python imports, like: > > $ pylint g_pypi > > [snip lots of other tests which take a lonnnnnng time] > > External dependencies > --------------------- > :: > > configobj (g_pypi.config) > portage (g_pypi.enamer,g_pypi.portage_utils,g_pypi.cli) > pkg_resources (g_pypi.cli,g_pypi.ebuild) > yolk > \-pypi (g_pypi.cli) > \-setuptools_support (g_pypi.cli) > \-yolklib (g_pypi.cli) > gentoolkit (g_pypi.portage_utils) > pygments (g_pypi.ebuild) > \-lexers (g_pypi.ebuild) > \-formatters (g_pypi.ebuild) > Cheetah > \-Template (g_pypi.ebuild) Hmmm...I also use GUI2Exe, which may help you too. It'll list "missing modules" and binary dependencies. It's basically a GUI interface to py2exe: http://xoomer.alice.it/infinity77/eng/GUI2Exe.html This looks interesting, but I've never used it: http://www.tarind.com/depgraph.html Finally, here's some more info on modulefinder: http://svn.python.org/projects/python/trunk/Lib/modulefinder.py Looks like you run modulefinder like this: mod = modulefinder.ModuleFinder() mod.run_script(path/to/python_script.py) mod.report() Mike From bscrivener42 at gmail.com Sun Jul 15 14:45:38 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Sun, 15 Jul 2007 18:45:38 -0000 Subject: Python and Tkinter Primer/Tutorial? In-Reply-To: References: Message-ID: <1184525138.178668.274570@22g2000hsm.googlegroups.com> On Jul 15, 9:46 am, "W. Watson" wrote: > Is there a primer out there on these two items? I have the Python tutorial, > but would like either a Tkinter tutorial/primer to supplement it, or a > primer/tutorial that addresses both. http://www.freenetpages.co.uk/hp/alan.gauld/tutgui.htm rd From nuno at salgado.ws Fri Jul 13 06:38:26 2007 From: nuno at salgado.ws (nuno at salgado.ws) Date: Fri, 13 Jul 2007 10:38:26 -0000 Subject: diferent answers with isalpha() In-Reply-To: <1184303234.474610.186270@e9g2000prf.googlegroups.com> References: <1184285142.547758.57760@22g2000hsm.googlegroups.com> <1184303234.474610.186270@e9g2000prf.googlegroups.com> Message-ID: <1184323106.838686.89970@q75g2000hsh.googlegroups.com> On Jul 13, 6:07 am, Jyotirmoy Bhattacharya wrote: > On Jul 13, 5:05 am, n... at salgado.ws wrote: > > > In Idle when I do print '?'.isalpha() I get True. When I make and > > execute a script file with the same code I get False. > > > Why do I have diferent answers ? > > Non-ASCII characters in ordinary (8-bit) strings have all kinds of > strangeness. First, the answer of isalpha() and friends depends on the > current locale. By default, Python uses the "C" locale where the > alphabetic characters are a-zA-z only. To set the locale to whatever > is the OS setting for the current user, put this near the beginning of > your script: > > import locale > locale.setlocale(locale.LC_ALL,'') > > Apparently IDLE does this for you. Hence the discrepancy you noted. > > Second, there is the matter of encoding. String literals like the one > you used in your example are stored in whatever encoding your text > editor chose to store your program in. If it doesn't match the > encoding using by the current locale, once again the program fails. > > As I see it, the only way to properly handle characters outside the > ASCII set is to use Unicode strings. Jyotirmoy, You are right. Thank you for your information. I will follow your advice but it gets me into another problem with string.maketrans/translate that I can't solve. From adam at volition-inc.com Wed Jul 11 18:14:18 2007 From: adam at volition-inc.com (Adam Pletcher) Date: Wed, 11 Jul 2007 17:14:18 -0500 Subject: Time A Script In-Reply-To: <024b01c7c310$fdecb4f0$f9c61ed0$@rawlins@thinkbluemedia.co.uk> References: <024b01c7c310$fdecb4f0$f9c61ed0$@rawlins@thinkbluemedia.co.uk> Message-ID: <893A44FF792E904A97B7515CE34191460102D78C@volimxs01.thqinc.com> Try: --- import time start_time = time.time() run_time = time.time() - start_time print 'Run time: %f seconds' % run_time --- Also have a look at the timeit module for more timing functionality. - Adam ________________________________ From: python-list-bounces+adam=volition-inc.com at python.org [mailto:python-list-bounces+adam=volition-inc.com at python.org] On Behalf Of Robert Rawlins - Think Blue Sent: Tuesday, July 10, 2007 11:40 AM To: python-list at python.org Subject: Time A Script Hello Guys, What's the best way to time how long it takes a script to run, from top to bottom and then have it print that execution time at the end? Thanks guys, Rob From nospam at nospam.com Sat Jul 21 22:09:08 2007 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 22 Jul 2007 04:09:08 +0200 Subject: [2.5] Regex doesn't support MULTILINE? Message-ID: Hello I'm trying to extract information from a web page using the Re module, but it doesn't seem to support MULTILINE: ============= import re #NO CRLF : works response = "Blablabla" #CRLF : doesn't work response = "Blablabla\r\n" pattern = "Bla.+?" p = re.compile(pattern,re.IGNORECASE|re.MULTILINE) m = p.search(response) if m: print m.group(1) else: print "Not found" ============= Do I need to add something else to have Re work as intended? Thank you. From superflit at gmail.com Wed Jul 11 12:52:32 2007 From: superflit at gmail.com (flit) Date: Wed, 11 Jul 2007 16:52:32 -0000 Subject: Simple search and Display system, no need for db? In-Reply-To: <5fjab0F3d2eqeU1@mid.uni-berlin.de> References: <1184119048.302574.141810@w3g2000hsg.googlegroups.com> <5fjab0F3d2eqeU1@mid.uni-berlin.de> Message-ID: <1184172752.996885.253340@m3g2000hsh.googlegroups.com> On Jul 11, 3:06 am, Marc 'BlackJack' Rintsch wrote: > If the data is not too large, simple text files would do. Maybe in CSV > format. Either with building and department as columns in the files or > coded into the file name or path. That seems to be a good idea, but I am afraid the web hosting does not have the csv modules.. (maybe if I do an split?) From mensanator at aol.com Thu Jul 26 14:02:26 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Thu, 26 Jul 2007 11:02:26 -0700 Subject: From D In-Reply-To: <87zm1jhecf.fsf@benfinney.id.au> References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> <87ps2ghtd7.fsf@benfinney.id.au> <1185412639.075218.186290@z24g2000prh.googlegroups.com> <1185426066.162458.187050@z28g2000prd.googlegroups.com> <87zm1jhecf.fsf@benfinney.id.au> Message-ID: <1185472946.945512.249830@w3g2000hsg.googlegroups.com> On Jul 26, 1:24 am, Ben Finney wrote: > "mensana... at aol.com" writes: > > On Jul 25, 9:04?pm, Steven D'Aprano > > wrote: > > Why does it make no sense? Have you never had to scrape a web page > > or read a CSV file? > > Again, unrelated to the way the Python compiler syntactically treats > the source code. That's what I was enquiring about. So, just as >>> int('123' '456') 123456 is not an error, the proposal is that >>> a = 123 456 SyntaxError: invalid syntax will not be an error either. Yet, >>> a = int('123 456') Traceback (most recent call last): File "", line 1, in a = int('123 456') ValueError: invalid literal for int() with base 10: '123 456' will still be an error. Just trying to be clear on this. Wouldn't want that syntax behavior to carry over into run-time. > > > So this proposal would only apply to string literals at compile > > time, not running programs? > > Exactly the same way that it works for string literals in source code: > once the source code is compiled, the literal is indistinguishable > from the same value written a different way. > > > And I want the same error to occur if my CSV parser tries to convert > > '123 456' into a single number. I don't want it to assume the > > number is '123456'. > > Once again, this is a discussion about Python syntax, not the > behaviour of the csv module. Who said I was using the csv module? > > -- > \ "I always had a repulsive need to be something more than | > `\ human." -- David Bowie | > _o__) | > Ben Finney From paddy3118 at googlemail.com Thu Jul 12 09:08:30 2007 From: paddy3118 at googlemail.com (Paddy) Date: Thu, 12 Jul 2007 13:08:30 -0000 Subject: New release: Crunchy 0.9 In-Reply-To: <1184024260.074366.33120@n2g2000hse.googlegroups.com> References: <1184024260.074366.33120@n2g2000hse.googlegroups.com> Message-ID: <1184245710.690396.37890@m3g2000hsh.googlegroups.com> On Jul 10, 12:37 am, Andr? wrote: > Crunchy 0.9 has been released. It is available athttp://code.google.com/p/crunchy > > What is Crunchy? > > Crunchy is a an application that transforms html Python tutorials into > interactive session viewed within a browser. We are not aware of any > other application (in any language) similar to Crunchy. Currently > Crunchy has only been fully tested with Firefox; we know that some > browsers simply don't work with it. Crunchy should work with all > operating systems - it has been tested fairly extensively on Linux, > Windows and Mac OS. > > What is new in this release? > > Crunchy has been rewritten from scratch from the previous version > (0.8.2), to use a custom plugin architecture. This makes easier to > extend and add new functionality. Rather than list the differences > with the old release, it is easier to list the essential features of > this new version. > > 1. Crunchy can work best with specially marked-up html tutorials. > However, it can now work with any html tutorials - including the > official Python tutorial on the python.org site. Html pages can be > loaded locally or remotely from anywhere on the Internet. Crunchy > uses a combination of Elementtree and BeautifulSoup to process html > pages. Non W3C-compliant pages can be handled, but the visual > appearance is not guaranteed to reproduce that normally seen using a > browser. > > 2. Crunchy can insert a number of Python interpreters inside a web > page. In the default mode, it does that whenever it encounters an > html
 element which is assumed to contain some Python code.
> These interpreters can either share a common environment (e.g. modules
> imported in one of them are known in the other) or be isolated one
> from another.
>
> 3. Crunchy adds automatic css styling to the Python code -  you can
> look at the official Python tutorial using your browser (all Python
> code in blue) and compare with what Crunchy displays to give you a
> good idea.
>
> 4. Instead of inserting an interpreter, Crunchy can insert a code
> editor that can be used to modify the Python code on the page and
> execute it.  The editor can be toggled to become a fairly decent
> syntax aware editor that can save and load files.
>
> 5. Crunchy has a "doctest" feature where the code inside the 
 is
> taken to be the result
> of an interpreter session and the user has to write the code so as to
> make the interpreter session valid; this is useful in a teaching
> environment. Messages from the Crunchy's doctest are "friendlier" for
> Python beginners than the usual tracebacks.
>
> 6. Crunchy has a small graphics library that can be imported, either
> inside an editor or an interpreter, to produce simple graphics (even
> animations!) inside the browser.
>
> 7. For the user that needs better quality graphics, Crunchy supports
> programs (such as matplotlib) that can create image files; by
> executing the code, the image produced is loaded inside the browser
> window.  In this capacity, Crunchy could be used as a front end for
> libraries such as matplotlib.
>
> 8. Crunchy supports code execution of files as separate processes,
> making it suitable to launch gui based application from the browser
> window.
>
> 9. Crunchy's interpreter has an interactive "help" feature like many
> python-aware IDEs.
>
> 10. Crunchy includes a fairly comprehensive tutorial on its own use,
> as well as a reference for tutorial writers that want to make their
> tutorials "crunchy-friendlier".
>
> 11. As a security feature, crunchy strips all pre-existing javascript
> code from an html page before displaying it inside the browser window.
>
> Bug reports, comments and suggestions are always welcome.
>
> Andr? Roberge, for the Crunchy team.

Fanmail:
  http://paddy3118.blogspot.com/2007/07/ive-been-crunched.html

- Paddy



From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Tue Jul 24 04:05:06 2007
From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
Date: Tue, 24 Jul 2007 10:05:06 +0200
Subject: classmethod & staticmethod
In-Reply-To: <1185247145.678362.75150@i38g2000prf.googlegroups.com>
References: <1185247145.678362.75150@i38g2000prf.googlegroups.com>
Message-ID: <46a5b2ad$0$18903$426a74cc@news.free.fr>

james_027 a ?crit :
> hi,
> 
> python's staticmethod is the equivalent of java staticmethod right?

IIRC, yes. A 'staticmethod' is in fact nothing more than a function 
attached to a class, and which can be called on the class or an instance 
of. Note that since Python supports modules and functions, staticmethods 
are of little practical use.

> with classmethod, I can call the method without the need for creating
> an instance right? since the difference between the two is that
> classmethod receives the class itself as implicti first argument. 

Yes.

> From
> my understanding classmethod are for dealing with class attributes?

Not necessarily - you can access class attributes from within an 
instance method (but obviously a classmethod cannot access instance 
attributes).

> Can somebody teach me the real use of classmethod & staticmethod?

The 'real' use is (are) the one(s) you'll find. FWIW, I use 
staticmethods for helper functions that don't need access to the class 
or instance but are too specific to a class to be of any use as plain 
functions. Which is not a very frequent case. Classmethods are more 
usefull - mostly as alternate constructors or utility methods for an 
alternate constructor, but there are other possible uses (sorry, I have 
no concrete example at hand).


From andre.roberge at gmail.com  Tue Jul 10 05:51:41 2007
From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=)
Date: Tue, 10 Jul 2007 09:51:41 -0000
Subject: "Empty" text
In-Reply-To: <469147b8$1@griseus.its.uu.se>
References: <469147b8$1@griseus.its.uu.se>
Message-ID: <1184061101.493471.151310@22g2000hsm.googlegroups.com>

On Jul 8, 5:23 pm, Jan Danielsson  wrote:
> Hello all,
>
>    I'm using mod_python+ElementTree to build XHTML pages. But I stumbled
> across this problem:
>
> --------------------
> def foo(req, desc = None):
>
>    ...
>
>    tr = ET.SubElement(tbl, "tr")
>    th = ET.SubElement(tr, "th")
>    th.text = "Description"
>    td = ET.SubElement(tr, "td")
>    ta = ET.SubElement(td, "textarea", name="desc", rows="8",
> cols="64")
>    if desc is None:
>       desc = ''
>    ta.text = desc
> --------------------
>
>    The problem is that this generates the following code:
>
>           
>             Description
>             
>               
>
>    I understand the opitmization ElementTree is performing; but it seems
> there are cases when it is not the proper thing to do. Is it possible to
>  force ElementTree to output the XHTML code I need it to?
>
> --
> Kind regards,
> Jan Danielsson

I ran into the same problem and a workaround I found was to use either
ta.text = " "   or ta.text = "\n" instead of ta.text = ''.
For my application, it did the right thing; your mileage may vary.

Andr?



From nogradi at gmail.com  Sun Jul 15 05:41:49 2007
From: nogradi at gmail.com (Daniel Nogradi)
Date: Sun, 15 Jul 2007 11:41:49 +0200
Subject: standalone module
In-Reply-To: <142168.64744.qm@web54501.mail.re2.yahoo.com>
References: <142168.64744.qm@web54501.mail.re2.yahoo.com>
Message-ID: <5f56302b0707150241q5a15b031jfdd7db38623e2ca5@mail.gmail.com>

> I want to create a standalone program ( an exe file ) from my python files
> which works on Windows and Linux.
>
> Could you please tell me how to do that?


The same executable should work on both linux and windows? Not
possible. But see:

http://mail.python.org/pipermail/python-list/2007-July/448658.html


From kay.schluehr at gmx.net  Thu Jul 26 15:46:09 2007
From: kay.schluehr at gmx.net (Kay Schluehr)
Date: Thu, 26 Jul 2007 12:46:09 -0700
Subject: Fwd: I am giving up perl because of assholes on clpm -- switching
	to Python
In-Reply-To: 
References: <4b490f2f0707260810qe4a410co366291a6dccd4f01@mail.gmail.com>
	
Message-ID: <1185479169.722588.151630@d55g2000hsg.googlegroups.com>

On Jul 26, 8:18 pm, jed drury  wrote:
> Hey, Perl's new motto is "There is more than 1 way to
> be an ASSHOLE!"

Do you think the unique asshole constraint feels more natural? I tend
to agree.



From dstromberg at datallegro.com  Wed Jul 11 20:56:21 2007
From: dstromberg at datallegro.com (Dan Stromberg - Datallegro)
Date: Thu, 12 Jul 2007 00:56:21 GMT
Subject: bash-style pipes in python?
Message-ID: 


I'm constantly flipping back and forth between bash and python.

Sometimes, I'll start a program in one, and end up recoding in the
other, or including a bunch of python inside my bash scripts, or snippets
of bash in my python.

But what if python had more of the power of bash-style pipes?  I might not
need to flip back and forth so much.  I could code almost entirely in python.

The kind of thing I do over and over in bash looks like:

	#!/usr/bin/env bash

	# exit on errors, like python. Exit on undefind variables, like python.
	set -eu

	# give the true/false value of the last false command in a pipeline
	# not the true/false value of the lat command in the pipeline - like
	# nothing I've seen
	set -o pipefail

	# save output in "output", but only echo it to the screen if the command fails
	if ! output=$(foo | bar 2>&1)
	then
		echo "$0: foo | bar failed" 1>&2
		echo "$output" 1>&2
		exit 1
	fi

Sometimes I use $PIPESTATUS too, but not that much.

I'm aware that python has a variety of pipe handling support in its
standard library.

But is there a similarly-simple way already, in python, of hooking the stdout of
process foo to the stdin of process bar, saving the stdout and errors from both
in a variable, and still having convenient access to process exit values?

Would it be possible to overload | (pipe) in python to have the same behavior as in
bash?

I could deal with slightly more cumbersome syntax, like:

	(stdout, stderrs, exit_status) = proc('foo') | proc('bar')

...if the basic semantics were there.

How about it?  Has someone already done this?



From gagsl-py2 at yahoo.com.ar  Sun Jul 22 04:34:17 2007
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Sun, 22 Jul 2007 05:34:17 -0300
Subject: [2.5] Regex doesn't support MULTILINE?
References: 
	
	
Message-ID: 

En Sun, 22 Jul 2007 01:56:32 -0300, Gilles Ganault   
escribi?:

> Incidently, as far as using Re alone is concerned, it appears that
> re.MULTILINE isn't enough to get Re to include newlines: re.DOTLINE
> must be added.
>
> Problem is, when I add re.DOTLINE, the search takes less than a second
> for a 500KB file... and about 1mn30 for a file that's 1MB, with both
> files holding similar contents.
>
> Why such a huge difference in performance?
>
> pattern = "(\d+:\d+).*?"

Try to avoid using ".*" and ".+" (even the non greedy forms); in this  
case, I think you want the scan to stop when it reaches the ending   
or any other tag, so use: [^<]* instead.

BTW, better to use a raw string to represent the pattern: pattern =  
r"...\d+..."

-- 
Gabriel Genellina



From JHoover at fbi.gov  Sun Jul 22 14:24:05 2007
From: JHoover at fbi.gov (Gordon Airporte)
Date: Sun, 22 Jul 2007 14:24:05 -0400
Subject: Where is the collections module?
Message-ID: 

I was going to try tweaking defaultdict, but I can't for the life of me 
find where the collections module or its structures are defined. Python 2.5.


From mark.dufour at gmail.com  Sun Jul  1 13:09:43 2007
From: mark.dufour at gmail.com (Mark Dufour)
Date: Sun, 1 Jul 2007 19:09:43 +0200
Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed
In-Reply-To: 
References: <8180ef690703310255q55572efaqc512b968504e2c1b@mail.gmail.com>
	<8180ef690706290348m4418d226l482e9a36474b3697@mail.gmail.com>
	
Message-ID: <8180ef690707011009l3b700c30l6643f0ea077b7bd3@mail.gmail.com>

hi felix,

On 6/29/07, felix seltzer  wrote:
> does this project include support for pygtk type GUI's?

No, it won't work for arbitrary python programs. Shed Skin is
currently limited to smallish programs (up to a few hundred lines),
that only use a few basic modules (random, math, string, and a few
others) and are written in the static subset of Python that Shed Skin
supports.

A serious pygtk program would probably be too large and too dynamic to
compile directly.  Instead, you'd typically move some speed-critical
functionality to a separate module, and compile this into an extension
module or separate program.

Look at Shed Skin as something that allows you to write fast extension
modules in pure Python, not as something that can convert arbitrary
Python programs.


Thanks,
Mark Dufour.
-- 
"One of my most productive days was throwing away 1000 lines of code"
- Ken Thompson


From pruebauno at latinmail.com  Tue Jul 17 14:29:19 2007
From: pruebauno at latinmail.com (pruebauno at latinmail.com)
Date: Tue, 17 Jul 2007 11:29:19 -0700
Subject: Dict Help
In-Reply-To: 
References: 
	
	<015101c7c718$e207e820$a617b860$@rawlins@thinkbluemedia.co.uk>
	
Message-ID: <1184696959.817430.144140@j4g2000prf.googlegroups.com>

On Jul 17, 5:57 am, "Robert Rawlins - Think Blue"
 wrote:
> Morning Gabriel,
>
> I'm looking for a little more advice on this dictionary/list to
> defaultdict/set conversion that we were talking about, there were a few
> things I was looking to clarify. Firstly, what is the difference between a
> standard dict and a default dict? Is it purely a performance issue?
>
> This dict is likely to grow pretty large and is read/written on a very
> regular basis so the better performing one is going to work best for me.
> Also, am I still able to iterate over a set in the same way I can a list?
>
> Here is an example of my add function at the moment, how can that be
> converted to a defaultdict/set instead of the dict/list approach?
>
>         self.History = {}
>
>         def addHistory(self, address, media):
>                 if address not in self.History:
>                         self.History[address] = []
>
>                 self.History[address].append(media)
>
> Thanks Gabriel,
>
> Rob
>
1. defaultdict just sets a dictionary entry to a default if the key
does not exist. In other words if you replace the first line with:

self.History=defaultdict(list) #replace list by set if you want

you can get rid of:

if address not in self.History: self.History[address]=[]

because that then happens automatically. Otherwise it works exactly
like a regular dictionary.

2. You can iterate over a set the same way you iterate over a list.

3. Change the following lines:

line 5 self.History[address] = set() #instead of [] (list)
line 7 self.History[address].add(media) #set uses add instead of
append



From hg at nospam.org  Tue Jul 17 16:28:41 2007
From: hg at nospam.org (hg)
Date: Tue, 17 Jul 2007 15:28:41 -0500
Subject: Can a low-level programmer learn OOP?
References: 
Message-ID: 

Chris Carlen wrote:

> Hi:
> 
>  From what I've read of OOP, I don't get it.  I have also found some
> articles profoundly critical of OOP.  I tend to relate to these articles.
> 
> However, those articles were no more objective than the descriptions of
> OOP I've read in making a case.  Ie., what objective
> data/studies/research indicates that a particular problem can be solved
> more quickly by the programmer, or that the solution is more efficient
> in execution time/memory usage when implemented via OOP vs. procedural
> programming?
> 
> The problem for me is that I've programmed extensively in C and .asm on
> PC DOS way back in 1988.  Then didn't program for nearly 10 years during
> which time OOP was popularized.  Starting in 1999 I got back into
> programming, but the high-level-ness of PC programming and the
> completely foreign language of OOP repelled me.  My work was in analog
> and digital electronics hardware design, so naturally I started working
> with microcontrollers in .asm and C.  Most of my work involves low-level
> signal conditioning and real-time control algorithms, so C is about as
> high-level as one can go without seriously loosing efficiency.  The
> close-to-the-machine-ness of C is ideal here.  This is a realm that I
> truly enjoy and am comfortable with.
> 
> Hence, being a hardware designer rather than a computer scientist, I am
> conditioned to think like a machine.  I think this is the main reason
> why OOP has always repelled me.
> 
> Perhaps the only thing that may have clicked regarding OOP is that in
> certain cases I might prefer a higher-level approach to tasks which
> involve dynamic memory allocation.  If I don't need the execution
> efficiency of C, then OOP might produce working results faster by not
> having to worry about the details of memory management, pointers, etc.
> 
> But I wonder if the OOP programmers spend as much time creating classes
> and trying to organize everything into the OOP paradigm as the C
> programmer spends just writing the code?
> 
> Ultimately I don't care what the *name* is for how I program.  I just
> need to produce results.  So that leads back to objectivity.  I have a
> problem to solve, and I want to find a solution that is as quick as
> possible to learn and implement.
> 
> Problem:
> 
> 1.  How to most easily learn to write simple PC GUI programs that will
> send data to remote embedded devices via serial comms, and perhaps
> incorporate some basic (x,y) type graphics display and manipulation
> (simple drawing program).  Data may result from user GUI input, or from
> parsing a text config file.  Solution need not be efficient in machine
> resource utilization.  Emphasis is on quickness with which programmer
> can learn and implement solution.
> 
> 2.  Must be cross-platform: Linux + Windows.  This factor can have a big
> impact on whether it is necessary to learn a new language, or stick with
> C.  If my platform was only Linux I could just learn GTK and be done
> with it.  I wouldn't be here in that case.
> 
> Possible solutions:
> 
> Form 1:  Use C and choose a library that will enable cross-platform GUI
> development.
> 
> Pro:  Don't have to learn new language.
> Con:  Probably will have difficulty with cross-platform implementation
> of serial comms.  This will probably need to be done twice.  This will
> waste time.
> 
> Form 2:  Use Python and PySerial and TkInter or wxWidgets.
> 
> Pro:  Cross-platform goal will likely be achieved fully.  Have a
> programmer nearby with extensive experience who can help.
> Con:  Must learn new language and library.  Must possibly learn a
> completely new way of thinking (OOP) not just a new language syntax.
> This might be difficult.
> 
> Form 3:  Use LabVIEW
> 
> Pro:  I think that the cross-platform goal can be met.
> Con:  Expensive.  I would prefer to use an Open Source solution.  But
> that isn't as important as the $$$.  I have also generally found the 2D
> diagrammatical programming language of "G" as repelling as OOP.  I
> suspect that it may take as much time to learn LabVIEW as Python.  In
> that case the time spent on Python might be better spent since I would
> be learning something foundational as opposed to basically just learning
> how to negotiate someone's proprietary environment and drivers.
> 
> 
> Comments appreciated.
> 
> 
> --
> Good day!
> 
> ________________________________________
> Christopher R. Carlen
> Principal Laser&Electronics Technologist
> Sandia National Laboratories CA USA
> crcarleRemoveThis at BOGUSsandia.gov
> NOTE, delete texts: "RemoveThis" and
> "BOGUS" from email address to reply.


yes, maybe you should look at UML first.

hg




From nazgul at jsbsystems.com  Sun Jul 29 17:29:48 2007
From: nazgul at jsbsystems.com (nazgul)
Date: Sun, 29 Jul 2007 16:29:48 -0500
Subject: Compiling 2.5.1 on OpenBSD 4.1
References: 
	<46AC1B91.3070706@v.loewis.de>
	
	<46ACC344.1020701@v.loewis.de>
Message-ID: 

=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=  wrote
in news:46ACC344.1020701 at v.loewis.de: 

> 
> It may work, but I don't like it. Can you please try this one instead,
> and report whether it works?
> 

Different error:

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes  -I. -I./Include  -DPy_BUILD_CORE  -c ./Modules/posixmodule.c -o Modules/posixmodule.o
In file included from Include/Python.h:57,
                 from Modules/posixmodule.c:30:
Include/pyport.h:520: warning: `struct winsize' declared inside parameter list
Include/pyport.h:520: warning: its scope is only this definition or declaration, which is probably not what you want
Include/pyport.h:521: warning: `struct winsize' declared inside parameter list
Modules/posixmodule.c: In function `_pystat_fromstructstat':
Modules/posixmodule.c:1306: error: structure has no member named `st_atimespec'
Modules/posixmodule.c:1307: error: structure has no member named `st_mtimespec'
Modules/posixmodule.c:1308: error: structure has no member named `st_ctimespec'
Modules/posixmodule.c: In function `posix_chroot':
Modules/posixmodule.c:1735: error: `chroot' undeclared (first use in this function)
Modules/posixmodule.c:1735: error: (Each undeclared identifier is reported only once
Modules/posixmodule.c:1735: error: for each function it appears in.)
Modules/posixmodule.c: In function `posix_setgroups':
Modules/posixmodule.c:5506: warning: implicit declaration of function `setgroups'
Modules/posixmodule.c: In function `posix_wait3':
Modules/posixmodule.c:5590: warning: implicit declaration of function `wait3'
Modules/posixmodule.c: In function `posix_wait4':
Modules/posixmodule.c:5614: warning: implicit declaration of function `wait4'
Modules/posixmodule.c: In function `posix_lstat':
Modules/posixmodule.c:5701: error: `lstat' undeclared (first use in this function)
Modules/posixmodule.c: In function `posix_major':
Modules/posixmodule.c:6337: warning: implicit declaration of function `major'
Modules/posixmodule.c: In function `posix_minor':
Modules/posixmodule.c:6350: warning: implicit declaration of function `minor'
Modules/posixmodule.c: In function `posix_makedev':
Modules/posixmodule.c:6363: warning: implicit declaration of function `makedev'
Modules/posixmodule.c: In function `posix_getloadavg':
Modules/posixmodule.c:7955: warning: implicit declaration of function `getloadavg'
*** Error code 1

Stop in /bu/pkg/Python-2.5.1 (line 1111 of Makefile).

__BSD_VISIBLE is there (it wasn't there before and that's what was causing my original problem).
dnm at kili:/bu/pkg/Python-2.5.1$ grep _BSD_SOURCE pyconfig.h
dnm at kili:/bu/pkg/Python-2.5.1$ grep _BSD_VISIBLE pyconfig.h
#define __BSD_VISIBLE 1

I don't understand what's causing the problem, though:

/usr/include/unistd.h:
#if __XPG_VISIBLE >= 500
ssize_t  pread(int, void *, size_t, off_t);
ssize_t  pwrite(int, const void *, size_t, off_t);
int	 ttyname_r(int, char *, size_t)
	    __attribute__((__bounded__(__string__,2,3)));
#endif

#if __BSD_VISIBLE ||  __XPG_VISIBLE <= 500
/* Interfaces withdrawn by X/Open Issue 5 Version 0 */
void	 *brk(void *);
int	 chroot(const char *);
int	 getdtablesize(void);
int	 getpagesize(void);
char	*getpass(const char *);
void	*sbrk(int);
#endif

#if __POSIX_VISIBLE >= 200112 || __XPG_VISIBLE >= 420
int     lockf(int, int, off_t);
#endif
---

posixmodule.i:
ssize_t pread(int, void *, size_t, off_t);
ssize_t pwrite(int, const void *, size_t, off_t);
int ttyname_r(int, char *, size_t)
            __attribute__((__bounded__(__string__,2,3)));
# 188 "/usr/include/unistd.h" 3 4
int lockf(int, int, off_t);
---

Plus, I get lots of warnings that I didn't get using my patch.  Sample:

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes  -I. -I./Include  -DPy_BUILD_CORE  -c ./Modules/threadmodule.c -o Modules/threadmodule.o
In file included from Include/Python.h:57,
                 from Modules/threadmodule.c:5:
Include/pyport.h:520: warning: `struct winsize' declared inside parameter list
Include/pyport.h:520: warning: its scope is only this definition or declaration, which is probably not what you want
Include/pyport.h:521: warning: `struct winsize' declared inside parameter list

Here are the differences between the pyconfig.h with my patch and with yours:

dnm at kili:/bu/pkg/Python-2.5.1$ diff pyconfig.h pyconfig.h.martin
93c93
< #define HAVE_CURSES_RESIZETERM 1
---
> /* #undef HAVE_CURSES_RESIZETERM */
647c647
< #define HAVE_TERM_H 1
---
> /* #undef HAVE_TERM_H */
744c744
< #define MVWDELCH_IS_EXPRESSION 1
---
> /* #undef MVWDELCH_IS_EXPRESSION */
863c863
< #define WINDOW_HAS_FLAGS 1
---
> /* #undef WINDOW_HAS_FLAGS */
932c932
< /* #undef _POSIX_C_SOURCE */
---
> #define _POSIX_C_SOURCE 200112L
941c941
< /* #undef _XOPEN_SOURCE */
---
> #define _XOPEN_SOURCE 600
944c944
< /* #undef _XOPEN_SOURCE_EXTENDED */
---
> #define _XOPEN_SOURCE_EXTENDED 1

Thanks,
dnm


From stefan.behnel-n05pAM at web.de  Thu Jul 26 05:42:08 2007
From: stefan.behnel-n05pAM at web.de (Stefan Behnel)
Date: Thu, 26 Jul 2007 11:42:08 +0200
Subject: Any reason why cStringIO in 2.5 behaves different from 2.4?
In-Reply-To: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de>
References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de>
Message-ID: <46A86C70.8040707@web.de>

Stefan Scholl wrote:
> After an hour searching for a potential bug in XML parsing
> (PyXML), after updating from 2.4 to 2.5, I found this one:
> 
> $ python2.5
> Python 2.5 (release25-maint, Dec  9 2006, 14:35:53)
> [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import StringIO
>>>> x = StringIO.StringIO(u"m\xf6p")
>>>> import cStringIO
>>>> x = cStringIO.StringIO(u"m\xf6p")
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128)
> $ python
> Python 2.4.4 (#2, Apr  5 2007, 20:11:18)
> [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import StringIO
>>>> x = StringIO.StringIO(u"m\xf6p")
>>>> import cStringIO
>>>> x = cStringIO.StringIO(u"m\xf6p")
> 
> 
> OK, that's why my code was fine with Python 2.4 and breaks with
> 2.5.

It wasn't fine with 2.4 either:

"""
Unlike the memory files implemented by the StringIO module, those provided by
this module are not able to accept Unicode strings that cannot be encoded as
plain ASCII strings.
"""

http://docs.python.org/lib/module-cStringIO.html

Read the docs...

Stefan


From Eric_Dexter at msn.com  Fri Jul 13 20:07:45 2007
From: Eric_Dexter at msn.com (Eric_Dexter at msn.com)
Date: Fri, 13 Jul 2007 17:07:45 -0700
Subject: Right tool and method to strip off html files (python, sed, awk?)
In-Reply-To: <1184353058.660535.140110@m3g2000hsh.googlegroups.com>
References: <1184353058.660535.140110@m3g2000hsh.googlegroups.com>
Message-ID: <1184371665.105931.125000@r34g2000hsd.googlegroups.com>

On Jul 13, 1:57 pm, seb... at gmail.com wrote:
> Hi,
>
> I'm in the process of refactoring a lot of HTML documents and I'm
> using html tidy to do a part of this
> work. (clean up, change to xhtml and remove font and center tags)
>
> Now, Tidy will just do a part of the work I need to
> do, I have to remove all the presentational tags and attributes from
> the pages (in other words rip off the pages) including the tables that
> are used for disposition of content (how to differentiate?).
>
> I thought about doing that with python (for which I'm in process of
> learning), but maybe an other tool (like sed?) would be better suited
> for this job.
>
> I kind of know generally what I need to do:
>
> 1- Find all html files in the folders (sub-folders ...)
> 2- Do some file I/O and feed Sed or Python or what else with the file.
> 3- Apply recursively some regular expression on the file to do the
> things a want. (delete when it encounters certain tags, certain
> attributes)
> 4- Write the changed file, and go through all the files like that.
>
> But I don't know how to do it for real, the syntax and everything. I
> also want to pick-up the tool that's the easiest for this job. I heard
> about BeautifulSoup and lxml for Python, but I don't know if those
> modules would help.
>
> Now, I know I'm not a the best place to ask if python is the right
> choice (anyways even my little finger tells me it is), but if I can do
> the same thing more simply with another tool it would be good to know.
>
> An other argument for the other tools is that I know how to use the
> find unix program to find the files and feed them to grep or sed, but
> I still don't know what's the syntax with python (fetch files, change
> them than write them) and I don't know if I should read the files and
> treat them as a whole or just line by line. Of course I could mix
> commands with some python, find command to my program's standard
> input, and my command's standard output to the original file. But I do
> I control STDIN and STDOUT with python?
>
> Sorry if that's a lot of questions in one, and I will probably get a
> lot of RTFM (which I'm doing btw), but I feel I little lost in all
> that right now.
>
> Any help would be really appreciated.
> Thanks

You might find a text editor is the way to go..  you can use autoit
either through python or by itself to control the text editor you
use..  I just downloaded pspad and it looks like it will do that.  It
may be a pain to script though.

http://sourceforge.net/projects/dex-tracker/



From steve at holdenweb.com  Tue Jul 24 10:22:08 2007
From: steve at holdenweb.com (Steve Holden)
Date: Tue, 24 Jul 2007 10:22:08 -0400
Subject: for line in file('filename'):
In-Reply-To: 
References: 
Message-ID: 

Yoav Goldberg wrote:
> 
> I use the idiom "for line in file('filename'): do_something(line)" quite 
> a lot.
> 
> Does it close the opened file at the end of the loop, or do I have to 
> explicitly save the file object and close it afterward?
> 
The file will *normally* be closed in most Python implementations, but 
it's good practice to close it explicitly. Google for "defensive 
programming" to find out why.

In 2.5 you can use the "with" statement to get an explicit close without 
having to write it. The following code comes from "What's new in Python 
2.5":

from __future__ import with_statement
with open('/etc/passwd', 'r') as f:
     for line in f:
         print line
         ... more processing code ...

This is because the open() built-in now returns a "context manager" 
object that closes the file automatically.

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 nospam.themindstorm at gmail.com  Fri Jul 27 19:21:40 2007
From: nospam.themindstorm at gmail.com (Alex Popescu)
Date: Fri, 27 Jul 2007 23:21:40 +0000 (UTC)
Subject: Packages
References: <1185576929.136179.174440@b79g2000hse.googlegroups.com>
Message-ID: 

"Kevin T. Ryan"  wrote in 
news:1185576929.136179.174440 at b79g2000hse.googlegroups.com:

> Hi All -
> 
> I'm having a problem and I hope you can help.  I can't seem to import
> packages from within the package substructure as I think I should be
> able to.  For example, I create a directory structure as follows:
> 
> testpkg
>   __init__.py [empty]
>   testsub1/
>     __init__.py [empty]
>     bad.py [import testpkg.testsub2.good; print "hello from bad"] <-
> error
>   testsub2/
>     __init__.py [empty]
>     good.py [print "hello from good"]
> 
> Whenever I try to run bad.py (just python bad.py from within the
> testsub2 subdirectory or from above the testpkg directory) I get an
> error.  For example:
> 
> $ python testpkg/testsub1/bad.py
> Traceback (most recent call last):
>   File "testpkg/testsub1/bad.py", line 1, in      import testpkg.testsub2.good
> ImportError: No module named testpkg.testsub2.good
> 
> How can I get my subpackages to recognize other subpackages in the
> same top-level package?  Thanks in advance!!
> 
> Kevin
> 

When executing bad.py python will be looking for imported module (in the 
standard path) and then in your current directory (so to find it you 
should have testsub1/testpkg/testsub2). You can solve this by adding 
your toplevel director (the parent of testpkg) to the PYTHONPATH. 

bests,
./alex
--
.w( the_mindstorm )p.





From exarkun at divmod.com  Tue Jul  3 09:03:29 2007
From: exarkun at divmod.com (Jean-Paul Calderone)
Date: Tue, 3 Jul 2007 09:03:29 -0400
Subject: Debugging "broken pipe" (in telnetlib)
In-Reply-To: <1183464742.148754.120550@w5g2000hsg.googlegroups.com>
Message-ID: <20070703130329.4947.1733977845.divmod.quotient.6397@ohm>

On Tue, 03 Jul 2007 05:12:22 -0700, Samuel  wrote:
>Hi,
>
>When using telnetlib, the connection sometimes breaks with the
>following error:
>
>"error: (32, 'Broken pipe')"
>
>where the traceback points to
>
>self.sock.send(buffer)
>
>in telnetlib.py. The problem is unreproducible, but happens fairly
>often (approx. 5% of the time). Any idea how to debug such a problem?
>How can I find out what broke the pipe?

EPIPE results when writing to a socket for which writing has been shutdown.
This most commonly occurs when the socket has closed.  You need to handle
this exception, since you can't absolutely prevent the socket from being
closed.  There might be some other change which would be appropriate, though,
if it is the case that something your application is doing is causing the
socket to be closed (for example, sending a message which the remote side
decides is invalid and causing it to close the socket explicitly from its
end).  It's difficult to make any specific suggestions in that area without
knowing exactly what your program does.

Jean-Paul


From zacherates at gmail.com  Wed Jul  4 08:09:03 2007
From: zacherates at gmail.com (zacherates)
Date: Wed, 04 Jul 2007 12:09:03 -0000
Subject: using subprocess for non-terminating command
In-Reply-To: <1183549118.773813.132940@r34g2000hsd.googlegroups.com>
References: <1183549118.773813.132940@r34g2000hsd.googlegroups.com>
Message-ID: <1183550943.531211.306410@n60g2000hse.googlegroups.com>

> How should I handle these kind of commands (ping 127.0.0.1) with
> subprocess module. I am using subprocess, instead of os.system because
> at anypoint in time, I need access to stdout and stderr of execution.

Ping, for one, allows you to set an upper bound on how long it runs
(the -c option).  This is probably the cleanest approach if it's
available.

You can also send the subprocess signals if you need it to exit
(although, this is a unix thing so I'm not sure how portable it is).
You could emulate having a timeout on child.stdout.read by registering
a callback with Timer to kill the child.

Cheers,
   Aaron



From ptmcg at austin.rr.com  Tue Jul  3 12:45:12 2007
From: ptmcg at austin.rr.com (Paul McGuire)
Date: Tue, 03 Jul 2007 09:45:12 -0700
Subject: Pretty Scheme, ??? Python
In-Reply-To: <1183480202.655654.100160@k29g2000hsd.googlegroups.com>
References: 
	<46895e12$0$5078$ba4acef3@news.orange.fr>
	<_Ddii.36114$G23.10348@newsreading01.news.tds.net>
	<1183418938.911025.55340@w5g2000hsg.googlegroups.com>
	
	<1183469909.444902.147310@57g2000hsv.googlegroups.com>
	
	<1183480202.655654.100160@k29g2000hsd.googlegroups.com>
Message-ID: <1183481112.560325.73990@g4g2000hsf.googlegroups.com>

By the way, the next release of pyparsing will allow you to shortcut
all of these .setResultsName calls, using this notation instead:

binop = ( LPAR +
            oneOf("+ -")('op') +
            wae('lhs') +
            wae('rhs') + RPAR )
with_ = ( LPAR + "with" + LPAR +
            id_('bound_id') +
            wae('named_expr') + RPAR +
            wae('bound_body') + RPAR )

This is implemented in the latest version in the SF SVN repository.

-- Paul



From uclamathguy at gmail.com  Tue Jul 24 13:38:47 2007
From: uclamathguy at gmail.com (Ryan Rosario)
Date: Tue, 24 Jul 2007 10:38:47 -0700
Subject: Reading a Directory of Emails - Problems
Message-ID: <72fc09510707241038s367aaa3bqd6a221074291d3d@mail.gmail.com>

Hi,

I have a directory that contains a bunch of email messages and I would like
to parse them using the email and mailbox packages. The emails were exported
from Apple Mail. From what I gather, I need to use MHMailbox, but I can't
get it to do anything useful and I cannot find any examples of how to use
this particular mailbox type.

mbox = mailbox.MHMailbox('stat_inbox.mbox/Messages',email.message_from_file)
for msg in mbox:
    print msg.keys()          #just to see if anything is happening

I get an error. AttributeError: MHMailbox instance has no attribute 'keys'.
Yet this works when using PortableUnixMailbox (on an mbox file, not a
directory of emails).

Can someone help me use this type of mailbox? Am I even using the correct
type of mailbox for this?

Thanks,
Ryan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From zacherates at gmail.com  Wed Jul  4 16:19:34 2007
From: zacherates at gmail.com (zacherates)
Date: Wed, 04 Jul 2007 20:19:34 -0000
Subject: using subprocess for non-terminating command
In-Reply-To: 
References: <1183549118.773813.132940@r34g2000hsd.googlegroups.com>
	<1183550943.531211.306410@n60g2000hse.googlegroups.com>
	<20070704143641.GA3434@gmail.com>
	<16651e80707040823y7d8103bbl34da35a776b147f@mail.gmail.com>
	
Message-ID: <1183580374.471044.180780@n2g2000hse.googlegroups.com>

> Only when the program has executed and the output available, subprocess can
> read through PIPE's stdout it seems ( not at any other time).
> With killing, I loose the output.

This is untrue.
>>> process.stdout.read() # Blocks until end of stream.
>>> process.stdout.read(1) # Reads one character, only blocks if that character is unavailable.

As such you can read the needed chars from the child's STDOUT one at a
time. For example:

import os
import signal
import subprocess
import threading
import sys

stop = False
ping = subprocess.Popen('ping 127.0.0.1', shell = True, stdout =
subprocess.PIPE)

def kill():
    global stop
    stop = True
    os.kill(ping.pid, signal.SIGTERM)

threading.Timer(5, kill).start()

while not stop:
     sys.stdout.write(ping.stdout.read(1))

This solution let's you read from the stdout of a program that may
never terminate and time out after a certain amount of time but it's
not pretty.  It's unix specific and introduces threads into a program
that doesn't need them.  I'd go with trying to limit the time the
child runs through command line options if at all possible.

Cheers,
   Aaron




From scott.daniels at acm.org  Mon Jul 16 22:30:19 2007
From: scott.daniels at acm.org (Scott David Daniels)
Date: Mon, 16 Jul 2007 19:30:19 -0700
Subject: Implementaion of random.shuffle
In-Reply-To: <1184597148.692325.36590@x35g2000prf.googlegroups.com>
References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com>
	
	<1184597148.692325.36590@x35g2000prf.googlegroups.com>
Message-ID: <139oacer2e9csbc@corp.supernews.com>

shabda raaj wrote:
> ... Oh, I wasn't aware that I could see the source of all python modules....
Well, actually not _all_ (or is that __all__), but that is exactly why 
so many of us love Python -- no magic (or at least as little as needed).

--Scott David Daniels
scott.daniels at acm.org


From claird at lairds.us  Thu Jul  5 10:16:29 2007
From: claird at lairds.us (Cameron Laird)
Date: Thu, 5 Jul 2007 14:16:29 +0000
Subject: The best platform and editor for Python
References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com>
	<1183398645.511107.258700@n2g2000hse.googlegroups.com>
	
	<1183630730.251890.238900@m36g2000hse.googlegroups.com>
Message-ID: 

In article <1183630730.251890.238900 at m36g2000hse.googlegroups.com>,
Kay Schluehr   wrote:
>On Jul 3, 8:12 pm, cla... at lairds.us (Cameron Laird) wrote:
>
>> Python is simply easier than C++; you might
>> well find that a debugger, for example, doesn't feel as essential
>> as it is for you with C++.
>
>That's what I love most about the Python community. Whenever there is
>just a non-standard, platform-dependent or crappy implementation of a
>feature you get told that you don't need it. When printf was good for
>little David print is good enough for me.
>
>Among the first things I examine about an IDE ( for Python ) is the
>integration of a good REPL and how well recursive functions can be
>debugged ( yes, I know, Pythonistas can't recurse and so it is not
>recommended as well but sometimes ... )
>

You've made factual claims with which I can't agree.

If I understand you correctly, Pythoneers (to the exclusion of other
software workers?) are prone to misrepresent lacunae as irrelevant.
Perhaps I've done so in this case; perhaps I characteristically do
so myself, and need to examine my own judgment more closely.  It
simply is not true, though, and even slanderous, to leave the
impression that the community as a whole wallows "fat and dumb" in
its rut of missing features.  Py2exe, pyexpect, pylint, ElementTree,
and many, many other Python facilities we now take for granted didn't
exist at one time, and were recognized as important lacks.  Old
comp.lang.python threads make this clear.

In writing this, I don't mean to minimize at all the merit of the
specific individuals who authored ElementTree, pylint, and so on.

You seem also to be saying that all Python debuggers are "non-standard,
platform-dependent or crappy".  Is that truly your assessment of pdb
?  Or are you focused
on the IDEs , and
really see them all that way?

Anyway, I repeat my claim:  I recommend to the original poster that he
consider learning Python in a style that's qualitatively different--
"lighter"--than his experience with C++.


From info at gegereka.org  Thu Jul 12 13:04:29 2007
From: info at gegereka.org (GEGEREKA!)
Date: 12 Jul 2007 17:04:29 GMT
Subject: MP3 AVI DIVX MPEG SOFT = www.GEGEREKA.com
Message-ID: <46965f1b$0$16282$2e0edba0@news.tweakdsl.nl>

Millions files for everyone. Music, movies, soft and other media.
Check it now!! http://www.gegereka.com


From enleverlesX.XmcX at XmclaveauX.com  Tue Jul  3 13:54:57 2007
From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI)
Date: Tue, 3 Jul 2007 19:54:57 +0200
Subject: python 3.0 or 3000 ....is it worth waiting??? Newbie Question
References: 
Message-ID: <468a8dc1$0$27406$ba4acef3@news.orange.fr>

Hi!

> Python 3000 doesn't include many significant changes to the language

One exemple : non-Ascii characters in identifiers (= no significatif 
change?)


Michel Claveau




From thomas at jollans.com  Wed Jul  4 10:18:58 2007
From: thomas at jollans.com (Thomas Jollans)
Date: Wed, 4 Jul 2007 16:18:58 +0200
Subject: Proposal: s1.intersects(s2)
In-Reply-To: <87sl84l16r.fsf@grogan.peloton>
References: <87sl84l16r.fsf@grogan.peloton>
Message-ID: <200707041619.04727.thomas@jollans.com>

On Wednesday 04 July 2007, David Abrahams wrote:
> Here's an implementation of the functionality I propose, as a
> free-standing function:
>
>         def intersects(s1,s2):
>             if len(s1) < len(s2):
>                 for x in s1:
>                     if x in s2: return True
>             else:
>                 for x in s2:
>                     if x in s1 return True
>             return False
>
> Right now, the only convenient thing to do is
>
>       if s1 & s2 ...
>
> but that builds a whole new set.  IMO that query should be available
> as a method of set itself.

>>> s1 = set(xrange(5))
>>> s2 = set(xrange(3,9))
>>> s1
set([0, 1, 2, 3, 4])
>>> s2
set([3, 4, 5, 6, 7, 8])
>>> s1 | s2
set([0, 1, 2, 3, 4, 5, 6, 7, 8])
>>> s1 & s2
set([3, 4])
>>>

It's all in python already. And documented on the web too.

-- 
      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 danmcleran at yahoo.com  Mon Jul 16 18:53:55 2007
From: danmcleran at yahoo.com (danmcleran at yahoo.com)
Date: Mon, 16 Jul 2007 15:53:55 -0700
Subject: Break up list into groups
In-Reply-To: 
References: <1184620307.340479.253430@z28g2000prd.googlegroups.com>
	
Message-ID: <1184626435.277616.29590@x35g2000prf.googlegroups.com>

> Here's an ugly way I wouldn't recommended (using itertools groupby):
>
> py> from itertools import groupby
> py> alist = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6,
> ...          0xF1, 7, 8, 0xF2, 9, 10, 11, 12, 13,
> ...          0xF0, 14, 0xF1, 15]
> py> def doit(alist):
> ...   i = (list(g) for k,g in groupby(alist, lambda x: 0xf0&x))
> ...   return [k for k in [j + i.next() for j in i] if len(k)>1]
> ...
> py> doit(alist)
>
> [[240, 1, 2, 3],
>   [240, 4, 5, 6],
>   [241, 7, 8],
>   [242, 9, 10, 11, 12, 13],
>   [240, 14],
>   [241, 15]]
>
> James

Wow that is ugly. I think I like the simpler way better.

Thanks



From eddie at holyrood.ed.ac.uk  Mon Jul 23 06:53:02 2007
From: eddie at holyrood.ed.ac.uk (Eddie Corns)
Date: Mon, 23 Jul 2007 10:53:02 +0000 (UTC)
Subject: Can a low-level programmer learn OOP?
References:  
	
	<7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com>
	 
	
Message-ID: 

Wolfgang Strobl  writes:
>few of James Gimple's snippets from "Algorithms in SNOBOL4"
>(->http://www.snobol4.org/) as an exercise using that library might help
>to get a better appreciation. Perhaps I'll try, eventually ...

I never noticed them or the PDF of the book there before.  Some Friday
afternoon reading for sure.

Personally I hope to get more to time to look at a combination of Lua and
PEGs (http://en.wikipedia.org/wiki/Parsing_expression_grammar) for my parsing
needs.

Eddie


From donn at u.washington.edu  Thu Jul 12 13:41:05 2007
From: donn at u.washington.edu (Donn Cave)
Date: Thu, 12 Jul 2007 10:41:05 -0700
Subject: PEP 3107 and stronger typing (note: probably a newbie question)
References: <468565a0$0$3686$426a74cc@news.free.fr>
	<1i0ikru.1uccqtm1efnzn3N%aleax@mac.com>
	
	<1i0n0tr.ve0o791347ugyN%aleax@mac.com>
	<7xd4za1086.fsf@ruckus.brouhaha.com>
	<5f0mhuF3b0stbU1@mid.individual.net>
	<7xd4z837e2.fsf@ruckus.brouhaha.com>
	<468b7426$0$9063$426a34cc@news.free.fr>
	<7x4pkkun56.fsf@ruckus.brouhaha.com>
	<1183575597.272150.152200@w5g2000hsg.googlegroups.com>
	
	<7xzm2budfv.fsf@ruckus.brouhaha.com>
	
	<7xir8vju1l.fsf@ruckus.brouhaha.com>
	
	
	<7xvecumrte.fsf@ruckus.brouhaha.com>
	
	
	<1i13w96.kyyobph71qxrN%aleax@mac.com>
	<7xwsx63we6.fsf@ruckus.brouhaha.com>
	<878x9llv5x.fsf@benfinney.id.au>
Message-ID: 

In article <878x9llv5x.fsf at benfinney.id.au>,
 Ben Finney  wrote:

> Paul Rubin  writes:
> 
> > The idea of designing languages with more and more support for
> > ensuring program correctness is to put the established, repetitive
> > processes into the computer where it belongs, freeing the programmer
> > to be innovative while still providing high assurance of that the
> > program will be right the first time.
> 
> This seems to make the dangerous assumption that the programmer has
> the correct program in mind, and needs only to transfer it correctly
> to the computer.
> 
> I would warrant that anyone who understands exactly how a program
> should work before writing it, and makes no design mistakes before
> coming up with a program that works, is not designing a program of any
> interest.

I don't get it.  Either you think that the above mentioned support
for program correctness locks program development into a frozen
stasis at its original conception, in which case you don't seem to
have read or believed the whole paragraph and haven't been reading
much else in this thread.  Certainly up to you, but you wouldn't be
in a very good position to be drawing weird inferences as above.

Or you see original conception of the program as so inherently
suspect, that random errors introduced during implementation can
reasonably be seen as helpful, which would be an interesting but
unusual point of view.

   Donn Cave, donn at u.washington.edu


From steve at holdenweb.com  Mon Jul  9 14:49:28 2007
From: steve at holdenweb.com (Steve Holden)
Date: Mon, 09 Jul 2007 14:49:28 -0400
Subject: Where is the syntax for the dict() constructor ?! (OT)
In-Reply-To: <003801c7c1ef$afcf6e60$03000080@hendrik>
References: <468D1D9D.6060002@gmail.com><468D3445.2060408@gmail.com><1183675552.466967.136360@i13g2000prf.googlegroups.com><5f6fo1F3b25tsU1@mid.uni-berlin.de><5f8rrpF3c8qopU1@mid.uni-berlin.de>	<1183853628.296224.107400@i13g2000prf.googlegroups.com><00bc01c7c13f$573770a0$03000080@hendrik>	
	<003801c7c1ef$afcf6e60$03000080@hendrik>
Message-ID: 

Hendrik van Rooyen wrote:
>  "Steve Holden"  wrote:
> 
>> Would we do that with esteeth?
> 
> Ok Steve you've got me - my dictionary goes from
> estate to esteem to ester...
> 
> The US spelling of "esthete" may have a bearing...
> 
> - Hendrik
> 

Sorry - dreadful joke. Since teeth chew, I wondered whether esteeth 
might eschew. [Graon ...]

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  Wed Jul 11 18:51:58 2007
From: ptmcg at austin.rr.com (Paul McGuire)
Date: Wed, 11 Jul 2007 15:51:58 -0700
Subject: 2**2**2**2**2 wrong? Bug?
In-Reply-To: 
References: 
	<7xbqek7ty1.fsf@ruckus.brouhaha.com> 
	<1184173446.779276.250530@k79g2000hse.googlegroups.com>
	<1184182757.797808.206480@d55g2000hsg.googlegroups.com>
	
Message-ID: <1184194318.602416.12200@r34g2000hsd.googlegroups.com>

On Jul 11, 3:53 pm, "Evan Klitzke"  wrote:
> On 7/11/07, Paul McGuire  wrote:
>
> > On Jul 11, 12:04 pm, David Jones  wrote:
> > > > In fact, if I put (2**2)**2**2**2
> > > > it comes up with the correct answer, 4294967296
>
> > > Actually, the "correct" answer (even by your own demonstration) is
> > > 65536.
>
> > It might be easier to demonstrate if we chose a less homogeneous
> > problem: 2**3**2.  A right (rightly?) associative language (such as
> > Python) reads this as 2**(3**2), or 2**9=512.  A left-associative
> > language (such as VB) reads this as (2**3)**2 or 8**2=64.  As was
> > pointed out earlier, left-associativity with exponentiation is of
> > little value, since (2**3)**2 is the same as 2**(3*2) or 2**6=64.
>
> It doesn't have anything to do with the language being left/right
> associative, it has to do with the operators in question. For example,
> subtraction is always left associative -- you would be really
> surprised if 3 - 2 - 1 evaluated to 2. Python happens to choose right
> associativity for exponentiation because it is more useful for that
> operator, but that doesn't make the language itself right associative.
>
> --
> Evan Klitzke 

Sorry, I meant that Python was right-associative only with respect to
exponentiation.  All other arithmetic operators are left-to-right (and
rightly so).  By contrast, VisualBasic evaluates exponentiation left-
to-right, so for the sake of this thread, VB is a left-associative
exponentiation language.

-- Paul



From aleax at mac.com  Thu Jul  5 11:25:08 2007
From: aleax at mac.com (Alex Martelli)
Date: Thu, 5 Jul 2007 08:25:08 -0700
Subject: PyRun_String using my module in a def
References: <1183601931.930115.132400@n2g2000hse.googlegroups.com>
	<1i0qtvm.sq102f16mpe7tN%aleax@mac.com>
	<1183609172.421840.171130@n60g2000hse.googlegroups.com>
	
Message-ID: <1i0rr99.a84octjowju7N%aleax@mac.com>

Gabriel Genellina  wrote:

> En Thu, 05 Jul 2007 01:19:32 -0300, Stuart   
> escribi?:
> 
> > What command do you mean when you say "update main_dict with
> > dlfl_dict"?
> 
> I think Alex Martelly was refering to use main_dict.update(dlfl_dict)
> (Python code) or PyDict_Update(main_dict, dlfl_dict) (in C code).

Yep.


> > I tried PyObject *rstring = PyRun_String( cmd, Py_file_input,
> > dlfl_dict, dlfl_dict );
> > This worked, but has the side effect of not allowing other commands
> > like "execfile"
> 
> The idea is to copy all items from dlfl_dict into main_dict, and use
> main_dict for both globals and locals.

Exactly.


Alex


From joejacob21 at gmail.com  Mon Jul 23 07:54:41 2007
From: joejacob21 at gmail.com (joe jacob)
Date: Mon, 23 Jul 2007 11:54:41 -0000
Subject: Configure apache to run python scripts
In-Reply-To: <46a4941a$0$21663$426a74cc@news.free.fr>
References: <1185160927.844397.244290@e16g2000pri.googlegroups.com>
	<46a4941a$0$21663$426a74cc@news.free.fr>
Message-ID: <1185191681.422317.111680@i38g2000prf.googlegroups.com>

On Jul 23, 4:42 pm, Bruno Desthuilliers  wrote:
> joe jacob a ?crit :
>
> > I need to configure apache to run python scripts. I followed the steps
> > mentioned in this site (http://www.thesitewizard.com/archive/
> > addcgitoapache.shtml). But I am not able to run python scripts from
> > Firefox, I      got a forbidden error "you do not have permission to
> > access the file in the server" when I try to run the script form
> > Firefox browser. Somebody please help me.
>
> http://httpd.apache.org/docs//howto/cgi.html
>
> with 'your_apache_version_here' in 1.3, 2.0, 2.2
>
> FWIW, your problem relates to apache and permissions, not to Python.
>
> HTH

I got it right, I configured the apache incorrectly. Now I can execute
the python scripts. Thanks for the response.



From siwiak at gmail.com  Thu Jul 12 18:55:29 2007
From: siwiak at gmail.com (siwiak at gmail.com)
Date: Thu, 12 Jul 2007 15:55:29 -0700
Subject: wx.App console window [Windows]
In-Reply-To: <1184279332.640059.120140@k79g2000hse.googlegroups.com>
References: <1184273064.350399.152490@o61g2000hsh.googlegroups.com>
	<1184279332.640059.120140@k79g2000hse.googlegroups.com>
Message-ID: <1184280929.137401.50620@o61g2000hsh.googlegroups.com>

On 13 Lip, 00:28, kyoso... at gmail.com wrote:
> On Jul 12, 3:44 pm, siw... at gmail.com wrote:
>
>
>
> > Hi All,
>
> > I'm looking for a way to  hide console window created by wx.App class.
>
> > examplary code below:
>
> > import wx
>
> > class Gui(wx.App):
> >         def __init__(self, *pargs, **kwargs):
> >                 wx.App.__init__(self, *pargs, **kwargs)
>
> > if __name__ == "__main__":
> >     app = Gui()
> >     app.MainLoop()
>
> > produces a blank console window (than dies).
>
> > What shall I do to make wx.App run without raising console window?
>
> > thanks in advance
>
> Save the file as a *.pyw. And I would recommend adding the following 2
> lines to your __init__ :
>
> 
>
> frame = wx.Frame(None, wx.ID_ANY, title='My Title')
> frame.Show()
>
> 
>
> Maybe even stick in a panel object for that matter.
>
> Mike

Thank you Mike, *.pyw made the first part of the trick just perfectly.
Thanks to your answer I was able to ask google proper question
concerning second part. Below (for possible future readers) I attach
solution I found:

People looking for possibility of running wx.App no console version
after py2exe compilation:
in setup script change 'console = ['foo.py']' for 'windows = ['foo.py']



From kelvie at ieee.org  Fri Jul 13 05:34:24 2007
From: kelvie at ieee.org (Kelvie Wong)
Date: Fri, 13 Jul 2007 02:34:24 -0700
Subject: Getting values out of a CSV
In-Reply-To: 
References: <1184295593.638409.22910@22g2000hsm.googlegroups.com>
	
	
	
Message-ID: <94ccbe710707130234u7b0c593eg9624803b2557bbba@mail.gmail.com>

On 7/12/07, Daniel  wrote:
> On Fri, 13 Jul 2007 08:51:25 +0300, Gabriel Genellina
>  wrote:
> >> data = [row for row in csv.reader(open('some.csv', 'rb'))
> >
> > Note that every time you see [x for x in ...] with no condition, you can
> > write list(...) instead - more clear, and faster.
> >
> > data = list(csv.reader(open('some.csv', 'rb')))
>
> Clearer? Maybe, but list comprehensions are clearer (at least for me)
>
> Faster? No. List Comprehensions are faster.
> --
> http://mail.python.org/mailman/listinfo/python-list
>

kelvie at valour pdfps $ python -m timeit -c 'data = list(open("make.ps"))'
100 loops, best of 3: 7.5 msec per loop
kelvie at valour pdfps $ python -m timeit -c 'data = [line for line in
open("make.ps")]'
100 loops, best of 3: 9.2 msec per loop

On my system just putting into a list is faster.  I think this is
because you don't need to assign each line to the variable 'line' each
time in the former case.

I, too, think it's faster to just use list() instead of 'line for line
in iterable', as it seems kind of redundant.

-- 
Kelvie


From maxkhesin at gmail.com  Mon Jul 16 17:37:41 2007
From: maxkhesin at gmail.com (xamdam)
Date: Mon, 16 Jul 2007 21:37:41 -0000
Subject: zipfile 2GB problems?
In-Reply-To: 
References: <1184474112.081258.111490@n60g2000hse.googlegroups.com>
	<1184525970.082235.238200@q75g2000hsh.googlegroups.com>
	
	<1184528949.751377.5620@g4g2000hsf.googlegroups.com>
	
	<1184612398.359979.28900@d55g2000hsg.googlegroups.com>
	
Message-ID: <1184621861.925437.64900@w3g2000hsg.googlegroups.com>

On Jul 16, 3:39 pm, Steve Holden  wrote:
> xamdam wrote:
> > On Jul 15, 5:39 pm, Steve Holden  wrote:
> >> xamdam wrote:
> >>>>> Additional info: my file is from a data provider, do not know what
> >>>>> they used to compress it. Previous files worked ok, this one is the
> >>>>> 1st over 2GB. Winzip has no problem with it.
> >>>> It could be you are using a Python with an in-built limit of 2GB on file
> >>>> size. What happens if you open the file, seek past the 2GB point and
> >>>> then try and read data?
> >>> Steve,
> >>> I used is_zipfile function, which from does exactly that from a quick
> >>> read - goes to the end, reads expected string. It worked fine. Tried
> >>> regular Windows 2.4.4 and 2.5.1, same result.
> >> Fine, if it isn't file size limitations I suspect you need to post some
> >> code and a traceback so we can get better insight into exactly what the
> >> problem is.
>
> > It's failing in the ZipFile constructor, which ends up throwing
>
> > zipfile(2.4.3).py:291> raise BadZipfile, "Bad magic number for file
> > header"
>
> Well, that one bald line by itself certainly doesn't give *me* any
> traction an what the problem might be. Getting information about this
> problem is like (i.e. as difficult as) pulling teeth!
>
> regards
>   Steve

Well, Steve, I don't know what else to tell you - I certainly do not
want to cause you tooth ache! I was sort of hoping for some ZIP expert
to go, 'oh, yeah'...



From george.sakkis at gmail.com  Wed Jul 25 13:14:15 2007
From: george.sakkis at gmail.com (George Sakkis)
Date: Wed, 25 Jul 2007 17:14:15 -0000
Subject: Base class for file-like objects? (a.k.a "Stream" in Java)
In-Reply-To: <1185317490.607920.100200@z24g2000prh.googlegroups.com>
References: <1185317490.607920.100200@z24g2000prh.googlegroups.com>
Message-ID: <1185383655.052470.233260@w3g2000hsg.googlegroups.com>

On Jul 24, 6:51 pm, Boris Du?ek  wrote:

> Hello,
>
> (sorry to begin with Java in a Python list ;-)
> in Java, when I want to pass input to a function, I pass
> "InputStream", which is a base class of any input stream.
>
> In Python, I found that "file" objects exist. While specifying
> argument types in Python is not possible as in Java, it is possible to
> check whether an object is an instance of some class and that's what I
> need - I need to check if an argument is a "file"-like object, and if
> yes, behave accordingly, if not, treat the argument as string with
> URL.
>
> But I am afraid there is no such a base class - I tried the following:
>
> >>> import urllib
>
> >>> f = open("test.txt", "r")
> >>> g = urllib.urlopen("http://www.google.com/")
>
> >>> isinstance(f, file)
> True
> >>> isinstance(f, file)
>
> False
> ...
>
> Is there some base class to "file"-like (or "stream"-like) objects in
> Python? And if not, is it at least planned for Python 3.0?
>
> Thanks for any suggestions,
> Boris Du?ek
>
> P.S.: The code should finally look in esence something like this:
>
> if isinstance(f, file):
>    pass
> elif isinstance(f, string):
>    f = urllib.urlopen(f)
> else:
>    raise "..."
> process_stream(f)


Other replies show you how to tackle this in Python 2.x. Python 3K
will come closer to Java by formalizing the concept of abstract base
classes [1] and will most likely include a fine-grained hierarchy of
stream-like base classes [2].

George


[1] http://www.python.org/dev/peps/pep-3119/
[2] http://www.python.org/dev/peps/pep-3116/



From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Tue Jul 31 04:33:07 2007
From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
Date: Tue, 31 Jul 2007 10:33:07 +0200
Subject: Where do they tech Python officialy ?
In-Reply-To: 
References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com>	<7xveca4ajp.fsf@ruckus.brouhaha.com>		<46ae3dc8$0$634$426a34cc@news.free.fr>
	
Message-ID: <46aef3bd$0$2989$426a74cc@news.free.fr>

Star a ?crit :
> MIT's freshman survey, EECS 1 is taught in Python and Scheme, soon to be 
> just Python.

they should keep scheme or replace it with another (statically typed ?) 
functional language IMHO.


please do the world (or at least usenet and mailing lists users) a 
favour : learn to answer properly !-)

1/ don't top-post
2/ only keep from the post you're answering waht you're answering to
3/ if possible, answer to the right post (given the content of your 
post, you should have answered to the OP, not to me)

Sorry to be the annoying dude here...


> -Star
> 
> On Wed, 25 Jul 2007, Bruno Desthuilliers wrote:
> 
>> Omari Norman a ?crit :
>>> On Mon, Jul 23, 2007 at 10:48:10PM -0700, Paul Rubin wrote:
>>>
>>>
>>>> If you're having trouble with Python because you're new at
>>>> programming, I can sympathize--I don't think it's the most
>>>> beginner-friendly of languages despite the efforts in that direction
>>>> by the designers.
>>>
>>>
>>> Just curious--what language would you recommend as most
>>> beginner-friendly?
>>
>> C ?-)
>>
>> (sorry, just kidding.)
>>
>>> My previous programming experience was with BASIC--and I think it is
>>> true that BASIC will, in many ways, rot your brain.
>>
>> So will Java.
>>
>> I learned programming with Hypertalk (MacIntosh's Hypercard scripting
>> language, which more or less gave birth to AppleTalk), then RealBasic
>> (Mac's Better VB-like), then VB, then Java, then C, then bits of Pascal,
>> then Python, and this is where I started to see the light. But I had
>> hard time unlearning all those java-ish anal-retentive stupidities and
>> arbitrary overcomplexifications before I really enjoyed Python. Playing
>> with Lisp (Common Lisp and Scheme) and Smalltalk helped getting rid of
>> mental pollution wrt/ declarative static typing. To be honest, playing
>> with Haskell and O'Caml also helped me understanding that static typing
>> is not necessarily bad by itself.
>>
>>> I had used QBasic
>>> and, later, a little VBA and some PHP. It took some time to unlearn some
>>> bad things (object orientation in VBA seems to be mostly a hack, for
>>> example, while PHP seems to be a big hack generally)
>>
>> Well... this is not exactly a scoop !-)
>>
>>> but it seems to me
>>> that Python helped me learn my first modern programming language.
>>>
>>>
>>>> I think Python is not used in university programs very much.  Look for
>>>> one that uses SICP (Scheme) or CTM (Mozart/Oz) or a functional
>>>> language like Haskell, in preference to the ones that use Java (the
>>>> Cobol of the 1990's).  With some reasonable experience in Scheme or
>>>> Mozart or Haskell, plus a Python manual, you'll be well on your way.
>>>
>>>
>>> I had heard of these languages, but learning them is a bit discouraging
>>> because (Java excepted) they don't seem to get much practical use.
>>
>> Before considering practical use (FWIW, Python was pretty far from
>> mainstream 7 year ago), you should ask yourself how learning one of
>> these languages will affect the way you thing about programming. While
>> mostly in the imperative/OO camp, Python stole quite a lot from
>> functional languages, and this is obviously a GoodThing(tm).
>>
>> My 2 cents
>> -- 
>> http://mail.python.org/mailman/listinfo/python-list
>>


From steve at holdenweb.com  Thu Jul 26 07:43:44 2007
From: steve at holdenweb.com (Steve Holden)
Date: Thu, 26 Jul 2007 07:43:44 -0400
Subject: code indentation
In-Reply-To: 
References: 		<1185297657.186852.136950@k79g2000hse.googlegroups.com>		<87lkd5jt83.fsf@benfinney.id.au>	<1185357861.989194.117000@r34g2000hsd.googlegroups.com>		<1185387723.155661.311510@b79g2000hse.googlegroups.com>
	
Message-ID: 

Thorsten Kampe wrote:
> *  (Wed, 25 Jul 2007 11:22:03 -0700)
>> On 25 srp, 17:31, Wildemar Wildenburger  wrote:
>>> vedrandeko... at v-programs.com wrote:
>>>>> And while we're on the topic of communication: The original poster
>>>>> would do well to learn that increasing the number of consecutive
>>>>> punctuation marks (!!!, ???) is a sure way to turn away many people
>>>>> who would otherwise be helpful. Sentences need at most one '!' or '?',
>>>>> adding more does not improve the chances of being taken seriously.
>>>> And if you can help me than please help me , but if you can't then
>>>> please don't leave me some stupid messages
>>> Whats stupid about this? It's sane advice.
>>>
>>> Which looks more serious to you:
>>>
>>> this:
>>> I can't do it!!!! Can you PLEASE help me????!!!?!
>>>
>>> or this:
>>> I don't know the answer. Can you please help me?
>>>
>>> Even if it makes no difference to you, to many people it does. So Ben is
>>> right: People *will* take your posts more seriously if you restrict your
>>> use of punctuation (if only because its easier to read).
>>> Don't feel offended, nobody was trying to put you down.
>> On this group I ask for serious help and now we talk about
>> communication. Then I you don't know how to help me then please DON'T
>> SAY ANYTHING
> 
> You already got serious help even though you haven't realised that 
> yet.
> 
We should be making allowances for this particular poster on account of 
relative youth: I hadn't realised earlier, but we are dealing with a 
fourteen-year-old. Since fourteen-year-olds already know everything we 
should be honored we are being asked for 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 michele.simionato at gmail.com  Sun Jul  8 00:39:46 2007
From: michele.simionato at gmail.com (Michele Simionato)
Date: Sun, 08 Jul 2007 04:39:46 -0000
Subject: Creating logged functions using decorators
In-Reply-To: 
References: 
Message-ID: <1183869586.867323.95160@k79g2000hse.googlegroups.com>

On Jul 7, 8:47 pm, "Nathan Harmston" 
wrote:
> Hi,
>
> I m thinking about writing some code which logs the input and output
> of a function/script and stores it in a database using sqlalchemy
> (although I havent started on this yet). I want to do this via a
> decorator ( I think this is the best way ).
>
> def log(fn):
>     def newfn(*args):
>         print datetime.date.today()
>         print __file__
>         print fn.__name__
>         print args
>         return fn(*args)
>     return newfn
>
> @log
> def doAnalysis(a, b):
>     print a, b
>     return a + b
>
> doAnalysis(3, 7)
>
> I can access the arguments passed to the "logged" function, but is
> there anyway I can capture the output of the function i.e. 10.
>
> Many Thanks in advance,
>
> Nathan


Using my own decorator module (http://www.phyast.pitt.edu/~micheles/
python/documentation.html)
that would be

from decorator import decorator

@decorator
def log(f, *args, **kw):
   result = f(*args, **kw)
   print args, kw, result
   return result

           Michele Simionato



From aleax at mac.com  Wed Jul  4 12:34:57 2007
From: aleax at mac.com (Alex Martelli)
Date: Wed, 4 Jul 2007 09:34:57 -0700
Subject: Reversing a string
References: 
	
	<1182997438.541012.54100@o61g2000hsh.googlegroups.com>
	
	
	
	<1i0kjpx.wjw44j15np22dN%aleax@mac.com>
	
	
Message-ID: <1i0pz5v.eftrpfbeilzpN%aleax@mac.com>

Aahz  wrote:
   ...
> This works in all versions of Python back to 1.5.2 IIRC.  reversed() is
> a moderately new built-in function;

Yep: it came with Python 2.4, first alpha just 4 years ago, final
release about 3 years and 8 months ago.  "Moderately new" seems an
appropriate tag.

> I would agree with people who claim
> that you should memorize most of the built-in functions (which is
> precisely why there is a high barrier to adding more built-in functions).

I think the built-in functions and types a beginner is likely to need
are a "fuzzy subset" (the decision of whether to include or exclude
something being not really obvious:-) roughly including:

abs all any bool chr cmp dict dir enumerate float getattr help hex int
iter len list max min object open ord property raw_input reversed set
sorted str sum tuple unichr unicode xrange zip

all reasonably documented at
 .  Of course, as I
mentioned, most inclusions and exclusions may be debatable (why do I
think people need xrange and not necessarily range, set and not
necessarily frozenset, property rather than classmethod, hex more likely
than oct, probably not complex, etc etc).


> But certainly if you're using a datatype you should make a point of
> reading all its documentation, which would mean you'd know that list()
> can convert any iterable type.

Yes, and also the methods and operators of (out of the builtin types I
listed above):

dict float int list open[*] set str tuple unicode

[*] well really file, that's the name of the builtin type, but open is
what one should use as a factory function for it!-)

str and unicode have almost identical methods, save for the big crucial
difference on the semantics of method .translate; float and int also
have the same operators; and tuple has hardly anything, so the learning
task is nowhere as big as it may seem from here:-).


Alex


From samper.d at gmail.com  Sat Jul 21 12:43:06 2007
From: samper.d at gmail.com (Dave Sampson)
Date: Sat, 21 Jul 2007 09:43:06 -0700
Subject: Python Subprocess module
In-Reply-To: <1184371388.515695.271360@22g2000hsm.googlegroups.com>
References: 
	<1184371388.515695.271360@22g2000hsm.googlegroups.com>
Message-ID: <1185036186.160950.204820@r34g2000hsd.googlegroups.com>

send keys for the p.c. you can use a try: except: concept and on the
> windows platform there is also a way to use autoit in python  using
> pywin.

thanks for the uggestion about sendkeys. I might be able to build that
into the wrapper.

So you're sugesting:

NIX = Pexpect

WINDOZE = sendkeys

Correct?




From robert.rawlins at thinkbluemedia.co.uk  Fri Jul 20 10:42:38 2007
From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue)
Date: Fri, 20 Jul 2007 15:42:38 +0100
Subject: DateTime Differance
Message-ID: <011701c7cadc$3815d800$a8418800$@rawlins@thinkbluemedia.co.uk>

Hello Guys,

 

I've used the eGenix date time module to create two date time objects which
I'm now looking to compare like so:

 

If date 1 is more than 5 minutes older than date 2:

                Do something here...

 

After reading through the egenix documentation I'm still a little confused
as the best way to do this. Can anyone offer any advice?

 

Thanks guys,

 

Rob

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From rustompmody at gmail.com  Wed Jul 11 01:35:49 2007
From: rustompmody at gmail.com (Rustom Mody)
Date: Wed, 11 Jul 2007 11:05:49 +0530
Subject: bool behavior in Python 3000?
In-Reply-To: 
References:  
	
	
	
	<7xzm23ygft.fsf@ruckus.brouhaha.com>
	
Message-ID: 

Considering bools as ints --
Pros: The ALU of any computer uses boolean gates to build an
arithmetic functions.  Therefore considering the base type of ints and
bools to be (strings of) bits seems natural

Cons: This comes from the pioneering work of Dijkstra and his coworkers)
The distributive law (one of them) in boolean algebra looks like this:
a /\ (b \/ c) = (a/\b) \/ (a/\c)

which becomes simpler to read and type and more familiar as
a(b+c) = ab + ac

So far so good.  However its dual is
a\/(b/\c) = (a\/b) /\ (a\/c)

which in arithmetic notation becomes
a + bc = (a+b)(a+c)

This is sufficiently unintuitive and unnatural that even people
familiar with boolean algebra dot get it (so Dijkstra, Gries etc
claim)

Boolean algebra is perfectly dual, arithmetic is not.  That is why we
need logical connectives 'and' and 'or' and dont somehow fudge along
with + and *.  Therefore True and False should belong with 'and', 'or'
and 0,1 should belong with +,*


From lgfang at localhost.my.domain  Fri Jul 13 13:19:53 2007
From: lgfang at localhost.my.domain (lgfang)
Date: Sat, 14 Jul 2007 01:19:53 +0800
Subject: patching pylint.el
References: <86ps3164xd.fsf@localhost.my.domain.i-did-not-set--mail-host-address--so-tickle-me>
	<1184319270.442107.315920@57g2000hsv.googlegroups.com>
Message-ID: <86bqegnruu.fsf@localhost.my.domain.i-did-not-set--mail-host-address--so-tickle-me>

>>>>> "syt" == syt   writes:
    syt> fyi, pylint related bug should be reported on the python-
    syt> projects at logilab.org mailing list.  I've opened a ticket for
    syt> your bug/patch: http://www.logilab.org/bug/eid/4026

Thank you, Sylvain

Fanglungang (fang.lungang at gmail)



From robinsiebler at gmail.com  Thu Jul  5 15:31:56 2007
From: robinsiebler at gmail.com (robinsiebler at gmail.com)
Date: Thu, 05 Jul 2007 12:31:56 -0700
Subject: Extracting arbitrary amounts of data from a dictionary.
Message-ID: <1183663916.635440.185720@e9g2000prf.googlegroups.com>

I had nothing better to do, so I thought I would make a database that
contained the songs played on the internet radio station I listen to
(hardradio.com) so I could see how many differents songs/artists they
played.  I stored the data like this:

    dates = {} #; year = {}; week = {}; date = {}; artist = []; song =
{}
#    dates = {'2007': {'25': {'06/23/07': {'aerosmith': [{'sweet
emotion': 1}, {'dream on': 2}],
#                                                    'Metallica':
[{'Fade to Black': 1}, {'Master of Puppets': 1}]},
#                 'last_song': 'Master of Puppets'}}}


So I end up with a the number of times any given song by a given
artist is played in a day.  Want I want to do is to be able to print
out a report for X number of weeks and I am trying to determine the
best way to interate through the 'week' key of the dictionary.

For example, this is week 27, the dictonary has 6 'week' keys and I
want the data from the last 3 weeks.  Is this the best way to iterate
through the dictionary?

       for date in dates[year][week].keys()[-3]:

Or is there a better way with all the new features that have been
added to Python?



From greg at cosc.canterbury.ac.nz  Sun Jul 22 03:25:55 2007
From: greg at cosc.canterbury.ac.nz (greg)
Date: Sun, 22 Jul 2007 19:25:55 +1200
Subject: ANN: Snobol 1.0
In-Reply-To: 
References:  
	
	<7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com>
	
Message-ID: 

Aahz wrote:
> So adding
> SNOBOL patterns to another library would be a wonderful gift to the
> Python community...

I wrote a module for Snobol-style pattern matching a
while back, but didn't get around to releasing it.
I've just put it on my web page:

http://www.cosc.canterbury.ac.nz/greg.ewing/python/Snobol.tar.gz

There's no manual yet, but there's a fairly complete
set of docstrings and some test cases to figure it
out from.

--
Greg


From abakshi11 at gmail.com  Tue Jul 10 15:09:15 2007
From: abakshi11 at gmail.com (abakshi11)
Date: Tue, 10 Jul 2007 12:09:15 -0700 (PDT)
Subject: Embedding Matplotlib in wxpython wx.Panel problem
In-Reply-To: <1177534801.938139.39220@r35g2000prh.googlegroups.com>
References: <1177534801.938139.39220@r35g2000prh.googlegroups.com>
Message-ID: <11527402.post@talk.nabble.com>


I was wondering if you ever got to create a small GUI program that did plots
using Matplotlib
I am gettin an error where its saying "WXagg's accelerator requires the
wxPython headers-the wxpython header files can not be located in any of the
standard include directories reported by 'wx-config --cppflags'
Do you think you can help?



Soren-3 wrote:
> 
> Hi,
> 
> I'm trying to create a small GUI program where I can do plots using
> Matplotlib. I've been trying to borrow code from the examples at the
> matplotlib website, but I can't get it to work.
> 
> I want to be able to create a wx.Panel that contains an axis for
> plotting. Around it i want other panels containing various settings,
> buttons etc. to control the plot. So far I can't even get the program
> to actually show a plot in a panel.
> 
> Does anyone here have experience in making a wxpython GUI with
> matplotlib?
> 
> Any help would be appreciated!
> 
> Thanks,
> Soren
> 
> My code shows a frame, and I'm trying to set up two panels.. one with
> a plot and one with a button.. The plotpanel is just a little square
> in the corner when I run it.. ???
> 
> My code is as follows:
> 
> import wx
> import pylab
> from matplotlib.numerix import arange, sin, cos, pi
> import matplotlib
> 
> matplotlib.use('WXAgg')
> from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
> from matplotlib.backends.backend_wx import NavigationToolbar2Wx
> from matplotlib.figure import Figure
> matplotlib.interactive(False)
> 
> class App(wx.App):
> 
>     def OnInit(self):
>         self.frame = MainFrame("Autoplotter", (50,60), (700,700))
>         self.frame.Show()
> 
>         return True
> 
> class MainFrame(wx.Frame):
> 
>     def __init__(self, title, pos, size):
>         wx.Frame.__init__(self, None, -1, title, pos, size)
> 
>         pPanel = PlotPanel(self, -1)            # Plot panel
> 
>         bPanel = ButtonPanel(self, 100,500, (200,100))    # button
> panel
> 
>         sizer = wx.BoxSizer(wx.VERTICAL)
> 
>         sizer.Add(pPanel,0)
>         sizer.Add(bPanel,0)
> 
>         self.SetSizer(sizer)
> 
> class ButtonPanel(wx.Panel):
> 
>     def __init__(self, Parent, xPos, yPos, insize):
> 
>         pos = (xPos, yPos)
>         wx.Panel.__init__(self, Parent, -1, pos, style =
> wx.RAISED_BORDER, size = insize)
> 
>         button = wx.Button(self, -1, 'HELLO!!', (10,10), (150,50))
> 
> class NoRepaintCanvas(FigureCanvasWxAgg):
>     """We subclass FigureCanvasWxAgg, overriding the _onPaint method,
> so that
>     the draw method is only called for the first two paint events.
> After that,
>     the canvas will only be redrawn when it is resized.
>     """
>     def __init__(self, *args, **kwargs):
>         FigureCanvasWxAgg.__init__(self, *args, **kwargs)
>         self._drawn = 0
> 
>     def _onPaint(self, evt):
>         """
>         Called when wxPaintEvt is generated
>         """
>         if not self._isRealized:
>             self.realize()
> 
>         if self._drawn < 2:
>             self.draw(repaint = False)
>             self._drawn += 1
> 
>         self.gui_repaint(drawDC=wx.PaintDC(self))
> 
> 
> class PlotPanel(wx.Panel):
> 
>     def __init__(self, parent, id = -1, color = None,\
>                  dpi = None, style = wx.NO_FULL_REPAINT_ON_RESIZE,
> **kwargs):
> 
>         wx.Panel.__init__(self, parent, id = id, style = style,
> **kwargs)
> 
>         self.figure = Figure(None, dpi)
>         self.canvas = NoRepaintCanvas(self, -1, self.figure)
>         self._resizeflag = True
> 
>         self.Bind(wx.EVT_IDLE, self._onIdle)
>         self.Bind(wx.EVT_SIZE, self._onSize)
> 
>         self._SetSize()
> 
>     def draw(self):                           # just draw something!
>         if not hasattr(self, 'subplot'):
>             self.subplot = self.figure.add_subplot(111)
>             theta = arange(0, 45*2*pi, 0.02)
>             rad = (0.8*theta/(2*pi)+1)
>             r = rad*(8 + sin(theta*7+rad/1.8))
>             x = r*cos(theta)
>             y = r*sin(theta)
>             #Now draw it
>             self.subplot.plot(x,y, '-r')
> 
>     def _onSize(self, event):
>         self._resizeflag = True
> 
>     def _onIdle(self, evt):
>          if self._resizeflag:
>              self._resizeflag = False
>              self._SetSize()
>              self.draw()
> 
>     def _SetSize(self, pixels = None):
>         """
>         This method can be called to force the Plot to be a desired
> size, which defaults to
>         the ClientSize of the panel
>         """
>         if not pixels:
>             pixels = self.GetClientSize()
>         self.canvas.SetSize(pixels)
>         self.figure.set_figsize_inches(pixels[0]/
> self.figure.get_dpi(),
>         pixels[1]/self.figure.get_dpi())
> 
> 
> if __name__ == "__main__":
> 
>     app = App(0)
>     app.MainLoop()
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 
> 

-- 
View this message in context: http://www.nabble.com/Embedding-Matplotlib-in-wxpython-wx.Panel-problem-tf3648104.html#a11527402
Sent from the Python - python-list mailing list archive at Nabble.com.



From wildemar at freakmail.de  Wed Jul 18 10:33:22 2007
From: wildemar at freakmail.de (Wildemar Wildenburger)
Date: Wed, 18 Jul 2007 16:33:22 +0200
Subject: Threading XL [was: Re: The Modernization of Emacs: exists already]
In-Reply-To: 
References: <1182093200.598418.218620@e9g2000prf.googlegroups.com>	<1182272678.877166.209640@j4g2000prf.googlegroups.com>	<1184764620.778937.264760@m37g2000prh.googlegroups.com>		<469E1837.9000106@freakmail.de>
	
Message-ID: <469E24B2.70203@freakmail.de>

Rustom Mody wrote:
> Eh? Me? you?? Who???
> Did I say something offensive? Sorry if I did... but I dont understand...
>
>   
No no, it's cool. Maybe I was a little too terse. Xah Lee likes to 
crosspost his pseudo-philosophical tech-musings to several discussion 
groups at regular intervalls. He's not too dumb about it either, he 
usually manages to pick topics that you can easily argue about for ages 
and not get anywhere (He sort of picked too easy a target with emacs 
this time.).
I don't know why he does it, but my personal belief is that he just 
likes to start endless discussions to feel better about himself because 
that proves to him his smarts or something (hence my 
one-word-explanation: Ego). Maybe he has other reasons. I couldn't care 
less. What I do care about is that people just go on and on in these 
threads. It's tedious and I wish people would just ignore the guy (Or 
reply to him directly --- now wouldn't that be fun, people?).


> I must say that I found the earlier post useful to me as an old-time
> emacs user who's not quite upto all the latest stuff.  However it was
> quite off topic for a python list.
>   
I fail to see how anything useful came up in this thread (except for 
antropologists/sociologists maybe), but if it did for you: fine. 
Whatever floats your boat :).


> The flame war that followed was quite a waste of time and bandwidth:
> -- one person who seems to know little blowing his trumpet
> -- others who know a great deal (of emacs) not acknowledging the room
> for improvement
>
> All off topic for a python list
>
>   
Very nice summary.


> Sorry once again if I said something offensive.
>   
Once again: You didn't.

/W


From aahz at pythoncraft.com  Fri Jul 13 18:47:37 2007
From: aahz at pythoncraft.com (Aahz)
Date: 13 Jul 2007 15:47:37 -0700
Subject: Can a low-level programmer learn OOP?
References: 
Message-ID: 

In article ,
Chris Carlen   wrote:
>
>From what I've read of OOP, I don't get it.  

For that matter, even using OOP a bit with C++ and Perl, I didn't get it
until I learned Python.

>The problem for me is that I've programmed extensively in C and .asm on 
>PC DOS way back in 1988.  

Newbie.  ;-)

(I started with BASIC in 1976.)

>Form 2:  Use Python and PySerial and TkInter or wxWidgets.
>
>Pro:  Cross-platform goal will likely be achieved fully.  Have a 
>programmer nearby with extensive experience who can help.
>Con:  Must learn new language and library.  Must possibly learn a 
>completely new way of thinking (OOP) not just a new language syntax. 
>This might be difficult.

My experience is that learning GUI programming is difficult.  Moreover,
GUI programming in C involves a lot of boilerplate that can be automated
more easily with Python.  So I think this will be a better solution.

Note very very carefully that Python does not require an OOP style of
programming, but it will almost certainly be the case that you just
naturally start using OOP techniques as you learn Python.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

I support the RKAB


From gagsl-py2 at yahoo.com.ar  Mon Jul 23 18:43:33 2007
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Mon, 23 Jul 2007 19:43:33 -0300
Subject: Extracting attributes from compiled python code or parse trees
References: <1185225185.546338.84980@m3g2000hsh.googlegroups.com>
Message-ID: 

En Mon, 23 Jul 2007 18:13:05 -0300, Matteo  escribi?:

> I am trying to get Python to extract attributes in full dotted form
> from compiled expression. For instance, if I have the following:
>
> param = compile('a.x + a.y','','single')
>
> then I would like to retrieve the list consisting of ['a.x','a.y'].
>
> The reason I am attempting this is to try and automatically determine
> data dependencies in a user-supplied formula (in order to build a
> dataflow network). I would prefer not to have to write my own parser
> just yet.

If it is an expression, I think you should use "eval" instead of "single"  
as the third argument to compile.

> Alternatively, I've looked at the parser module, but I am experiencing
> some difficulties in that the symbol list does not seem to match that
> listed in the python grammar reference (not surprising, since I am
> using python2.5, and the docs seem a bit dated)

Yes, the grammar.txt in the docs is a bit outdated (or perhaps it's a  
simplified one), see the Grammar/Grammar file in the Python source  
distribution.

> In particular:
>
>>>> import parser
>>>> import pprint
>>>> import symbol
>>>> tl=parser.expr("a.x").tolist()
>>>> pprint.pprint(tl)
>
> [258,
>  [326,
>   [303,
>    [304,
>     [305,
>      [306,
>       [307,
>        [309,
>         [310,
>          [311,
>           [312,
>            [313,
>             [314,
>              [315,
>               [316, [317, [1, 'a']], [321, [23, '.'], [1,
> 'x']]]]]]]]]]]]]]]],
>  [4, ''],
>  [0, '']]
>
>>>> print symbol.sym_name[316]
> power
>
> Thus, for some reason, 'a.x' seems to be interpreted as a power
> expression, and not an 'attributeref' as I would have anticipated (in
> fact, the symbol module does not seem to contain an 'attributeref'
> symbol)

Using this little helper function to translate symbols and tokens:

names = symbol.sym_name.copy()
names.update(token.tok_name)
def human_readable(lst):
   lst[0] = names[lst[0]]
   for item in lst[1:]:
     if isinstance(item,list):
       human_readable(item)

the same tree becomes:

['eval_input',
  ['testlist',
   ['test',
    ['or_test',
     ['and_test',
      ['not_test',
       ['comparison',
        ['expr',
         ['xor_expr',
          ['and_expr',
           ['shift_expr',
            ['arith_expr',
             ['term',
              ['factor',
               ['power',
                ['atom', ['NAME', 'a']],
                ['trailer', ['DOT', '.'], ['NAME', 'x']]]]]]]]]]]]]]]],
  ['NEWLINE', ''],
  ['ENDMARKER', '']]

which is correct is you look at the symbols in the (right) Grammar file.

But if you are only interested in things like a.x, maybe it's a lot  
simpler to use the tokenizer module, looking for the NAME and OP tokens as  
they appear in the source expression.


-- 
Gabriel Genellina



From jjl at pobox.com  Sun Jul  1 12:18:44 2007
From: jjl at pobox.com (John J. Lee)
Date: Sun, 01 Jul 2007 16:18:44 GMT
Subject: using urllib, urllib2 ,
	mechanize to access password protected site
References: <1183038121.174729.230750@c77g2000hse.googlegroups.com>
Message-ID: <87fy48yu57.fsf@pobox.com>

comeshopcheap  writes:

> Hi
>
> I am using this script to access doba.com (I need to download some
> files) but I keep on being sent back to the login page not the user
> home page. Any help. I think I may need to use a post method and
> opener is using a get method
>
> Thanks
>
> import mechanize
> cookies = mechanize.CookieJar()
> # build_opener() adds standard handlers (such as HTTPHandler and
> # HTTPCookieProcessor) by default.  The cookie processor we supply
> # will replace the default one.
> opener =
> mechanize.build_opener(mechanize.HTTPCookieProcessor(cookies))
> opener.addheaders = [("User-agent", "Mozilla/5.0 (Windows; U; Windows
> NT 5.1; en-US; rv:1.8.1.4) Gecko/20070515 Firefox/2.0.0.4"), ]
> data="username=user&password=pw"
> #r = opener.open("http://comeshopcheap.com/")  # GET
> r = opener.open("https://www.doba.com/members/login.php", data)  # POST

You shouldn't need to worry re POST and GET.

Visiting the login page is presumably not enough in itself to log you
in.  So, what are you doing to ensure you're logged in?

Probably you want to fill in and submit the login form on the login
page.  Alternatively, use e.g. mechanize.MozillaCookieJar and load
cookies from your web browser (this option requires that you are
already logged in persistently, though, so I'd suggest filling in the
login form as the safe option).


John


From steve at holdenweb.com  Thu Jul 26 12:24:18 2007
From: steve at holdenweb.com (Steve Holden)
Date: Thu, 26 Jul 2007 12:24:18 -0400
Subject: I am giving up perl because of assholes on clpm -- switching
	to   Python
In-Reply-To: 
References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com>
	
Message-ID: <46A8CAB2.4000508@holdenweb.com>

zentara wrote:
> On Wed, 25 Jul 2007 14:45:29 -0500, Martha_Jones at tx.net wrote:
> 
>> 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
> 
> This is where the big boys play, you have to be able to be able to
> scuffle and take punishment if you are wrong or unduly ignorant.
> You also need to squash somehow who attacks you, when you
> know you are right.
> 
That's about the feeblest excuse for bad manners I have ever heard :-)

Who decides how ignorant "unduly ignorant" is?

I think it's significant that you emphasize gender in your response. I 
believe that this attitude, while not limited to male behavior, is much 
more predominant therein. Sadly there are too few female members of 
either c.l.py or c.l.p.m for it to make much difference.

> I was watching a CNBC yesterday, and they interviewed a leading
> solar panel company's CEO. One guy just blasted him for no reason
> other than he gets a government subsidy, and even the moderator felt
> bad for the way the executive was blasted. BUT...... they are the big
> boys, playing for real money, and if you play there, you have to expect
> to have your toughness tested..... it means real profit and loss.
> 
> If you want a better place to ask beginner questions, or to be treated
> with more respect, try the perl-beginners maillist or
> http://perlmonks.org.  The monks are usually very polite.

So you are saying that disrespect is an appropriate way to behave on a 
newsgroup? That sounds somewhat self-indulgent - you appear to be 
absolving yourself on the responsibility to behave politely in (network) 
company.

On c.l.py there are standards of behavior, and we encourage people to 
observe them (while attempting to engage politely with those who don't). 
I suppose, in fairness, I should admit that the tone of your post is 
actually far more polite than that of the one you were responding to. I 
shudder to think what Martha underwent to make her vent like that ...

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd           http://www.holdenweb.com
Skype: holdenweb      http://del.icio.us/steve.holden
--------------- Asciimercial ------------------
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
----------- Thank You for Reading -------------



From http  Sat Jul 28 03:12:16 2007
From: http (Paul Rubin)
Date: 28 Jul 2007 00:12:16 -0700
Subject: Relative-importing *
References: <1185559874.299008.167010@x40g2000prg.googlegroups.com>
	<871weth2gg.fsf@benfinney.id.au>
	
Message-ID: <7xsl79uhm7.fsf@ruckus.brouhaha.com>

Steven D'Aprano  writes:
> I read "from module import *" as explicitly saying "clobber the current
> namespace with whatever names module exports". That's what from does: it
> imports names into the current namespace. It isn't some sort of easy to
> miss side-effect. If a name already existed, it gets clobbered, just like
> any other import:

Seems to me that there should be a compiler warning when this happens.


From claird at lairds.us  Tue Jul 31 13:33:40 2007
From: claird at lairds.us (Cameron Laird)
Date: Tue, 31 Jul 2007 17:33:40 +0000
Subject: standalone process to interact with the web
References: <1185899130.331170.151980@e16g2000pri.googlegroups.com>
	
Message-ID: 

In article ,
Steve Holden   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 -
>
>   http://wwwsearch.sourceforge.net/mechanize/
>
>With mechanize and its partner ClientForm you can rule the web world ;-)
			.
			.
			.
For a more narrative approach to the same point, I like to think
that 
helps.


From bignose+hates-spam at benfinney.id.au  Thu Jul 26 22:55:39 2007
From: bignose+hates-spam at benfinney.id.au (Ben Finney)
Date: Fri, 27 Jul 2007 12:55:39 +1000
Subject: Comparing Dictionaries
References: 
Message-ID: <87abtih7x0.fsf@benfinney.id.au>

Kenneth Love  writes:

> In other words, I consider these two dictionaries to be equivalent:
> 
>     { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'mickey' }
>     { 'mouse' : 'mickey', 'dog' : 'bone', 'cat' : 'fever' }
> 
> while these two are not:
> 
>     { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'mickey' }
>     { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'michael' }
> 
> Any suggestions on how to compare these via some assert statement?

Dictionaries already know how to compare themselves to each other.

    >>> {'dog': 'bone', 'cat': 'fever', 'mouse': 'mickey'} == {'mouse': 'mickey', 'dog': 'bone', 'cat': 'fever'}
    True
    >>> {'dog': 'bone', 'cat': 'fever', 'mouse': 'mickey'} == {'mouse': 'michael', 'dog': 'bone', 'cat': 'fever'}
    False

-- 
 \     "Many are stubborn in pursuit of the path they have chosen, few |
  `\                  in pursuit of the goal."  -- Friedrich Nietzsche |
_o__)                                                                  |
Ben Finney


From mensanator at aol.com  Sun Jul 29 14:59:07 2007
From: mensanator at aol.com (mensanator at aol.com)
Date: Sun, 29 Jul 2007 11:59:07 -0700
Subject: 128 or 96 bit integer types?
In-Reply-To: <46ab05a9$0$1345$834e42db@reader.greatnowhere.com>
References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com>
	
	<1185562901.206212.52570@j4g2000prf.googlegroups.com>
	
	<1185607142.096574.209200@e16g2000pri.googlegroups.com>
	<46ab05a9$0$1345$834e42db@reader.greatnowhere.com>
Message-ID: <1185735547.172823.20030@x40g2000prg.googlegroups.com>

On Jul 28, 3:34 am, David H Wild  wrote:
> In article <1185607142.096574.209... at e16g2000pri.googlegroups.com>,
>    mensana... at aol.com  wrote:
>
> > For example, how many ways can you put 492 marbles into
> > 264 ordered bins such that each bin has at least 1 marble?
> > The answer
> > 66189415264331559482776409694993032407028709677550
> > 59629130019289014193777349831417543311612293951363
> > 4124491233746912456893016976209252459301489030
> > has 146 digits.
>
> What on  earth made you think of that question?

Reearch on the Collatz Conjecture. Any Collatz
sequence can be described by a non-empty list of
integers > 0. Such as

[1,1,1,1,1,1,1,1]
[1,2,3,4,5,6]
[1009873,74396597698765,2,240895734075]

I proved that ANY posible list must exist on the
Collatz graph infinitely many times. The polynomials
derived from such a list identify the first occurence
of the set of infinite solutions.

For a sequence in 3n+C to be a loop cycle, it is
necessary (but not sufficient) for a power of 2
(2**p) to be congruent to a power of 3 (3**q) modulo
a divisor of C.

For example, the congruence classes of 2**p mod 41 are

(1,2,4,5,8,9,10,16,18,20,21,23,25,31,32,33,36,37,39,40)

the congruence classes of 3**q mod 41 are
(1,3,9,14,27,32,38,40)

The only classes they have in common are: {1,9,32,40}
so from this table,

p or q   2p (mod 41)   3q (mod 41)

0             1             1
1             2             3
2             4             9
3             8            27
4            16            40
5            32            38
6            23            32
7             5            14
8            10             1
9            20             3
10           40             9
11           39            27
12           37            40
13           33            38
14           25            32
15            9            14
16           18             1
17           36             3
18           31             9
19           21            27
20            1            40

only those p,q pairs (such as p=20 q=8) that have
matching congruence classes mod 41 can be potential
loop cycles in 3n+41.

This can be translated to the marble problem by asking
how many ways are there to make a list of q non-zero
positive integers that sum to p?

Of the 50388 ways, 8 of them have integer solutions
and because these 8 are cyclic permutaions, they
represent the same loop cycle

     [2,1,3,1,2,1,1,9] 1
     [1,3,1,2,1,1,9,2] 11
     [3,1,2,1,1,9,2,1] 37
     [1,2,1,1,9,2,1,3] 19
     [2,1,1,9,2,1,3,1] 49
     [1,1,9,2,1,3,1,2] 47
     [1,9,2,1,3,1,2,1] 91
     [9,2,1,3,1,2,1,1] 157

To actually answer you question, there is a known loop
cycle in 3n+85085 for which p=492 and q=264. If there is
one solution, there must be at leats 263 others (the
cyclic permutations), but to brute force search for any
others would require enumerating the answer to how many
ways can 492 marbles be put in 264 bins such that each
bin has at least 1 marble.

>
> --
> David Wild using RISC OS on broadbandwww.davidhwild.me.uk




From patohara at bozemanpass.com  Tue Jul 17 13:11:54 2007
From: patohara at bozemanpass.com (Pat O'Hara)
Date: Tue, 17 Jul 2007 11:11:54 -0600
Subject: Relative Imports
Message-ID: <469CF85A.9090205@bozemanpass.com>

Hey guys, I know this is a really stupid question, but I've tried 
googling and nothing came up. I also tried IRC, but it was too crowded 
and I didn't get much useful information.

I'm using Python 2.5 on WinXP, and I'm trying to do a relative import. 
Here's the package structure

A/
   __init__.py
   aneededmodule.py
   [some more modules]
   B/
      __init__.py
      anothermodule.py

anothermodule.py needs to use aneededmodule.py; package A's __init__.py 
looks like this:

from aneededmodule import somestuff

My problem is that when anothermodule tries to import ..aneededmodule or 
..somestuff (because somestuff was imported into __init__), I get a 
ValueError: Attempted relative import in non-package.

What's my problem? This seems like something very trivial, but I've 
never had to use python for a project of this size before, so I've never 
dealt with this.

Thanks for your help,
-Pat


From openopt at ukr.net  Sun Jul  1 05:04:27 2007
From: openopt at ukr.net (dmitrey)
Date: Sun, 01 Jul 2007 02:04:27 -0700
Subject: howto resend args and kwargs to other func?
In-Reply-To: 
References: <1183279997.244378.105810@n60g2000hse.googlegroups.com>
	
Message-ID: <1183280667.542964.175570@u2g2000hsc.googlegroups.com>

On Jul 1, 12:00 pm, Duncan Booth  wrote:

> You 'need something like this', so write something like that.
> Did you intend to ask a question?

I would gladly write the one, but the example doesn't work, and I
don't know any easy way (moreover any way) to make it work correctly.
D.



From samwyse at gmail.com  Sat Jul  7 23:01:53 2007
From: samwyse at gmail.com (samwyse)
Date: Sun, 08 Jul 2007 03:01:53 -0000
Subject: Re-raising exceptions with modified message
In-Reply-To: 
References: 
Message-ID: <1183863713.876365.111820@57g2000hsv.googlegroups.com>

On Jul 5, 8:53 am, Christoph Zwerschke  wrote:
> What is the best way to re-raise any exception with a message
> supplemented with additional information (e.g. line number in a
> template)? Let's say for simplicity I just want to add "sorry" to every
> exception message.

OK, this seems pretty minimal, yet versatile.   It would be nice to be
able to patch the traceback, but it turns out that it's fairly hard to
do. If you really want to do that, however, go take a look at
http://lucumr.pocoo.org/cogitations/2007/06/16/patching-python-tracebacks-part-two/


# Written by Sam Denton 
# You may use, copy, or distribute this work,
# as long as you give credit to the original author.
def rewriten_exception(old, f):
    class Empty(): pass
    new = Empty()
    new.__class__ = old.__class__
    new.__dict__ = old.__dict__.copy()
    new.__str__ = f
    return new

def test(code):
    try:
        code()
    except Exception, e:
        raise rewriten_exception(e, lambda: str(e) + ", sorry!")

test(lambda: unicode('\xe4'))
test(lambda: 1/0)



From tom at finland.com  Fri Jul 13 13:44:13 2007
From: tom at finland.com (tom at finland.com)
Date: Fri, 13 Jul 2007 17:44:13 GMT
Subject: NoneType object not iterable
Message-ID: 

Hi!
My code is

 > db = {}
 >
> def display():
>     keyList = db.keys()
>     sortedList = keyList.sort()
>     for name in sortedList:
>         line = 'Name: %s, Number: %s' % (name, db[name])
>         print line.replace('\r', '')

And it gives following error:

>     for name in sortedList:
> TypeError: 'NoneType' object is not iterable

How can sortedList variable turn into NoneType? I just don't get it...


From deets at nospam.web.de  Sat Jul  7 02:57:09 2007
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sat, 07 Jul 2007 08:57:09 +0200
Subject: C++ Modules for python: How to?
In-Reply-To: <1183764388.576690.31740@n60g2000hse.googlegroups.com>
References: <1183750094.154566.248170@m36g2000hse.googlegroups.com>
	<5f7llqF3bfvstU1@mid.uni-berlin.de>
	<1183764388.576690.31740@n60g2000hse.googlegroups.com>
Message-ID: <5f8rqaF3bgs8vU1@mid.uni-berlin.de>

> 
> How do I install SIP? I can't seem to do this. I've downloaded the
> package and read the README file, but I don't see a way of installing
> it on windows. I ran the configure.py file but then it generates
> makefiles to run which can't be run on windows. I also attempted to
> download QT but it doesn't appear to be free (it's an evaluation and I
> don't feel like submitting my personal information to download it).
> 
> Am I missing something? Thank you for your reply.

I've compiled SIP and Qt with mingw on windows. But you don't need Qt 
for SIP.

Diez


From ahlongxp at gmail.com  Fri Jul 13 10:44:21 2007
From: ahlongxp at gmail.com (ahlongxp)
Date: Fri, 13 Jul 2007 14:44:21 -0000
Subject: How to create new files?
In-Reply-To: <1184274877.612434.26870@k79g2000hse.googlegroups.com>
References: <1184274877.612434.26870@k79g2000hse.googlegroups.com>
Message-ID: <1184337861.559491.253220@e9g2000prf.googlegroups.com>

On Jul 13, 5:14 am, Robert Dailey  wrote:
> Hi,
>
> I'm trying to create a Python equivalent of the C++ "ifstream" class,
> with slight behavior changes.
>
> Basically, I want to have a "filestream" object that will allow you to
> overload the '<<' and '>>' operators to stream out and stream in data,
> respectively. So far this is what I have:
>
> class filestream:
>         def __init__( self, filename ):
>                 self.m_file = open( filename, "rwb" )
>
> #       def __del__( self ):
> #               self.m_file.close()
>
>         def __lshift__( self, data ):
>                 self.m_file.write( data )
>
>         def __rshift__( self, data ):
>                 self.m_file.read( data )
>
> So far, I've found that unlike with the C++ version of fopen(), the
> Python 'open()' call does not create the file for you when opened
> using the mode 'w'. I get an exception saying that the file doesn't
> exist. I expected it would create the file for me. Is there a way to
> make open() create the file if it doesn't exist, or perhaps there's
> another function I can use to create the file? I read the python docs,
> I wasn't able to find a solution.
>
using "w" or "wb" will create new file if it doesn't exist.
at least it works for me.
> Also, you might notice that my "self.m_file.read()" function is wrong,
> according to the python docs at least. read() takes the number of
> bytes to read, however I was not able to find a C++ equivalent of
> "sizeof()" in Python. If I wanted to read in a 1 byte, 2 byte, or 4
> byte value from data into python I have no idea how I would do this.
>
f.read(10) will read up to 10 bytes.
you know what to do now.

> Any help is greatly appreciated. Thanks.

and another thing to mention, __del__() will not always be called( any
comments?).
so you'd better flush your file explicitely by yourself.

--
ahlongxp

Software College,Northeastern University,China
ahlongxp at gmail.com
http://www.herofit.cn





From cunheise at gmail.com  Fri Jul 27 14:04:09 2007
From: cunheise at gmail.com (cunheise@yahoo.com.cn)
Date: Fri, 27 Jul 2007 11:04:09 -0700
Subject: Factory pattern again
In-Reply-To: 
References: <11825158.post@talk.nabble.com>
	<46a9c21f$0$18765$426a74cc@news.free.fr>
	
Message-ID: <1185559449.103726.75520@e9g2000prf.googlegroups.com>

first you need find the bottleneck of your script db or function
if the bottleneck is db
1. which db do you use do you optimize the db from read
2. the sql you write do not use any index "maybe select code, type
from products where type = 'I' or type = 'S' will help" and you need
create index on type field maybe you need set limit 2000 to sql depend
on your requirement

On Jul 27, 11:26 pm, Mike Howarth  wrote:
> Having overcome my first hurdle with the factory pattern, I've now hit
> another stumbling block
>
> At the moment I'm trying to return around 2000 records from a db and load up
> the relevant product object, what I've found is this is running extremely
> slowly (> 20mins), the db is normalized and indexes exist.
>
> Can anyone advise on how best I could speed this up?
>
>    def getWebRangeProducts(self):
>
>         if self.c.connected:
>
>             cu = self.c.cursor #create the cursor
>
>             sql = "SELECT type, code FROM products"
>
>             cu.execute(sql)
>
>             if cu.rowcount > 0:
>
>                 rows = cu.fetchall()
>
>                 for row in rows:
>
>                    self.loadProduct(row[0].strip(),row[1].strip())
>
>                 return self.products
>
>     def loadProduct(self,type,product_code):
>
>         print type + ":" + product_code
>
>         if type == 'I':
>
>             try:
>                 product = factory('Item', product_code)
>                 self.products.append(product)
>             except:
>                 print 'problem occured:' + type + ':' + product_code
>
>         elif type == 'S':
>
>             try:
>                 item_set = factory('Set', product_code)
>                 item_set.getItems()
>                 self.products.extend(item_set.getItems())
>             except:
>                 print 'problem occured:' + type + ':' + product_code
>
>         else:
>             pass
>
>
>
> Bruno Desthuilliers-5 wrote:
>
> > Mike Howarth a ?crit :
> >> Hi
>
> >> I was wondering whether anyone could help me, I'm pretty new to python
> >> coming from a PHP background and I'm having a few products in getting my
> >> head round how to write the factory pattern within python.
>
> >> I'm currently looking to try to return values from a db and load up the
> >> relevant objects, values returned are product type (I,S) and product code
> >> (123).
>
> >> At the moment I've adapted some code I've found illustrating the factory
> >> method but ideally I would like to use the type to load up the relevant
> >> object.
>
> >> Another issue I've found is that I don't seem to be able to access to the
> >> price attribute of each of the object. I'm sure these are very
> >> straightforward issues however I seem to have tied myself in knots over
> >> this
> >> and could do with a fresh set of 'pythonic' eyes to help me out.
>
> >> registry = {}
>
> >> class MetaBase(type):
> >>      def __init__(cls, name, bases, dict):
> >>          registry[name] = cls
>
> >> class Product(object):
> >>      __metaclass__ = MetaBase
>
> >> class Item(Product):
> >>      def __init__(self, *args, **kw):
> >>          self.price = 1
>
> >> class Set(Product):
> >>      def __init__(self, *args, **kw):
> >>          self.price = 2
>
> >> def factory(kind, *args, **kw):
> >>      return registry[kind](*args, **kw)
>
> >> item = registry['Item']
>
> > This returns the Item *class*, not an instance of... So the following:
>
> >> print item.price
>
> > cannot work, since price is an instance attribute, not a class attribute.
>
> > What you want is:
>
> > item = factory('Item')
> > print item.price
>
> > HTH
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> --
> View this message in context:http://www.nabble.com/Factory-pattern-again-tf4156186.html#a11831500
> Sent from the Python - python-list mailing list archive at Nabble.com.





From oren.tsur at gmail.com  Mon Jul 23 10:29:36 2007
From: oren.tsur at gmail.com (oren.tsur at gmail.com)
Date: Mon, 23 Jul 2007 14:29:36 -0000
Subject: Parsing XML with ElementTree (unicode problem?)
Message-ID: <1185200976.082516.105420@57g2000hsv.googlegroups.com>

(this question was also posted in the devshed python forum:
http://forums.devshed.com/python-programming-11/parsing-xml-with-elementtree-unicode-problem-461518.html
).
-----------------------------

(it's a bit longish but I hope I give all the information)

1. here is my problem: I'm trying to parse an XML file (saved locally)
using elementtree.parse but I get the following error:
xml.parsers.expat.ExpatError: not well-formed (invalid token): line
13, column 327
apparently, the problem is caused by the token 'Sauni?re' due to the
apostrophe.

the thing is that I'm sure that python (ElementTree module and parse()
function) can handle this type of encoding since I obtain my xml file
from the web by opening it with:

from elementtree import ElementTree
from urllib import urlopen
query = r'http://ecs.amazonaws.com/onca/xml?
Service=AWSECommerceService&AWSAccessKeyId=189P5TE3VP7N9MN0G302&Operation=ItemLookup&ItemId=1400079179&ResponseGroup=Reviews&ReviewPage=166'
root = ElementTree.parse(urlopen(query))

where query is a query to the AWS, and this specific query has the
'Sauni?re' in the response. (you could simply open the query with a
web browser and see the xml).

I create a local version of the XML file, containing only the tags
that are of interest. my file looks something like this (I replaced
some of the content with 'bla bla' string in order to make it fit
here):


805 3
5 6
2004-04-03
Not as good as Angels and Demons
I found that this book was not as good and thrilling as
Angels and Demons. bla bla.



827 4
2 8
2004-04-01
The Da Vinci Code, a master piece of words
The Da Vinci Code by Dan Brown is a well-written bla bla. The
story starts out in Paris, France with a murder of Jacque Sauni?re,
the head curator at Le Louvre.bla bla 



BUT, then trying:

fIn  = open(file,'r') #or even 'import codecs'  and opening with 'fIn
= codecs.open(file,encoding = 'utf-8')'
tree = ElementTree.parse(fIn)



where file is the saved file, I get the error above
(xml.parsers.expat.ExpatError: not well-formed (invalid token): line
13, column 327). so what's the difference? how comes parsing is fine
in the first case but erroneous in the second case? please advise.

2. there is another problem that might be similar I get a similar
error if the content of the (locally saved) xml have special
characters such as '&', for example in 'angles & demons' (vs. 'angles
and demons'). is it the same problem? same solution?

thanks!



From timid.Gentoo at gmail.com  Thu Jul  5 14:56:49 2007
From: timid.Gentoo at gmail.com (_spitFIRE)
Date: Thu, 05 Jul 2007 18:56:49 -0000
Subject: SMTP server w/o using Twisted framework
In-Reply-To: 
References: <1183659790.338100.199900@g4g2000hsf.googlegroups.com>
	
Message-ID: <1183661809.613856.312100@57g2000hsv.googlegroups.com>

On Jul 5, 1:34 pm, "Jeff McNeil"  wrote:
> If you just want to send mail, you should be able to use the standard
> smtplib module (http://docs.python.org/lib/module-smtplib.html). If
> your recipients are on the Internet, you would need to handle MX
> resolution yourself.
>

How complicated is to handle the MX resolution by myself? I'm sorry
that I don't have a clue regarding that. Any pointers would be greatly
appreciated.

> I know you said you want to avoid a relay server, but it's probably
> the best bet unless you control the SMTP infrastructure or are simply
> sending messages locally.

The problem is that with the scenario I'm faced with, I don't have any
reliable SMTP server that I can use. Hence, I though I will spawn my
own light-weight SMTP server that can send mails to the people I want,
on the Internet. But, from what you are saying it seems, it might not
be that light weight after all!

> Otherwise, you'll probably need to also
> implement queuing and retry logic (depending on your requirements).

Isn't there a library module that can help me implement all this?

> There are also some warning lights that may go off and flag your mail
> as spam if you're using a method like that...
>
> -Jeff

Would you please fill me in with some pointers as to why my mail might
get flagged as spam? Would it be considered spam even if I've a valid
from address, and a proper message/subject? Does the spam filter also
rely on the sending server's DNS etc because of which you say it might
get flagged as spam?



From arkanes at gmail.com  Tue Jul 24 15:39:21 2007
From: arkanes at gmail.com (Chris Mellon)
Date: Tue, 24 Jul 2007 14:39:21 -0500
Subject: Hacking with __new__
In-Reply-To: <1185299898.927797.29520@g4g2000hsf.googlegroups.com>
References: <1185241394.990936.206360@k79g2000hse.googlegroups.com>
	
	<46a5d26b$0$18658$426a74cc@news.free.fr>
	<1185299898.927797.29520@g4g2000hsf.googlegroups.com>
Message-ID: <4866bea60707241239u56acce0p6a459ecc8530de1@mail.gmail.com>

On 7/24/07, Sandra-24  wrote:
> On Jul 24, 5:20 am, Bruno Desthuilliers  42.desthuilli... at wtf.websiteburo.oops.com> wrote:
> > IIRC, __new__ is supposed to return the newly created object - which you
> > are not doing here.
> >
> > class Bar(Foo):
> >      def __new__(cls, a, b, c, *args):
> >          print 'Bar.__new__', len(args)
> >          if not args:
> >              cls = Zoo
> >          obj = super(Bar, cls).__new__(cls, a, b, c, *args)
> >          if not args:
> >              obj.__init__(a, b, c, 7)
> >          return obj
>
> Thanks guys, but you are right Bruno, you have to return the newly
> created object or you get:
>
> >>> b = Bar(1,2,3)
> Bar.__new__ 0
> Foo.__new__ 3
> Zoo.__init__ 4
> Foo.__init__ 3
> >>> b is None
> True
>
> However, if you return the object you get:
>
> >>> b = Bar(1, 2, 3)
> Bar.__new__ 0
> Foo.__new__ 3
> Zoo.__init__ 4
> Foo.__init__ 3
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: __init__() takes exactly 5 arguments (4 given)
>
> Which is the same blasted error, because it seems to want to call init
> on the returned object and it's calling it with 4 args :( Is there any
> way around that?
>

__init__ is going to be called with the arguments passed to __new__
and there doesn't seem to be any way to affect that. Your only option
to make it not happen is for Zoo not to be a subclass of Bar.

Possible workarounds:
Each subclass of Bar needs a corresponding __new__

Each subclass of Bar needs a cooperating __init__ that detects (via
optional arguments) if it's being called by Bar.__new__ or directly
and noops in the second case.


From evan at yelp.com  Mon Jul  2 14:53:45 2007
From: evan at yelp.com (Evan Klitzke)
Date: Mon, 2 Jul 2007 11:53:45 -0700
Subject: Python compilation ??
In-Reply-To: 
References: 
Message-ID: 

On 7/2/07, Cathy Murphy  wrote:
> Is python a compiler language or interpreted language. If it is interpreter
> , then why do we have to compile it?

It's an interpreted language. It is compiled into bytecode (not
machine code) the first time a script is run to speed up subsequent
executions of a script.

-- 
Evan Klitzke 


From http  Thu Jul 26 20:29:26 2007
From: http (Paul Rubin)
Date: 26 Jul 2007 17:29:26 -0700
Subject: question about math module notation
References: 
	<7xd4ye7vv9.fsf@ruckus.brouhaha.com>
	
	<7xejiukhjz.fsf@ruckus.brouhaha.com>
	<1185495629.464194.313300@57g2000hsv.googlegroups.com>
Message-ID: <7xvec6heop.fsf@ruckus.brouhaha.com>

Dan Bishop  writes:
> > I was surprised to find that gives an exact (integer, not
> > floating-point) answer.  Still, I think it's better to say 2**64
> > which also works for (e.g.) 2**10000 where math.pow(2,10000)
> > raises an exception.
> 
> It *is* binary floating point.  Powers of 2 are exactly
> representable.  Of course, it doesn't give an exact answer in general.
> 
> >>> int(math.pow(10, 23))
> 99999999999999991611392L

Oh yikes, good point.  math.pow(2,64) is really not appropriate for
what the OP wanted, I'd say.  If you want integer exponentiation, then
write it that way.  Don't do a floating point exponentiation that just
happens to not lose precision for the specific example.

    >>> int(math.pow(3,50)) # wrong
    717897987691852578422784L
    >>> 3**50  # right
    717897987691852588770249L


From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Mon Jul 23 06:26:13 2007
From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
Date: Mon, 23 Jul 2007 12:26:13 +0200
Subject: decorators tutorials
In-Reply-To: <1185183257.471106.318070@x35g2000prf.googlegroups.com>
References: <1185178383.499234.299850@z24g2000prh.googlegroups.com>
	<1185180112.321457.73170@n2g2000hse.googlegroups.com>
	<1185183257.471106.318070@x35g2000prf.googlegroups.com>
Message-ID: <46a48245$0$19544$426a34cc@news.free.fr>

james_027 a ?crit :
> Hi all,
> 
> I am having difficulty understanding decorator. The definition was
> clear for me, but the syntax is not so clear to me.
> 
> will decorators will always have to be in this way
> 
> def check_login(func):
>     def _check_login(*args):
>         print "I am decorator"
>         return func(*args)
>     return _check_login
> 

Sort of... Well, depends...

Basically, a decorator is a callable taking a callable as argument and 
returning a callable. These callable are usually *but* not necessarily 
functions. You may want to read the section about the special method 
__call__ in the  Fine Manual.

Also, you may want to write a 'parameterized' decorator - a decorator 
taking arguments. In this case, you need one more wrapping level:

def check_login(msg):
   def check_login_deco(func):
     def _check_login(*args, **kw):
       print msg
       return func(*args, **kw)
     return _check_login
   return check_login_deco

@check_login("I am the decorator")
def my_func(toto, tata):
   print toto, tata




From alexandre.ferrieux at gmail.com  Mon Jul 23 05:18:35 2007
From: alexandre.ferrieux at gmail.com (Alexandre Ferrieux)
Date: Mon, 23 Jul 2007 02:18:35 -0700
Subject: Lazy "for line in f" ?
In-Reply-To: 
References: <1185120650.412694.314280@o61g2000hsh.googlegroups.com>
	
	<1185143634.778056.227720@g4g2000hsf.googlegroups.com>
	
	<1185173778.656660.195650@n60g2000hse.googlegroups.com>
	<7xbqe3efm5.fsf@ruckus.brouhaha.com>
	<1185177589.837857.105390@r34g2000hsd.googlegroups.com>
	
Message-ID: <1185182315.489049.271010@r34g2000hsd.googlegroups.com>

On Jul 23, 10:33 am, Duncan Booth 
wrote:
>
> The extra buffering means that iterating over a file is about 3 times
> faster than repeatedly calling readline.
>
>     while 1:
>         line = f.readline()
>         if not line:
>             break
>
>     for line in f:
>         pass
>

Surely you'll notice that the comparison is spoilt by the fact that
the readline version needs an interpreted test each turn around.
A more interesting test would be the C-implemented iterator, just
calling fgets() (the thin layer policy) without extra 8k-blocking.

-Alex



From steve at holdenweb.com  Wed Jul 25 18:04:03 2007
From: steve at holdenweb.com (Steve Holden)
Date: Wed, 25 Jul 2007 18:04:03 -0400
Subject: is_iterable function.
In-Reply-To: <1185392870.4432.62.camel@dot.uniqsys.com>
References: 	<1185389920.275300.174900@q75g2000hsh.googlegroups.com>	<5uNpi.36822$G23.3430@newsreading01.news.tds.net>
	<1185392870.4432.62.camel@dot.uniqsys.com>
Message-ID: 

Carsten Haese wrote:
> On Wed, 2007-07-25 at 19:26 +0000, Neil Cerutti wrote:
>> Speaking of the iter builtin function, is there an example of the
>> use of the optional sentinel object somewhere I could see?
> 
> Example 1: If you use a DB-API module that doesn't support direct cursor
> iteration with "for row in cursor", you can simulate it this way:
> 
> for row in iter(cursor.fetchone, None):
>    # do something
> 
[...]
This would, of course, be a horribly inefficient way to handle a 
database result with 1,500,000 rows. Calling fetchall() might also have 
its issues. The happy medium is to use a series of calls to fetchmany(N) 
with an appropriate value of 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 nytrokiss at gmail.com  Mon Jul  9 17:30:33 2007
From: nytrokiss at gmail.com (James Matthews)
Date: Mon, 9 Jul 2007 14:30:33 -0700
Subject: Choosing Tkinter over wxPython...
In-Reply-To: <3e384$4692a3c4$4275d90a$11745@FUSE.NET>
References: <3e384$4692a3c4$4275d90a$11745@FUSE.NET>
Message-ID: <8a6b8e350707091430s7ff43f5el4f5081bc381e042c@mail.gmail.com>

Sorry i am a wxpython person! TKinter wouldn't work for me so i moved to
wxPython. However try pyQT or pyGTK both seem to be good toolkits and have
large user bases

On 7/9/07, Kevin Walzer  wrote:
>
> I've spent some time playing with both, and while wxPython is nice,
> Tkinter just seems to fit my head better, and with appropriate selection
> of widgets and interface design, seems to yield up perfectly usable GUI's.
>
> Can anyone else who finds Tkinter better for them than wxPython (or the
> other toolkits) explain why it works for them?
>
> --
> Kevin Walzer
> Code by Kevin
> http://www.codebykevin.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://www.goldwatches.com/watches.asp?Brand=14
http://www.jewelerslounge.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From steve at holdenweb.com  Sun Jul 15 17:37:13 2007
From: steve at holdenweb.com (Steve Holden)
Date: Sun, 15 Jul 2007 17:37:13 -0400
Subject: 2**2**2**2**2 wrong? Bug?
In-Reply-To: 
References: 	<1184042559.120947.124560@k79g2000hse.googlegroups.com>	<1184050285.997766.299860@d55g2000hsg.googlegroups.com>		<1184351416.166930.290710@k79g2000hse.googlegroups.com>		<1184362323.476796.22570@w3g2000hsg.googlegroups.com>
	
Message-ID: 

Wayne Brehaut wrote:
> On Fri, 13 Jul 2007 14:32:03 -0700, "mensanator at aol.com"
[...]
> But I digress (but only because provoked!)...
> 
>>> [for purposes of this argument, at least]
> 
> This statement is the informal equivalent to  saying  "Define a base-1
> number system as...", as I noted above. If you'd noted this, and
> understood it, or were willing to accept it whether or not you
> understood it, you'd have saved us both some bother--but me more than
> you I guess, so maybe you were just trolling?
> 
wwway to beat a response to a pulp. Sometimes it's easier and better for 
your blood pressure just to let someone else have the last word, however 
ill-informed or hostile.

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 abhingar at bellsouth.net  Tue Jul 10 06:16:55 2007
From: abhingar at bellsouth.net (Atul Bhingarde)
Date: Tue, 10 Jul 2007 06:16:55 -0400
Subject: highly einteractive editor for python
References: 
	
Message-ID: 

What I want to see is that it is possible to create a python based 
application in a environment where I can see the results as I am creating 
it, specifically gui widgets (from say TK). This will provide a robust 
mechanism to see gui layout as well.

Thanks

Atul
"Josiah Carlson"  wrote in message 
news:BsFki.19734$2v1.17797 at newssvr14.news.prodigy.net...
> Atul Bhingarde wrote:
>> Does anybody know an editor that facilitates, interactive python 
>> development. Where GUI etc developed will be possible to see in real time 
>> mode.
>
> Boa Constructor?  wxGlade embedded in some other software (SPE?)  XRCed? 
> What do you mean by "real time mode"?
>
>  - Josiah 




From bbxx789_05ss at yahoo.com  Mon Jul  2 00:00:31 2007
From: bbxx789_05ss at yahoo.com (7stud)
Date: Sun, 01 Jul 2007 21:00:31 -0700
Subject: unicode
In-Reply-To: <1183348316.943369.230970@q75g2000hsh.googlegroups.com>
References: <1183267580.178435.265640@o61g2000hsh.googlegroups.com>
	
	<1183318859.305908.218960@w5g2000hsg.googlegroups.com>
	<46880b1a$0$22417$9b622d9e@news.freenet.de>
	<1183348316.943369.230970@q75g2000hsh.googlegroups.com>
Message-ID: <1183348831.983714.292640@k29g2000hsd.googlegroups.com>

On Jul 1, 9:51 pm, 7stud  wrote:
> Hi,
>
> Thanks for the detailed response.
>
> On Jul 1, 2:14 pm, "Martin v. L?wis"  wrote:
>
> > > 1) If you print a unicode string:
>
> > > a) str() calls encode(), and encode() tries to convert the unicode
> > > string to a regular string.  encode() uses the default encoding, which
> > > is ascii.  If encode() can't convert a character, then encode() raises
> > > an exception.
>
> > Yes and no. This is what str() does, but str() isn't called. Instead,
> > print inspects sys.stdout.encoding, and uses that encoding to encode
> > the string. That, in turn, may raise an exception (in particular if
> > sys.stdout.encoding is "ascii" or not set).
>
> Is that the same as print calling encode(u_str, sys.stdout.encoding)

ooops.  I mean is that the same as print calling
u_str.encode(sys.stdout.encoding)?



From paul at boddie.org.uk  Tue Jul  3 19:03:27 2007
From: paul at boddie.org.uk (Paul Boddie)
Date: Tue, 03 Jul 2007 16:03:27 -0700
Subject: Chroot Jail Not Secure for Sandboxing Python?
In-Reply-To: <1182787116.717732.35390@q75g2000hsh.googlegroups.com>
References: <1182748892.916068.146780@p77g2000hsh.googlegroups.com>
	<467f55f7$0$20850$9b622d9e@news.freenet.de>
	<1182782910.811850.284350@u2g2000hsc.googlegroups.com>
	<1182787116.717732.35390@q75g2000hsh.googlegroups.com>
Message-ID: <1183503807.200323.213810@k29g2000hsd.googlegroups.com>

Paul Boddie wrote:
>

[chroot "jail" solutions]

> I don't have the details with me now, but I'll probably upload the
> code in the near future and post some kind of explanation of what it
> does here.

I've now uploaded the code to the Python Package Index:

http://www.python.org/pypi/jailtools

It's a bit unpolished and anyone wanting to experiment with it should
look at the code to see, for example, what each of the test programs
do. I do *not* claim that this is a secure solution: it's an
experiment where a Python process is started with access only to a set
of "approved" modules, whose identity becomes that of a particular
user, and whose environment is that of a chroot "jail", with
"sandboxed" code only then being executed inside that environment.
Anyone looking for something to deploy as a solution should look
elsewhere.

Paul



From mgi820 at motorola.com  Mon Jul 30 13:27:14 2007
From: mgi820 at motorola.com (Gary Duzan)
Date: Mon, 30 Jul 2007 17:27:14 +0000 (UTC)
Subject: File handle not being released by close
References: <1185806160.161748.58910@d55g2000hsg.googlegroups.com>
Message-ID: 

In article <1185806160.161748.58910 at d55g2000hsg.googlegroups.com>,
  wrote:
>
> [ ... ]
>
>for fileName in fileNames:
>  fileBeginning = os.path.splitext(fileName)[0]
>  fileEnd       = os.path.splitext(fileName)[1]
>
>  if fileEnd == ".py":
>    print fileName
>    f=open(fileBeginning+".tmp", 'w')
>    f.write("Hello")
>    f.close
     f.close()

					Gary Duzan
					Motorola CHS




From kib2 at free.fr  Mon Jul 16 05:04:05 2007
From: kib2 at free.fr (tool69)
Date: Mon, 16 Jul 2007 11:04:05 +0200
Subject: running a Delphi part from Python ?
In-Reply-To: <86c61$469b30d1$d443bb3a$15805@news.speedlinq.nl>
References: <889c1$469b275c$d443bb3a$2876@news.speedlinq.nl>
	<469b2b65$0$21672$426a74cc@news.free.fr>
	<86c61$469b30d1$d443bb3a$15805@news.speedlinq.nl>
Message-ID: <469b3530$0$26995$426a74cc@news.free.fr>

Stef Mientki a ?crit :

> AFAIK, Scintilla is a code editor.
> What I need looks more like ms-word,
> handling lists, tables, images, formulas.
> 
> thanks,
> Stef Mientki


So you'll need the RichTextCtrl

http://www.wxpython.org/docs/api/wx.richtext.RichTextCtrl-class.html

See a sample in the demo under "Recent Additions".


From aisaac at american.edu  Thu Jul 12 20:44:02 2007
From: aisaac at american.edu (Alan Isaac)
Date: Fri, 13 Jul 2007 00:44:02 GMT
Subject: Fastest way to convert a byte of integer into a list
In-Reply-To: <1184284861.695430.99300@e9g2000prf.googlegroups.com>
References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com>
	<1184284461.506663.75500@g12g2000prg.googlegroups.com>
	<1184284861.695430.99300@e9g2000prf.googlegroups.com>
Message-ID: 

> On Jul 13, 9:54 am, Matimus  wrote:
>>num = 255
>>numlist = [num >> i & 1 for i in range(8)]
 

Godzilla wrote:
> Thanks matimus! I will look into it...
 

Watch out for the order, which might
or might not match your intent.

Cheers,
Alan Isaac


From gnewsg at gmail.com  Wed Jul 11 12:54:27 2007
From: gnewsg at gmail.com (billiejoex)
Date: Wed, 11 Jul 2007 09:54:27 -0700
Subject: asyncore and OOB data
Message-ID: <1184172867.420979.215300@q75g2000hsh.googlegroups.com>

Hi there,
In an asyncore based FTP server I wrote I should be able to receive
OOB data from clients.
A client sending such kind of data should act like this:

>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(('127.0.0.1', 21))
>>> s.sendall('hello there\r\n', socket.MSG_OOB)

According to asyncore documentation I should handle this kind of event
in "handle_expt" method of dispatcher class, that should be called
when OOB is received by the underlying socket. I've tried to override
handle_expt method in such way:

    def handle_expt(self):
        print "OOB data arrived"
        data = self.socket.recv(1024, socket.MSG_OOB)
        print data

...but, even if it is called, "data" contains only a "\n" character
instead of the entire string ("hello there\r\n").
Why does this happen? Should I have to use a different approach?

Thanks in advance.



From wildemar at freakmail.de  Wed Jul 25 11:31:52 2007
From: wildemar at freakmail.de (Wildemar Wildenburger)
Date: Wed, 25 Jul 2007 17:31:52 +0200
Subject: code indentation
In-Reply-To: <1185357861.989194.117000@r34g2000hsd.googlegroups.com>
References: 		<1185297657.186852.136950@k79g2000hse.googlegroups.com>		<87lkd5jt83.fsf@benfinney.id.au>
	<1185357861.989194.117000@r34g2000hsd.googlegroups.com>
Message-ID: <46A76CE8.6070500@freakmail.de>

vedrandekovic at v-programs.com wrote:
>> And while we're on the topic of communication: The original poster
>> would do well to learn that increasing the number of consecutive
>> punctuation marks (!!!, ???) is a sure way to turn away many people
>> who would otherwise be helpful. Sentences need at most one '!' or '?',
>> adding more does not improve the chances of being taken seriously.
>>     
>
> And if you can help me than please help me , but if you can't then
> please don't leave me some stupid messages
>   

Whats stupid about this? It's sane advice.

Which looks more serious to you:

this:
I can't do it!!!! Can you PLEASE help me????!!!?!

or this:
I don't know the answer. Can you please help me?

Even if it makes no difference to you, to many people it does. So Ben is 
right: People *will* take your posts more seriously if you restrict your 
use of punctuation (if only because its easier to read).
Don't feel offended, nobody was trying to put you down.

/W


From no at no.no  Fri Jul 13 12:13:24 2007
From: no at no.no (Daniel)
Date: Fri, 13 Jul 2007 19:13:24 +0300
Subject: Getting values out of a CSV
References: <1184295593.638409.22910@22g2000hsm.googlegroups.com>
	
	
	
	
	 <5fpcdeF3dm8bpU2@mid.uni-berlin.de>
Message-ID: 

On Fri, 13 Jul 2007 16:18:38 +0300, Marc 'BlackJack' Rintsch  
 wrote:
>> $ python -m timeit -c 'import csv; data =  
>> list(csv.reader(open("some.csv",
>> "rb")))'
>> 10000 loops, best of 3: 44 usec per loop
>> $ python -m timeit -c 'import csv; data = [row for row in
>> csv.reader(open("some.csv", "rb"))]'
>> 10000 loops, best of 3: 37 usec per loop
>>
>> I don't know why there seems to be a differece, but I know that list  
>> comps
>> are python are very heavily optimised.
>
> Does the machine use power saving features like SpeedStep or
> something similar, i.e. runs the processor always with 100% speed or is  
> it
> dynamically stepped if there's load on the processor?  Do both tests read
> the data always from cache or has the very first loop had to fetch the  
> CSV
> file from disk?
>
> $ python -m timeit -n 1000 -c 'import csv; data = [row for row in
> csv.reader(open("test.csv", "rb"))]' 1000 loops, best of 3: 1.27 msec per
> loop
>
> $ python -m timeit -n 1000 -c 'import csv; data =
> list(csv.reader(open("test.csv", "rb")))' 1000 loops, best of 3: 1.25  
> msec
> per loop

No SpeedStep - tried a few repeats just in case files were cached,  
consistent 35usec for comp 40usec for list

Python 2.5.1 on Linux 1.2ghz

Even replacing the csv lookup with a straight variable declaration:  
[range(10)*3], same results

Weird.

Python


From bravo.loic at gmail.com  Tue Jul 17 03:58:10 2007
From: bravo.loic at gmail.com (bravo.loic at gmail.com)
Date: Tue, 17 Jul 2007 00:58:10 -0700
Subject: Compiling python2.5 on IBM AIX
In-Reply-To: <1184600488.343686.263220@d55g2000hsg.googlegroups.com>
References: <1184581796.377610.98230@o61g2000hsh.googlegroups.com>
	<1184600488.343686.263220@d55g2000hsg.googlegroups.com>
Message-ID: <1184659090.881833.124240@x35g2000prf.googlegroups.com>

> I haven't compiled it myself, but I'm told that the installation I
> work with was compiled with:
>
> export PATH=$PATH:/usr/vacpp/bin:/usr/vacpp/lib
> ./configure --with-gcc="xlc_r -q64" --with-cxx="xlC_r -q64" --disable-
> ipv6 AR="ar -X64"
> make
> make install

I've tried with the followong configuration :
----------
export PATH=$PATH:/usr/vacpp/bin:/usr/vacpp/lib
./configure --prefix=${BASE} --with-gcc="xlc_r -q64" --with-cxx="xlC_r
-q64" --disable-ipv6 AR="ar -X64" LDFLAGS="-L\${BASE}/lib/" PPFLAGS="-I
\${BASE}/include/"

make
---------

but it doesn't compile either :

make
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Modules/python.o ./Modules/python.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Modules/_typesmodule.o Modules/_typesmodule.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Parser/acceler.o Parser/acceler.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Parser/grammar1.o Parser/grammar1.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Parser/listnode.o Parser/listnode.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Parser/node.o Parser/node.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Parser/parser.o Parser/parser.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Parser/parsetok.o Parser/parsetok.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Parser/bitset.o Parser/bitset.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Parser/metagrammar.o Parser/metagrammar.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Parser/firstsets.o Parser/firstsets.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Parser/grammar.o Parser/grammar.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Parser/pgen.o Parser/pgen.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Parser/myreadline.o Parser/myreadline.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Parser/tokenizer.o Parser/tokenizer.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Objects/abstract.o Objects/abstract.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Objects/boolobject.o Objects/boolobject.c
        xlc_r -q64 -c  -DNDEBUG -O  -I. -I./Include   -DPy_BUILD_CORE -
o Objects/bufferobject.o Objects/bufferobject.c
"Objects/bufferobject.c", line 22.15: 1506-275 (S) Unexpected text ','
encountered.
make: 1254-004 The error code from the last command is 1.

any idea ?

thanks

--
BL



From sschwarzer at sschwarzer.net  Sun Jul 22 11:36:12 2007
From: sschwarzer at sschwarzer.net (Stefan Schwarzer)
Date: Sun, 22 Jul 2007 17:36:12 +0200
Subject: [ANN] ftputil 2.2.3 released
Message-ID: 

ftputil 2.2.3 is now available from
http://ftputil.sschwarzer.net/download .

Changes since version 2.2.2
---------------------------

This release fixes a bug in the ``makedirs`` call (report and fix by
Julian, whose last name I don't know ;-) ). Upgrading is recommended.

What is ftputil?
----------------

ftputil is a high-level FTP client library for the Python programming
language. ftputil implements a virtual file system for accessing FTP
servers, that is, it can generate file-like objects for remote files.
The library supports many functions similar to those in the os,
os.path and shutil modules. ftputil has convenience functions for
conditional uploads and downloads, and handles FTP clients and servers
in different timezones.

Read the documentation at
http://ftputil.sschwarzer.net/documentation .

License
-------

ftputil is Open Source software, released under the revised BSD
license (see http://www.opensource.org/licenses/bsd-license.php ).

Stefan

-- 
Dr.-Ing. Stefan Schwarzer
SSchwarzer.com - Softwareentwicklung f?r Technik und Wissenschaft
http://sschwarzer.com


From andre.roberge at gmail.com  Mon Jul 30 10:49:57 2007
From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=)
Date: Mon, 30 Jul 2007 14:49:57 -0000
Subject: Detecting __future__ features
In-Reply-To: 
References: 
	
	<1185800016.950517.43240@g4g2000hsf.googlegroups.com>
	
	<5h68ggF3idk61U1@mid.uni-berlin.de>
	
Message-ID: <1185806997.605006.317050@19g2000hsx.googlegroups.com>

On Jul 30, 11:10 am, Neil Cerutti  wrote:
> On 2007-07-30, Diez B. Roggisch  wrote:
>
> > Making the switch between different parser-implementations on
> > the fly isn't technically impossible - but really, really,
> > really complicated. But then, if it's lameness sucks so much,
> > you might wanna take a stab at it?
>
> I was considering the following specific quote:
>
>   What if you are designing a module meant to be imported, and
>   used by other programs over which you have no control?   You
>   can't use "from __future__ import" in your module."
>
> If that were true, I think it would indeed be lame. Of course, it
> isn't true, right?
>

Yes, it was my mistake; I replied too quicly from a faulty memory
bank...

(extract foot from mouth ... inhale deeply to resupply oxygen to the
brain ...)
Andr?

> --
> Neil Cerutti




From duncan.booth at invalid.invalid  Mon Jul 23 04:33:36 2007
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 23 Jul 2007 08:33:36 GMT
Subject: Lazy "for line in f" ?
References: <1185120650.412694.314280@o61g2000hsh.googlegroups.com>
	
	<1185143634.778056.227720@g4g2000hsf.googlegroups.com>
	
	<1185173778.656660.195650@n60g2000hse.googlegroups.com>
	<7xbqe3efm5.fsf@ruckus.brouhaha.com>
	<1185177589.837857.105390@r34g2000hsd.googlegroups.com>
Message-ID: 

Alexandre Ferrieux  wrote:

> On Jul 23, 9:36 am, Paul Rubin  wrote:
>> Alexandre Ferrieux  writes:
>> > So I'll reiterate the question: *why* does the Python library add 
that
>> > extra layer of (hard-headed) buffering on top of stdio's ?
>>
>> readline?
> 
> I know readline() doesn't have this problem. I'm asking why the file
> iterator does.
> 
Here's a program which can create a large file and either read it with 
readline or iterate over the lines. Output from various runs should 
answer your question.

The extra buffering means that iterating over a file is about 3 times 
faster than repeatedly calling readline.

C:\Temp>test.py create 1000000
create file
Time taken=7.28 seconds

C:\Temp>test.py readline
readline
Time taken=1.03 seconds

C:\Temp>test.py iterate
iterate
Time taken=0.38 seconds

C:\Temp>test.py create 10000000
create file
Time taken=47.28 seconds

C:\Temp>test.py readline
readline
Time taken=10.39 seconds

C:\Temp>test.py iterate
iterate
Time taken=3.58 seconds


------- test.py ------------
import time, sys

NLINES = 10
def create():
    print "create file"
    f = open('testfile.txt', 'w')
    for i in range(NLINES):
        print >>f, "This is a test file with a lot of lines"
    f.close()

def readline():
    print "readline"
    f = open('testfile.txt', 'r')
    while 1:
        line = f.readline()
        if not line:
            break
    f.close()

def iterate():
    print "iterate"
    f = open('testfile.txt', 'r')
    for line in f:
        pass
    f.close()

def doit(fn):
    start = time.time()
    fn()
    end = time.time()
    print "Time taken=%0.2f seconds" % (end-start)

if __name__=='__main__':
    if len(sys.argv) >= 3:
        NLINES = int(sys.argv[2])

    if sys.argv[1]=='create':
        doit(create)
    elif sys.argv[1]=='readline':
        doit(readline)
    elif sys.argv[1]=='iterate':
        doit(iterate)

----------------------------


From wildemar at freakmail.de  Wed Jul 25 11:32:52 2007
From: wildemar at freakmail.de (Wildemar Wildenburger)
Date: Wed, 25 Jul 2007 17:32:52 +0200
Subject: From D
In-Reply-To: 
References: <1185272393.484032.125180@22g2000hsm.googlegroups.com>	<46a6086d$0$8399$9b622d9e@news.freenet.de>	<5gmthsF3hc0n2U1@mid.individual.net>
	
Message-ID: <46A76D24.20906@freakmail.de>

Steven D'Aprano wrote:
> Python already does:
> "hello-" "world" => "hello-world"
>
> Propose:
> 123 456 789 => 123456789
> 123.456 789 => 123.456789
>
>   
I second that!

/W



From orsenthil at users.sourceforge.net  Wed Jul  4 15:51:34 2007
From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran)
Date: Thu, 5 Jul 2007 01:21:34 +0530
Subject: Tkinter toggle a Label Widget based on checkbutton value
Message-ID: <20070704195134.GA3690@gmail.com>

Following is a tk code, which will display a checkbutton, and when checkbox is
enabled, it will show the below present Label.

What I was trying is, when checkbox is enabled the Label should be shown and
when checkbox is disabled, the window should look like before.

But, I am finding that once enabled (shown), its not very-straightforward to
hide it from the window.

Any suggestions on  how can i make this checkbutton effect.
1) Press Enable IP, the Label IP should be shown.
2) Toggle Enable IP (So that its unset). the Label IP should not be shown.

#!/usr/bin/python
from Tkinter import *
root = Tk()
root.title('something')
x = StringVar()
def display():
    if x.get():
        ip = Label(root,text="IP:")
        ip.grid(row=3,column=0)

proxy = Checkbutton(root, text="Enable IP:", variable = x,onvalue="proxy",
        offvalue="",command=display)
proxy.grid(row=2,column=0)
root.mainloop()


-- 
O.R.Senthil Kumaran
http://uthcode.sarovar.org


From gagsl-py2 at yahoo.com.ar  Wed Jul 25 21:56:53 2007
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Wed, 25 Jul 2007 22:56:53 -0300
Subject: first, second, etc line of text file
References: 
	
Message-ID: 

En Wed, 25 Jul 2007 19:14:28 -0300, James Stroud   
escribi?:

> Daniel Nogradi wrote:
>> A very simple question: I currently use a cumbersome-looking way of
>> getting the first, second, etc. line of a text file:
>
> to_get = [0, 3, 7, 11, 13]
> got = dict((i,s) for (i,s) in enumerate(open(textfile)) if i in to_get)
> print got[3]
>
> This would probably be the best way for really big files and if you know
> all of the lines you want ahead of time.

But it still has to read the complete file (altough it does not keep the  
unwanted lines).
Combining this with Paul Rubin's suggestion of itertools.islice I think we  
get the best solution:
got = dict((i,s) for (i,s) in  
enumerate(islice(open(textfile),max(to_get)+1)) if i in to_get)

-- 
Gabriel Genellina



From bdesth.quelquechose at free.quelquepart.fr  Sun Jul 22 00:38:30 2007
From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers)
Date: Sun, 22 Jul 2007 06:38:30 +0200
Subject: is_iterable function.
In-Reply-To: 
References: 
Message-ID: <46a7a1e9$0$31506$426a34cc@news.free.fr>

Neil Cerutti a ?crit :
> def is_iterable(obj):
>     try:
>         iter(obj)
>         return True
>     except TypeError:
>         return False
> 
> Is there a better way?

The only other alternative I see is worse:

def iterable(obj):
   # strings are iterable and don't have an __iter__ method...
   for name in ('__iter__', '__getitem__'):
     try:
       getattr(obj, name)
       return True
     except AttributeError:
       pass
  else:
    return False




From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Mon Jul 16 08:20:53 2007
From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
Date: Mon, 16 Jul 2007 14:20:53 +0200
Subject: questions about functions inside a function
In-Reply-To: 
References: 
Message-ID: <469b62a4$0$27165$426a74cc@news.free.fr>

fdu.xiaojf at gmail.com a ?crit :
> I want to create a list of function.
> 
> Here is my code:
> In [9]: a = []
> 
> In [10]: for i in range(4):
>    ....:     b = lambda : i**2
>    ....:     a.append(b)
>    ....:
>    ....:
> 
> In [11]: for f in a:
>    ....:     f()
>    ....:
>    ....:
> 9
> 9
> 9
> 9
> 
> What I want is, the value of i should be bounded to the anonymous 
> function. And the output should like this:
> 
> for f in a:
>     print f()
> 0
> 1
> 4
> 9
> 
> How to achieve this?
> 
 >>> a = [lambda i=i:i**2 for i in range(4)]
 >>> for f in a:
...     print f()
...
0
1
4
9
 >>>

HTH


From horpner at yahoo.com  Fri Jul 20 15:22:55 2007
From: horpner at yahoo.com (Neil Cerutti)
Date: Fri, 20 Jul 2007 19:22:55 GMT
Subject: Pythonic way for missing dict keys
References: 
Message-ID: 

On 2007-07-20, Alex Popescu  wrote:
> Hi all!
>
> I am pretty sure this has been asked a couple of times, but I
> don't seem to find it on the archives (Google seems to have a
> couple of problems lately).
>
> I am wondering what is the most pythonic way of dealing with missing 
> keys and default values.
>
> According to my readings one can take the following approaches:

There's also the popular collections.defaultdict. 

Usually, the get method of normal dicts is what I want. I use a
defaultdict only when the implicit addition to the dictionary of
defaulted elements is what I really want.

-- 
Neil Cerutti


From Martha_Jones at tx.net  Wed Jul 25 15:45:29 2007
From: Martha_Jones at tx.net (Martha_Jones at tx.net)
Date: Wed, 25 Jul 2007 14:45:29 -0500
Subject: I am giving up perl because of assholes on clpm -- switching to Python
Message-ID: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com>

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


From cam.ac.uk at mh391.invalid  Fri Jul 13 06:08:36 2007
From: cam.ac.uk at mh391.invalid (Michael Hoffman)
Date: Fri, 13 Jul 2007 11:08:36 +0100
Subject: Getting values out of a CSV
In-Reply-To: 
References: <1184295593.638409.22910@22g2000hsm.googlegroups.com>
	
	
	
Message-ID: 

Daniel wrote:
> On Fri, 13 Jul 2007 08:51:25 +0300, Gabriel Genellina 
>  wrote:
 >
>> Note that every time you see [x for x in ...] with no condition, you 
>> can write list(...) instead - more clear, and faster.
 >
> Faster? No. List Comprehensions are faster.

Why do you think that?
-- 
Michael Hoffman


From byte8bits at gmail.com  Thu Jul 26 16:49:34 2007
From: byte8bits at gmail.com (brad)
Date: Thu, 26 Jul 2007 16:49:34 -0400
Subject: question about math module notation
In-Reply-To: <7xd4ye7vv9.fsf@ruckus.brouhaha.com>
References: 
	<7xd4ye7vv9.fsf@ruckus.brouhaha.com>
Message-ID: 

Paul Rubin wrote:
> print 2**64

Ah yes, that works too... thanks. I've settled on doing it this way:

print int(math.pow(2,64))

I like the added parenthesis :)


From Brad.Johnson at ballardtech.com  Fri Jul 27 15:06:32 2007
From: Brad.Johnson at ballardtech.com (Brad Johnson)
Date: Fri, 27 Jul 2007 12:06:32 -0700
Subject: Problem embedding in small Win32 App
Message-ID: 

I received no responses yesterday, this is a repost. I'm still stuck on
this one ladies and gentlemen, and I'm sure it's one of those simple
things (isn't it always?)

I am creating a small test application in Windows to test the embedding
of the interpreter in order to execute arbitrary Python statements and
print their results, all via a dialog application.

Strings are sent to the interpreter via:

	PyRun_String(CString(*pbstrInput), Py_file_input, _d, _d);

Where _d is my global dictionary.

I would like to capture the output, so I created a small class to extend
Python:

      PyRun_String("class OutputCatcher:\n"
        "\tdef __init__(self):\n"
        "\t\tself.data=''\n"
        "\tdef write(self, stuff):\n"
        "\t\tself.data = stuff\n\n"
        "import sys\n"
        "_outcatcher = OutputCatcher()\n"
        "sys.stdout = _outcatcher\n",
        Py_file_input, _d, _d);

Using this class, I thought I could access "_outcatcher.data" to get the
last thing written to sys.stdout, and this does seem to work using the
following code:

      PyObject* o = PyDict_GetItemString(_d, "_outcatcher");
      PyObject* a = PyObject_GetAttrString(o, "data");
      ::MessageBox(NULL, PyString_AsString(a), _T(""), NULL);

However, it only works twice. On the third try, I get an access
violation trying to access the stdout object (for a print statement).
The pointer appears to be valid, but all of the data has overwritten
with 0xDBDBDBDB, with obvious consequences. 

Thanks for your help in advance.

~Brad Johnson


From Graham.Dumpleton at gmail.com  Wed Jul  4 21:01:14 2007
From: Graham.Dumpleton at gmail.com (Graham Dumpleton)
Date: Thu, 05 Jul 2007 01:01:14 -0000
Subject: mod_python & doc file system layout
In-Reply-To: <468bad13$1@griseus.its.uu.se>
References: <468bad13$1@griseus.its.uu.se>
Message-ID: <1183597274.592953.28660@x35g2000prf.googlegroups.com>

On Jul 5, 12:22 am, Jan Danielsson  wrote:
> Hello all,
>
>    This is probably more of an apache question, but I'm guessing there
> will be other mod_python-beginners who are wondering the same thing.
>
>    Let's say I have a web app called MyApp. It uses the usual images and
> style sheets. I keep it all in
> ~/projects/MyApp/{styles,images,index.py,.htaccess}. I configure up
> apache to use virtual hosts, and point it to MyApp.
>
>    Now when I access myapp.local (which points to 127.0.0.1, obviously),
> my index.py is parsed properly. However, any access made to /images or
> /styles end up being handled by mod_python, which isn't good, because it
> won't load images or style sheets.
>
>    I have solved this by moving index.py (and the associated .htaccess)
> to a subdirectory "main".
>
>    I guess one solution would be to make an access to / on the virtual
> server redirect to main.
>
>    Another solution, I guess, would be to make the python script load
> the images and style sheets.. A solution which I find to be particularly
> ugly. :-)
>
>    Any mod_python users out there with any other solutions?

In the subdirectories containing your static files add a .htaccess
file containing:

  SetHandler None

Graham



From timr at probo.com  Mon Jul 30 00:33:37 2007
From: timr at probo.com (Tim Roberts)
Date: Mon, 30 Jul 2007 04:33:37 GMT
Subject: 128 or 96 bit integer types?
References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com>
	
	<1185562901.206212.52570@j4g2000prf.googlegroups.com>
	
	<1185607142.096574.209200@e16g2000pri.googlegroups.com>
Message-ID: <5hqqa3dv7f8sk5r34mo2p7o7d85oeqtjv7@4ax.com>

"mensanator at aol.com"  wrote:
>
>So I never let the age of the universe intimidate me.

+1 QOTW.
-- 
Tim Roberts, timr at probo.com
Providenza & Boekelheide, Inc.


From hamish at cloud.net.au  Wed Jul 11 06:59:29 2007
From: hamish at cloud.net.au (Hamish Moffatt)
Date: Wed, 11 Jul 2007 20:59:29 +1000
Subject: SafeConfigParser can set unsafe values
In-Reply-To: <1184131252.068248.159390@o11g2000prd.googlegroups.com>
References: <46940a3e$0$18464$afc38c87@news.optusnet.com.au>
	<1184111631.293350.106340@o11g2000prd.googlegroups.com>
	
	<1184131252.068248.159390@o11g2000prd.googlegroups.com>
Message-ID: <4694b811$0$14986$afc38c87@news.optusnet.com.au>

Matimus wrote:
>> I agree, but that was a trivial example to demonstrate the problem.
>> Writing the file out to disk writes it exactly as set(), causing a get()
>> to fail just the same later.
> 
> No... The above statement is not true.

Yes, it is. Whatever you set gets written out directly. Your example 
proves this:

> cp.set("sect","opt","hello%world")
> cp.write(sys.stdout)
> [/code]
> 
> Produces this output:
> [sect]
> opt = hello%world

Then when you get() this value later, it fails.

> The write method never calls get. However, when you read the file that
> was output by the above code using .get(...) will raise an error. You
> can avoid that error by setting the optional 'raw' parameter to True.

But then you have disabled substitution, which is not the same thing! I 
don't necessarily want to disable substitution, I just want transparent 
handling of lone %s.

Since SafeConfigParser.get() is fussy about the format of interpolation 
instructions, SafeConfigParser.set() can safely know when you're not 
trying to use them and escape lone percents.

To summarise: set() should not set something which get() will ALWAYS 
fail on!


Hamish


From tinaweb at bestemselv.com  Fri Jul 27 05:40:01 2007
From: tinaweb at bestemselv.com (Tina I)
Date: Fri, 27 Jul 2007 11:40:01 +0200
Subject: Submit form, open result in a browser
Message-ID: 

Hi,

Is there a way to submit a form and then open the resulting page in the 
default browser? (Writing the form submission code is not a problem by 
the way)
I guess what I'm asking is how I can get the resulting URL and feed it 
to the webbrowser module.
I need to do it this way because the site owners will not let me parse 
the page and show the result inside my application... loss of 
advertising revenue I guess. And since it's just a small added feature 
to the application, opening it in a browser is fine. I just need to get 
an idea on how to do it...

Thanks
Tina


From jstroud at mbi.ucla.edu  Wed Jul 25 17:09:42 2007
From: jstroud at mbi.ucla.edu (James Stroud)
Date: Wed, 25 Jul 2007 14:09:42 -0700
Subject: I am giving up perl because of assholes on clpm -- switching
	to Python
In-Reply-To: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com>
References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com>
Message-ID: 

Martha_Jones at tx.net wrote:
> 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

You have convinced me to subscribe to clpm! Sounds like it will be fun 
reading.

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/


From jorge.vargas at gmail.com  Sun Jul  1 23:58:45 2007
From: jorge.vargas at gmail.com (Jorge Vargas)
Date: Sun, 1 Jul 2007 23:58:45 -0400
Subject: How to uninstall packages
In-Reply-To: 
References: 
	<200707012003.05390.thomas@jollans.com>
	
Message-ID: <32822fe60707012058g2ca32b62mea422ecf33d0de6e@mail.gmail.com>

On 7/1/07, Rustom Mody  wrote:
> Yeah sure thats what is (finally) working but its never clear upfront
> for a package what its dependency needs are -- linux version of DLL
> hell.  And it gets worse for systems that are little worlds in
> themselves like python, ruby, eclipse, webmin etc.  because they have
> their own package-management systems which invariably quarell with the
> native apt/rpm or whatever...
>
IMO the problem is two folds

1- distros and "little worlds" as you call them, not getting in sync
as to why or how is the best way to handle packages. which results in
incompatible installations, for example anything that installs with
setuptools is almost 100% incompatible with anything installed by
emerge,apt,etc. because in general (at least that's the case with
distros I have used) they handle setuptools packages like normal
distutils and handle the dependecies "externally".

2- setuptools/distutils having no uninstall option this is mainly
because of the fact that noone has sit down and write a clear way to
make sure a package is not needed anymore. which will clearly put
setuptools in the land of apt or rpm, but then what happens when a
setuptools package depends on something like gnome which isn't handle
this way.

so yes it's a big mess.

> On 7/1/07, Thomas Jollans  wrote:
> > On Sunday 01 July 2007, Rustom Mody wrote:
> >
> > > I first installed the debian package python-pysqlite1.1 using
> > > synaptic. Since this seemed too old for other packages (sqlalchemy) I
> > > downloaded the sources  pysqlite-2.3.4.tar.gz and ran setup install.
> >
> > I wonder why you chose not to use python-pysqlite2...
> > --
> > http://mail.python.org/mailman/listinfo/python-list
> >
> --
> http://mail.python.org/mailman/listinfo/python-list
>


From xxmplus at gmail.com  Wed Jul 11 19:01:00 2007
From: xxmplus at gmail.com (xxmplus at gmail.com)
Date: Wed, 11 Jul 2007 23:01:00 -0000
Subject: highly einteractive editor for python
In-Reply-To: 
References: 
Message-ID: <1184194860.424325.292430@z28g2000prd.googlegroups.com>

On Jul 9, 5:14 pm, "Atul Bhingarde"  wrote:
> Does anybody know an editor that facilitates, interactive python
> development. Where GUI etc developed will be possible to see in real time
> mode.
>
> Thanks
>
> Atul

Have a look at UliPad:
http://wiki.woodpecker.org.cn/moin/UliPad



From missive at frontiernet.net  Thu Jul 12 18:24:15 2007
From: missive at frontiernet.net (Lee Harr)
Date: Thu, 12 Jul 2007 22:24:15 GMT
Subject: Class decorators do not inherit properly
References: 
Message-ID: 

> Traceback (most recent call last):
>   File "/Users/chris/Projects/CMR/closed.py", line 132, in 
>     class M0(MetropolisHastings):
>   File "/Users/chris/Projects/CMR/closed.py", line 173, in M0
>     @_add_to_post
> NameError: name '_add_to_post' is not defined
>
> yet, when I look at the dict of the subclass (here called M0), I see the 
> decorator method:
>


I think the term "class decorator" is going to eventually
mean something other than what you are doing here. I'd
avoid the term for now.


When you decorate a class method, the function you use
needs to be defined before the method definition.

Using a class method to decorate another class method is
going to be tricky. The way I usually do it is to create
a separate function outside of the class definition for
the decorator function.


You're going to have to show us the actual code you are
having trouble with, or else (probably more useful, really)
try to put together a minimal example of what you are
trying to do and show us that code.



From gagsl-py2 at yahoo.com.ar  Mon Jul  9 06:47:58 2007
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Mon, 09 Jul 2007 07:47:58 -0300
Subject: Portable general timestamp format, not 2038-limited
References: <1182544384.709759.235300@o11g2000prd.googlegroups.com>
	
Message-ID: 

En Thu, 05 Jul 2007 17:57:32 -0300, Wojtek  escribi?:

> Note: Since I am using the year 9999 as a "magic number", some of you
> may think that I am repeating the Y2K problem. Hey, if my application
> is still being used in the year 9998 I am not being paid nearly
> enough...

I would not say the code itself, but some design decisions may survive for  
a long time. Like the railroad inter-rail distance, which even for the  
newest trains, remains the same as used by Stephenson in England two  
centuries ago - and he choose the same width as used by common horse carts  
at the time. (Some people goes beyond that and say it was the same width  
as used in the Roman empire but this may be just a practical coincidence,  
no causality being involved).

-- 
Gabriel Genellina



From steve at holdenweb.com  Thu Jul 26 15:11:29 2007
From: steve at holdenweb.com (Steve Holden)
Date: Thu, 26 Jul 2007 15:11:29 -0400
Subject: Why PHP is so much more popular for web-development
In-Reply-To: <7xlkd3m1si.fsf@ruckus.brouhaha.com>
References: <1185385374.866372.198520@x35g2000prf.googlegroups.com>		<1185392048.737400.290050@j4g2000prf.googlegroups.com>	<13ahh6kosqqeba1@corp.supernews.com>
	<7xlkd3m1si.fsf@ruckus.brouhaha.com>
Message-ID: 

Paul Rubin wrote:
> Jeffrey Froman  writes:
>> Consider a PHP-based CMS that allows users to upload files. Because the
>> application runs as the webserver user, uploaded files, and the directory
>> where they reside, must be accessible and writable by that user. It is the
>> same user that any other hosting customer on that machine has access to.
>> Thus, any user on the shared host could write a quick CGI script that
>> accesses, adds, removes, or defaces your uploaded content.
> 
> That sounds trivial to ameliorate (at least somewhat) by putting your
> uploads in a directory whose name is known only to you (let's say it's
> a random 20-letter string).  The parent directory can be protected to
> not allow reading the subdirectory names.

But you have to admit that's "security by obscurity".

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 stesch at no-spoon.de  Thu Jul 26 16:48:22 2007
From: stesch at no-spoon.de (Stefan Scholl)
Date: Thu, 26 Jul 2007 22:48:22 +0200
Subject: Any reason why cStringIO in 2.5 behaves different from 2.4?
References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de>
	<46A86C70.8040707@web.de>
	<0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de>
	<0T49cr71I3edNv8%stesch@parsec.no-spoon.de>
	<46A8AA57.4010802@web.de>
Message-ID: <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de>

Stefan Behnel  wrote:
> The XML is *not* well-formed if you pass Python unicode instead of a byte
> encoded string. Read the XML spec.

Pointers, please.

Last time I read that part of the spec was when a customer's
consulting company switched to ISO-8859-15 without saying
something beforehand. The old code (PHP) I have to maintain
couldn't deal with it.

It was wrong to switch encoding without telling somebody about
it. And a XML processor isn't required to support ISO-8859-15.
But I thought it was too embarrassing not to support this
encoding. I fixed that part without making a fuss.


A Python XML processor that can't handle the own encoding is
embarrassing. It isn't required to support it. It would be OK if
it wouldn't support UTF-7. But a parseString() method that
doesn't want Python strings? No way!


-- 
Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/


From nick at craig-wood.com  Thu Jul 19 04:30:03 2007
From: nick at craig-wood.com (Nick Craig-Wood)
Date: Thu, 19 Jul 2007 03:30:03 -0500
Subject: Interprocess communication woes
References: <1184810559.180382.179220@j4g2000prf.googlegroups.com>
Message-ID: 

Murali  wrote:
>  After some investigation, I found out that this problem had nothing to
>  do with my GUI app not getting refreshed and I was able to reproduce
>  this problem with normal python scripts. Here is one such script
> 
>  #File test.py
>  from subprocess import Popen
>  from subprocess import PIPE
>  import sys
>  if __name__ == '__main__':
>   prog = sys.argv[1]
>   proc = Popen(prog, shell = True, stdout = PIPE, bufsize = 0)
>   out = proc.stdout
>   while proc.poll() is None:
>     print out.readline()
> 
>  Run this program as follows
>  $ test.py "ping -c 10 www.google.com"
> 
>  Now, you would see the responses as if you just launched ping on the
>  command line. Now, lets look at another program. Here is a simple C++
>  program that prints numbers 1 to 10 at the passage of every second
>  (sort of a stopwatch)
> 
>  #include 
>  #include 
>  #include 
>  main ( )
>  {
>   timeval t1, t2;
>   gettimeofday(&t1, NULL);
>   int prev = -1;
>   int cur = 0;
>   while (true)
>   {
>     gettimeofday(&t2,NULL);
>     if(t2.tv_sec - t1.tv_sec > 10)
>       break;
>     else
>     {
>       cur = t2.tv_sec-t1.tv_sec;
>       if (cur != prev)
>       {
>         printf("%d\r\n",cur);
>         prev = cur;
>       }
>     }
>   }
>  }
> 
>  if you would build this program and call it lets say timer ($ g++ -o
>  timer timer.cpp)  and run it with our python script like this
> 
>  $python test.py "./timer"
> 
>  you would see that every time you run the program your results vary
>  and on top of this the stdout of the timer program gets displayed all
>  at once presumably when the timer program has completed execution.
> 
>  Why this discrepancy between the ping and timer programs? Is my
>  test.py script correct? Is there a better or a preferred method for
>  doing interprocess communication in Python.

Buffering is your problem.

If you add a fflush(stdout); after the printf(...); you'll find the
c++ program works as you expect.

It is just a fact of life of the C stdio system.  If it is connected
to a terminal then it will turn off buffering.  If it is connected
anything else (eg a pipe via subprocess) then it will buffer stuff as
you've seen.

So you can

a) modify the c++ prog to add fflush() in or use setvbuf()
b) use the pexpect module - http://pexpect.sourceforge.net/
c) use the pty module (unix only)

The pexpect module will connect to the subprogram with pseudo-ttys,
fooling the program, and the C library, into thinking that it is
speaking to a terminal and turn off buffering.  Pexpect doesn't work
on windows.

The fact that ping works is because it uses fflush() - you can see
this if you "ltrace" it.

-- 
Nick Craig-Wood  -- http://www.craig-wood.com/nick


From http  Tue Jul 10 19:41:58 2007
From: http (Paul Rubin)
Date: 10 Jul 2007 16:41:58 -0700
Subject: bool behavior in Python 3000?
References:  
	
	
	
Message-ID: <7xzm23ygft.fsf@ruckus.brouhaha.com>

Steven D'Aprano  writes:
> Pretending that False and True are just "magic names" for 0 and 1 might be
> "easier" than real boolean algebra, but that puts the cart before the
> horse. Functionality comes first: Python has lists and dicts and sets
> despite them not being ints, and somehow newcomers cope. I'm sure they
> will cope with False and True not being integers either.

Are they are aren't they?

print 1 in [True]
print 1 == True
print len(set(map(type, [1, 1])))
print len(set(map(type, [1, True])))


From hg at nospam.org  Sun Jul  1 16:09:28 2007
From: hg at nospam.org (hg)
Date: Sun, 01 Jul 2007 15:09:28 -0500
Subject: ctype and functions that return a pointer to a structure
Message-ID: 

Hi,

I have the following code:
******************************************
from ctypes import * 
g_lib = cdll.LoadLibrary("libc.so.6")
class Struct_Password(Structure): 
    """ 
     
    """ 
    _fields_ = [ ('name', c_char_p), 
                ('code', c_char_p), 
                ('date', c_long), 
                ('min',  c_long), 
                ('max',  c_long), 
                ('warn', c_long), 
                ('inact', c_long), 
                ('expire', c_long), 
                ('flag', c_ulong) 
            ]
l_res =  g_lib.getspnam('john') 
l_struct = cast(l_res, POINTER( Struct_Password() ) ) 
print l_struct
******************************************

The exception I get is "unhashable type" - apparently cast only handles
simple types.

Is there a way to convert l_res to Struct_Password ?

Thanks,

hg



From tazmaster at rocketmail.com  Tue Jul 10 02:54:14 2007
From: tazmaster at rocketmail.com (Jim Langston)
Date: Mon, 9 Jul 2007 23:54:14 -0700
Subject: 2**2**2**2**2 wrong? Bug?
References: 
Message-ID: 

Gah!  Python goes right to left?  Dang, I haven't seen that since APL.

 wrote in message 
news:mailman.512.1184044672.22759.python-list at python.org...
>>> ((((2**2)**2)**2)**2)
65536

>>> 2**(2**(2**(2**2)))
200352993040684646497907235156025575044782547556975141926501697371089405955631145308950613088.............................................
The same as "2**2**2**2**2"



-----Original Message-----
From: python-list-bounces+brianjiang=gdnt.com.cn at python.org 
[mailto:python-list-bounces+brianjiang=gdnt.com.cn at python.org] On Behalf Of 
Jim Langston
Sent: 2007??7??10?? 12:47
To: python-list at python.org
Subject: Re: 2**2**2**2**2 wrong? Bug?

"Paul Rubin"  wrote in message 
news:7xbqek7ty1.fsf at ruckus.brouhaha.com...
> "Jim Langston"  writes:
>> In Python 2.5 on intel, the statement
>> 2**2**2**2**2
>> evaluates to
>> >>> 2**2**2**2**2
>
> I get the same number from hugs--why do you think it might be wrong?

2**2 = 4
4**2 = 16
16**2 = 256
256**2 = 65536
65536**2 = 4294967296

In fact, if I put (2**2)**2**2**2
it comes up with the correct answer, 4294967296





From python at jayloden.com  Sat Jul 28 13:14:08 2007
From: python at jayloden.com (Jay Loden)
Date: Sat, 28 Jul 2007 13:14:08 -0400
Subject: Python 2.5.1 can't find win32file?
In-Reply-To: <1185634068.634813.187350@e16g2000pri.googlegroups.com>
References: <1185628601.992750.55990@e16g2000pri.googlegroups.com>
	<1185634068.634813.187350@e16g2000pri.googlegroups.com>
Message-ID: <46AB7960.1070903@jayloden.com>

samwyse wrote:
> Interestingly enough, this works:
> 
> C:\Python25>path=%path%;C:\Python25\Lib\site-packages\pywin32-210-
> py2.5-win32.eg
> g\pywin32_system32
> 
> C:\Python25>python
> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import win32file
>>>>
> 
> It looks like the system search path isn't getting updated so that
> PYWINTYPES25.DLL can be found when win32file.pyd is loaded.
> 
> Anyone have any ideas?

If you just want to update your PATH, you can do that from My Computer -> Properties -> Advanced -> Environment Variables and just update PATH for your user (or all users if you prefer).

-Jay


From gagsl-py2 at yahoo.com.ar  Tue Jul 17 12:26:50 2007
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Tue, 17 Jul 2007 13:26:50 -0300
Subject: how to find available classes in a file ?
References: <2e302$469bf38f$d443bb3a$30036@news.speedlinq.nl>
	<1184627599.597658.267380@g4g2000hsf.googlegroups.com>
	
	<1184681117.305570.311350@x35g2000prf.googlegroups.com>
Message-ID: 

En Tue, 17 Jul 2007 11:05:17 -0300, Alex Popescu  
 escribi?:

> On Jul 17, 4:41 am, "Gabriel Genellina" 
> wrote:
>> > On Jul 17, 1:44 am, Stef Mientki 
>> > wrote:
>> >> I want to have a (dynamically) list of all classes defined in a  
>> py-file.
>>
>> inspect.getmembers(the_module, inspect.isclass) would do. But this
>> requires the module to be importable.
>>
>
> I may be wrong but I think I've found a difference between my
> dir(module) approach
> and the inspect.getmembers(module, inspect.isclass): the first one
> returns the
> classes defined in the module, while the later also lists the imported
> available
> classes.

Let's try, using the standard module wave.py which imports class Chunk  
 from chunk.py:

py> import inspect
py> import wave
py> inspect.getmembers(wave, inspect.isclass)
[('Chunk', ), ('Error', ), ...
py> dir(wave)
['Chunk', 'Error', 'WAVE_FORMAT_PCM', 'Wave_read', 'Wave_write', ...

Chunk appears on both. (That's not a surprise, since inspect.getmembers  
uses dir() internally).
If you want to include *only* classes defined in the module itself, you  
could test the __module__ attribute:

py> wave.Chunk.__module__
'chunk'
py> wave.Wave_read.__module__
'wave'

How to filter when the class is defined deeply inside a package is left as  
an exercise to the reader :)

-- 
Gabriel Genellina



From sjmachin at lexicon.net  Wed Jul 25 09:04:23 2007
From: sjmachin at lexicon.net (John Machin)
Date: Wed, 25 Jul 2007 06:04:23 -0700
Subject: 16-bit colour representation
In-Reply-To: <1185364424.797757.84620@22g2000hsm.googlegroups.com>
References: <1185364424.797757.84620@22g2000hsm.googlegroups.com>
Message-ID: <1185368663.434253.89740@d30g2000prg.googlegroups.com>

On Jul 25, 9:53 pm, beertje  wrote:
> This has me a bit stumped...
>
> I'm trying to extract pictures from a file. So far I'm successfully
> retrieved the header and what I think is the colour for each pixel.
> Here's the description:
>
> """
> 3) The picture data format:
> The color information is 15 bit data stored in 16 bit. This means the
> most
> significant bit is unused. The data is stored line for line in little
> endian Intel format starting with top left edge to bottom right edge.
> This
> is normally called chunky format.
>
> Bit  0.. 4      blue value
> Bit  5.. 9      green value
> Bit 10..14      red value
> """

Do yourself a favour -- read the next line in TFM. It says: "To get 8
bit RGB data, all these values must be shifted 3 bits to the left."

>
> So I've got a list of 16-bit numbers, but how to extract RGB info from
> those I'm a bit lost. I thought at first I should convert the decimal
> (say 23294) into a binary (say 0101101011111110) into something like
> this:
> blue: 01011
> green: 01011
> red: 11111

I think you've lost it somewhere;  23294 -> red 22, green 23, blue 30;
see below.

>
> But encountered two problems: First, I don't know what the best way is
> to do this conversion,

b = rgb & 31
g = (rgb >> 5) & 31
r = (rgb >> 10) & 31

IOW like you would in C; IOW isn't this whole question OT?

> but more importantly I don't see how every
> colour could possibly be represented like this. 65535 is presumably
> white, but converting this into chunks of 5 gives me a 31, 31, 31, a
> dark shade of grey.

It is a dark shade of grey in 8-bit RGB, but it's as white as the
driven snow in 5-bit RGB.

You need to scale it up. TFM indicates rgb8 = rgb5 << 3 -- i.e.
multiply by 8, but 31 * 8 is 248, not 255. You might want to try rgb8
= (rgb5 * 255 + 16) / 31 instead.

>
> I guess I'm on the wrong track completely?
>
> I'm a bit unsure about how to treat what the guide calls 'UWORD'...

TFM says "UWORD is unsigned 16 bit", so you treat it as an Unsigned
(16-bit) WORD, which is what you [should] have been doing.

>
> Here's the full guide:http://lists.kde.org/?l=kde-games-devel&m=105548792026813&w=1#2
> (16-bit PC cards)



From rcdailey at gmail.com  Thu Jul 12 17:52:43 2007
From: rcdailey at gmail.com (Robert Dailey)
Date: Thu, 12 Jul 2007 21:52:43 -0000
Subject: Function parameter type safety?
Message-ID: <1184277163.803229.318660@g4g2000hsf.googlegroups.com>

Hi,

Is there a way to force a specific parameter in a function to be a
specific type? For example, say the first parameter in a function of
mine is required to be a string. If the user passes in an integer, I
want to notify them that they should pass in a string, not an integer.



From dhwild at talktalk.net  Sun Jul 29 16:15:22 2007
From: dhwild at talktalk.net (David H Wild)
Date: Sun, 29 Jul 2007 21:15:22 +0100
Subject: 128 or 96 bit integer types?
References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com>
	
	<1185562901.206212.52570@j4g2000prf.googlegroups.com>
	
	<1185607142.096574.209200@e16g2000pri.googlegroups.com>
	<46ab05a9$0$1345$834e42db@reader.greatnowhere.com>
	<1185735547.172823.20030@x40g2000prg.googlegroups.com>
Message-ID: <46acfbb8$0$1339$834e42db@reader.greatnowhere.com>

In article <1185735547.172823.20030 at x40g2000prg.googlegroups.com>,
   mensanator at aol.com  wrote:
> To actually answer you question, there is a known loop
> cycle in 3n+85085 for which p=492 and q=264. If there is
> one solution, there must be at leats 263 others (the
> cyclic permutations), but to brute force search for any
> others would require enumerating the answer to how many
> ways can 492 marbles be put in 264 bins such that each
> bin has at least 1 marble.

Thank you very much. I am awestruck.

-- 
David Wild using RISC OS on broadband
www.davidhwild.me.uk


From bignose+hates-spam at benfinney.id.au  Thu Jul 12 08:38:24 2007
From: bignose+hates-spam at benfinney.id.au (Ben Finney)
Date: Thu, 12 Jul 2007 22:38:24 +1000
Subject: variable naming query
References: <1184236383.691966.56530@w3g2000hsg.googlegroups.com>
Message-ID: <87lkdlkda7.fsf@benfinney.id.au>

loial  writes:

> What is the difference between
>
> self.myvariable

Indicates to the reader that the attribute 'myvariable' is available
for use as part of the interface of the object.

Prefer this style unless you have good reason in a particular case to
do otherwise.

> self._myvariable

Indicates to the reader that the attribute '_myvariable' should not be
used as part of the interface to the object.

> self.__myvariable

Indicates to the reader that the attribute '__myvariable' is not
available by that name outside the object, and name mangling is
automatically done to discourage its use from outside the object.

> and when should I use each of them?

Use each of them to indicate the above conditions where appropriate.

Note that none of them will change the nature of the attribute, and
Python will allow use of any of them by the correct name. There is no
such thing as "limited-access" attributes in Python; we rely on the
maxim that "we're all consenting adults here". If an attribute exists
in the current scope, it is available for any use regardless of what
name you give it.

-- 
 \     "I wish there was a knob on the TV to turn up the intelligence. |
  `\      There's a knob called 'brightness' but it doesn't work."  -- |
_o__)                                              Eugene P. Gallagher |
Ben Finney


From dave at boost-consulting.com  Tue Jul  3 18:55:20 2007
From: dave at boost-consulting.com (David Abrahams)
Date: Tue, 03 Jul 2007 18:55:20 -0400
Subject: import mysteries
References: 
	
Message-ID: <87zm2dm71j.fsf@grogan.peloton>


on Thu Jun 21 2007, Peter Otten <__peter__-AT-web.de> wrote:

> David Abrahams wrote:
>
>> I'm pretty comfortable with Python, but recently I'm constantly
>> finding mysterious issues with import.  For example, looking at
>> 
>>   http://genshi.edgewall.org/browser/trunk/genshi/filters/transform.py
>> 
>> the examples use the symbol 'HTML' but it's not defined locally, it's
>> not explicitly imported, and there's no import *.  Yet doctest will
>> test this module and it passes with flying colors.  It turns out HTML
>> is defined in genshi.input.  How do I know that?  I grepped for it.
>> How does it become available to this module?
>
> Explicitly passed, see
>
> http://genshi.edgewall.org/browser/trunk/genshi/filters/tests/transform.py

IIRC I ran doctest on the file I cited, not the one you're pointing
at.  Is there some new magic doctest feature I should know about?

>> Another example: I was recently working on some code that did an
>> import from inside a class method.  That import was failing.  I moved
>> the import to the top of the file (at module scope) and it succeeded.
>> I'm fairly sure that nobody was monkeying around with sys.path in that
>> case.  Can anyone think of a likely explanation?
>
> Too vague, sorry.

  # this will succeed if I do it here
  # import foo.bar

  class X:
        def y():
            import foo.bar # but this fails

  
-- 
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com

The Astoria Seminar ==> http://www.astoriaseminar.com



From wildemar at freakmail.de  Sun Jul  8 16:49:01 2007
From: wildemar at freakmail.de (Wildemar Wildenburger)
Date: Sun, 08 Jul 2007 22:49:01 +0200
Subject: The Modernization of Emacs: terminology buffer and keybinding
In-Reply-To: <851wfivdtr.fsf@lola.goethe.zz>
References: <1182093200.598418.218620@e9g2000prf.googlegroups.com>	<1182272495.990807.99110@a26g2000pre.googlegroups.com>	<87tzt3ihev.fsf@kobe.laptop>
		<1182370216.961241.6960@n60g2000hse.googlegroups.com>	<85zm2ufjpb.fsf@lola.goethe.zz>	<1182372592.803332.288260@u2g2000hsc.googlegroups.com>	<1182373919.262388.100740@c77g2000hse.googlegroups.com>	<85r6o6fhkb.fsf@lola.goethe.zz>	<1182375045.626510.188170@m36g2000hse.googlegroups.com>	<85myyufgwj.fsf@lola.goethe.zz>	<1182375528.985142.293900@q69g2000hsb.googlegroups.com>		<1182545268.055596.228700@i38g2000prf.googlegroups.com>		<1183841277.333384.188950@g4g2000hsf.googlegroups.com>		<1183856442.027967.272530@g4g2000hsf.googlegroups.com>	<1183883315.265068.61600@n60g2000hse.googlegroups.com>	<1183923997.160960.3080@q75g2000hsh.googlegroups.com>
	<851wfivdtr.fsf@lola.goethe.zz>
Message-ID: <46914DBD.8050302@freakmail.de>

David Kastrup wrote:
> Twisted  writes:
>   
>> Judging by the existence of the newsgroup comp.emacs, emacs is
>> indeed considered by some to be a quite valuable antique. Otherwise
>> why on earth would it have an apparently fairly active newsgroup a
>> full seven years into the 21st century?
>>     
>
> As opposed to your brain, Emacs has not undergone fossilization 10
> years ago.
Will you people let it go already? Didn't we agree that guy was 
trolling. Just let the man rant. What harm does he do? At least he's not 
bombing busses in Jerusalem or Bagdad, not spreading AIDS in Africa, not 
selling kids lives to companies. He just pookes fun at everyone. Why do 
you people care? Its a text editor, dammit. Let go.

/W


From vasudevram at gmail.com  Thu Jul 26 12:20:44 2007
From: vasudevram at gmail.com (vasudevram)
Date: Thu, 26 Jul 2007 16:20:44 -0000
Subject: wxGlade: Who knows how to drive this application?
In-Reply-To: 
References: 
	
Message-ID: <1185466844.117993.13000@e16g2000pri.googlegroups.com>


Steve Holden wrote:

> I've been trying to use wxGlade recently and I am finding it something
> of a challenge. Is there any user who finds the user interface
> satisfactory and the operation of the program predictable?

Good (for me) that you posted this question, as I got to know about
wxGlade (also the others mentioned like Dabo, which I'm gonna check
out) - I might not have heard of it otherwise :-)

Tried it out (wxGlade) yesterday after reading your post. Results:

I could get it to run, no problem.

Tried Alberto's tutorial that builds the GUI for a tabbed notebook
with a menu. Worked mostly fine.

One problem I had was that it is an SDI app (Single Document Interface
- Windows term) and, maybe due to that, the (preview of the) frame
you're designing sometimes gets hidden under the other windows (the
main wxGlade window, the Properties window, the GUI widgets tree,
etc.) so I sometimes had to fiddle around with the mouse to uncover
it. Or it could have been due to my monitor's resolution.

I have wxPython 2.6 installed on my (Windows) machine, so had to
change the default code generation from 2.8 to 2.6. After that I could
run the generated code. I used the option to generate each class in a
separate file. The generated code was quite readable - I could
understand it easily.

Having the tree of widgets shown in one window is a plus point - it
helps you to visualize the structure / nesting of the widgets in your
app.

Another slight problem was that, though I had sized the main frame to
occupy the whole  screen (while in design mode), when I ran the
generated code, the main frame was partially outside the screen.
Possibly this again was due to my monitor - getting
GUI apps to display correctly on differing target monitors is
challenging ...

That was all I've tried so far, but I think even that much is of some
help, at least - it should save some time with designing one's GUI. I
plan to try it out some more.

My 2 cents ...

Vasudev Ram
http://www.dancingbison.com
http://sourceforge.net/projects/xtopdf
http://jugad.livejournal.com




From greg at cosc.canterbury.ac.nz  Tue Jul 10 20:59:31 2007
From: greg at cosc.canterbury.ac.nz (greg)
Date: Wed, 11 Jul 2007 12:59:31 +1200
Subject: os.wait() losing child?
In-Reply-To: 
References: 
Message-ID: <5fioi8F3cchqoU1@mid.individual.net>

Jason Zheng wrote:
> while (True):
>   pid = os.wait()
>   ...
>   if (someCondition):
>     break
 >   ...

Are you sure that someCondition() always becomes true
when the list of pids is empty? If not, you may end
up making more wait() calls than there are children.

It might be safer to do

   while pids:
     ...

--
Greg


From eddie at holyrood.ed.ac.uk  Mon Jul 23 13:43:31 2007
From: eddie at holyrood.ed.ac.uk (Eddie Corns)
Date: Mon, 23 Jul 2007 17:43:31 +0000 (UTC)
Subject: Can a low-level programmer learn OOP?
References: 
	
	<7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com>
	 
	
	
	<1185204512.255392.105820@r34g2000hsd.googlegroups.com>
Message-ID: 

Paul McGuire  writes:

>On Jul 23, 5:53 am, ed... at holyrood.ed.ac.uk (Eddie Corns) wrote:
>> Wolfgang Strobl  writes:
>> >few of James Gimple's snippets from "Algorithms in SNOBOL4"
>> >(->http://www.snobol4.org/) as an exercise using that library might help
>> >to get a better appreciation. Perhaps I'll try, eventually ...
>>
>> I never noticed them or the PDF of the book there before.  Some Friday
>> afternoon reading for sure.
>>
>> Personally I hope to get more to time to look at a combination of Lua and
>> PEGs (http://en.wikipedia.org/wiki/Parsing_expression_grammar) for my parsing
>> needs.
>>
>> Eddie

>If you get a chance to look at pyparsing, I'd be interested in your
>comments.  The PEG page and the SNOBOL implementation have many
>similar concepts with pyparsing (or is it the other way around?).

It's on my list of things to get round to.

I think what I'm really after though is a parsing DSL.  I only did only one
fairly small project in SNOBOL but I was impressed at the ease with which I
could express the problem (some googling suggested that many end users found
the same).  I guess I want SNOBOL embedded in a modern language with scoping
etc.  Python is antithetical to (this class of) DSLs (IMHO) :(

Probably what I really need is parser combinators in Haskell or maybe camlp4
or some such exotica but unfortunately I've never heard of them.

Eddie


From the.mindstorm.mailinglist at gmail.com  Sun Jul 15 01:18:08 2007
From: the.mindstorm.mailinglist at gmail.com (Alex Popescu)
Date: Sat, 14 Jul 2007 22:18:08 -0700
Subject: Getting values out of a CSV
In-Reply-To: 
References: <1184295593.638409.22910@22g2000hsm.googlegroups.com>
	
	
	
	
	
	
Message-ID: <1184476688.405321.122740@m3g2000hsh.googlegroups.com>

On Jul 14, 5:55 am, "Gabriel Genellina" 
wrote:
>
> So, as always, one should measure in each specific case if optimization is  
> worth the pain [...].
>

I hope I am somehow misreading the above sentence :-). IMO synonim
language contructs
should result in the same performance or at least have clear/
documented performance.
I don't think we really want to see in code something like:

if threshold:
  do_it_with_list_function
else:
  do_it_with_list_comprehension

bests,

./alex
--
.w( the_mindstorm )p.



> --
> Gabriel Genellina




From raims at dot.com  Sun Jul  8 04:35:33 2007
From: raims at dot.com (Lawrence Oluyede)
Date: Sun, 8 Jul 2007 10:35:33 +0200
Subject: __unicode__ method for exception object
References: 
	<874pkfoj9i.fsf@benfinney.id.au>
Message-ID: <1i0xhdr.agguths7nm0wN%raims@dot.com>

Ben Finney  wrote:
> Your terminal has been detected as using the 'ascii' encoding, so
> while that's true no attempt to output non-ASCII characters will work.
> 
> You'll need to change whatever settings are on your terminal emulator
> so that it is using an encoding (such as 'utf-8') which can display
> the characters you want.

AFAIK that's not a terminal problem. I have a UTF-8 terminal and the
problem is still there. 

-- 
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 jstroud at mbi.ucla.edu  Mon Jul 16 18:18:29 2007
From: jstroud at mbi.ucla.edu (James Stroud)
Date: Mon, 16 Jul 2007 15:18:29 -0700
Subject: Break up list into groups
In-Reply-To: 
References: <1184620307.340479.253430@z28g2000prd.googlegroups.com>
	
Message-ID: 

James Stroud wrote:
> Here's how I *would* do it:
> 
> py> def doit(alist):
> ...   ary = []
> ...   for i in alist:
> ...     if 0xf0 & i:
> ...       ary.append([i])
> ...     else:
> ...       ary[-1].append(i)
> ...   return [x for x in ary if x]
> ...


To be absolutely compliant with the specifications, it should be

    return [x for x in ary if len(x)>1]

in the recommended way. This does not affect the example given, though.

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/


From duncan.booth at invalid.invalid  Mon Jul 23 06:38:29 2007
From: duncan.booth at invalid.invalid (Duncan Booth)
Date: 23 Jul 2007 10:38:29 GMT
Subject: Lazy "for line in f" ?
References: <1185120650.412694.314280@o61g2000hsh.googlegroups.com>
	
	<1185143634.778056.227720@g4g2000hsf.googlegroups.com>
	
	<1185173778.656660.195650@n60g2000hse.googlegroups.com>
	<7xbqe3efm5.fsf@ruckus.brouhaha.com>
	<1185177589.837857.105390@r34g2000hsd.googlegroups.com>
	
	<1185182315.489049.271010@r34g2000hsd.googlegroups.com>
	
Message-ID: 

Duncan Booth  wrote:

> or even:
> 
>    read = f.readline
>    while read():
>        pass
> 

Oops, I forgot the other obvious variant on this, which has the benefit of 
getting rid of the test I said was 'required' while still leaving the data 
accessible:

    for line in iter(f.readline, ''):
        pass

Takes 8.89 seconds (best of 3 runs) versus 3.56 (best of 3) for the 
similar:

    for line in f:
        pass

So readline is 250% slower at best, and only then if you remember the 
obscure use of iter. :)


From aahz at pythoncraft.com  Thu Jul  5 10:34:28 2007
From: aahz at pythoncraft.com (Aahz)
Date: 5 Jul 2007 07:34:28 -0700
Subject: Proposal: s1.intersects(s2)
References: 
	
	
	
Message-ID: 

In article ,
Steven D'Aprano   wrote:
>
>My main feeling is that any such function should be a set method rather
>than a built-in function like len(). The name change was comparatively
>unimportant.

Look up at the Subject: line.  There never was any suggestion that
intersects() be anything other than a set method.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

I support the RKAB


From aleax at mac.com  Sun Jul  1 14:09:10 2007
From: aleax at mac.com (Alex Martelli)
Date: Sun, 1 Jul 2007 11:09:10 -0700
Subject: Reversing a string
References: 
	
	<1182997438.541012.54100@o61g2000hsh.googlegroups.com>
	
	
	
Message-ID: <1i0kjpx.wjw44j15np22dN%aleax@mac.com>

Martin Durkin  wrote:
   ...
> >>>>>> def rev(x):
> >>>             mylist = []
> >>>             for char in x:
> >>>                  mylist.append(char)
> >>>             mylist.reverse()
> >>>             for letter in mylist:
> >>>                  print letter
> >>> 
> >>> However, compare the incredible difference in clarity and elegance
> >>> between that and:
> >>> 
> >>>> >>> print "\n".join("spam"[::-1])
   ...
> >> OK, maybe I'm missing the point here as I'm new to Python. The first
> >> one seems clearer to me. What am I missing?
> >> 
> > I think all you are missing is familarity with Python, but I too don't
> > like one-liners simply for their own sake.
> 
> I guess that's it. The first one reads more like a textbook example which
> is about where I am at. Is there any speed benefit from the one liner?

The first example reads "excruciatingly low-level" to me: its autor is
thinking in terms of what the machine is doing, mapped into pretty
elementary low-level constructs.

The second example depends first of all on knowledge of extended-slicing
(specifically the fact that x[::-1] is a reversal, because of the
negative -1 "step" aka "stride").  If you don't know about extended
slicing, you're unlikely to just "get it from context", because it uses
a syntax based on punctuation rather than readable words whose meaning
you might guess at.  Python has a modest amount of such "punctuation
syntax" -- about the same amount as C but definitely more than Cobol
(where one would typically write "ADD a TO b" to avoid shocking totally
clueless readers with "mysterious punctuation" such as "a + b"...!!!-).
Punctuation is often very concise but not "intrinsically obvious" unless
you've been exposed to it already;-).

If I was targeting total newbies, since extended slicing is something
that they can well wait a while to learn, I'd probably compromise in
favor of "reversed(x)".  The "reversed" built-in function does basically
the same job as a [::-1] slicing, but any English speaker can probably
guess what it's doing -- presenting a reversed permutation of its
sequence argument.

So, something like:

for c in reversed(x): print c

is mostly likely how I'd present the solution to the task.  Using join
to make a single string is (in this particular case) needlessly
precious, though not really a big deal (and beginners had better learn
about joining pretty early on).  But that definitely does not justify
the excruciating, "micromanaged" nature of the first example, which
uselessly belabors the concept of "reversing" to a silly extent.

Python LETS you program at such lowish levels, if you insist, but it
encourages thinking more about your problem and less about the way the
inner gears of the machine will turn in order to produce a solution for
it...!  Part of the encouragement is indeed that coding at a higher
level of abstraction tends to make your program faster (an "abstraction
reward" to replace the "abstraction penalty" so common with some other
languages:-) -- but clarity and productivity are more important still.


Alex


From nagle at animats.com  Sun Jul 22 13:56:37 2007
From: nagle at animats.com (John Nagle)
Date: Sun, 22 Jul 2007 10:56:37 -0700
Subject: URL parsing for the hard cases
Message-ID: 

    Is there something available that will parse the "netloc" field as
returned by URLparse, including all the hard cases?  The "netloc" field
can potentially contain a port number and a numeric IP address.  The
IP address may take many forms, including an IPv6 address.

    I'm parsing URLs used by hostile sites, and the wierd cases come up
all too frequently.

					John Nagle


From dtgeadamo at yahoo.com  Sat Jul 14 04:39:47 2007
From: dtgeadamo at yahoo.com (Viewer T.)
Date: Sat, 14 Jul 2007 01:39:47 -0700
Subject: Access Denied while trying to delete file from python script
Message-ID: <1184402387.265806.322680@z28g2000prd.googlegroups.com>

I am trying to write a script that deletes certain files based on
certain criteria.

What I am trying to do is to automate the process of deleting certain
malware files that disguise themselves as system files and hidden
files. When I use os.remove() after importing the os module is raises
a Windows Error: Access denied probably because the files have
disguised themselves as system files. Is there anway to get adequate
privileges under windows to be able to delete system files from within
a python script. I know it is probably a windows security feature but
is there anyway to gain such privileges.



From nytrokiss at gmail.com  Mon Jul  9 15:25:40 2007
From: nytrokiss at gmail.com (James Matthews)
Date: Mon, 9 Jul 2007 12:25:40 -0700
Subject: Pydev 1.3.7 Released
In-Reply-To: 
References: 
Message-ID: <8a6b8e350707091225m578ef540m197f7732241e3ba6@mail.gmail.com>

I just downlaoded the old one!

On 7/9/07, Fabio Zadrozny  wrote:
>
> Hi All,
>
> Pydev and Pydev Extensions 1.3.7 have been released
>
> Details on Pydev Extensions: http://www.fabioz.com/pydev
> Details on Pydev: http://pydev.sf.net
> Details on its development: http://pydev.blogspot.com
>
> Release Highlights:
> ----------------------------------------------
>
> * Support for Eclipse 3.3
> * Bug Fix: Interpreter modules not correctly set/persisted after
> specifying interpreter (so, the builtins and other system libraries would
> not be available in completions).
> * Mylyn integration.
> * Open With Pydev: does not appear for containers anymore.
> * Code-completion:
>   The folowing cases are now considered in code-completion to discover the
> type of a variable:
>       o Type/Interface checking: (note that 'assert' is required) assert
> isinstance(obj, Interface) -- default from python
>       o assert Interface.implementedBy(obj) -- zope
>       o assert IsImplementation(obj, Interface) -- custom request
>       o assert IsInterfaceDeclared(obj, Interface) -- custom request
>       o Factory methods a = adapt(obj, Interface) -- pyprotocols
>       o a = obj.GetAdapter(Interface) -- custom request
>       o a = obj.get_adapter(Interface) -- custom request
>       o a = GetSingleton(Interface) -- custom request
>       o a = GetImplementation(Interface) -- custom request
>
>
> What is PyDev?
> ---------------------------
>
> PyDev is a plugin that enables users to use Eclipse for Python and Jython
> development -- making Eclipse a first class Python IDE -- It comes with many
> goodies such as code completion, syntax highlighting, syntax analysis,
> refactor, debug and many others.
>
>
> Cheers,
>
> --
> Fabio Zadrozny
> ------------------------------------------------------
> Software Developer
>
> ESSS - Engineering Simulation and Scientific Software
> http://www.esss.com.br
>
> Pydev Extensions
> http://www.fabioz.com/pydev
>
> Pydev - Python Development Enviroment for Eclipse
> http://pydev.sf.net
> http://pydev.blogspot.com
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://www.goldwatches.com/watches.asp?Brand=14
http://www.jewelerslounge.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From tn.pablo at gmail.com  Sat Jul 21 01:42:17 2007
From: tn.pablo at gmail.com (Pablo Torres)
Date: Fri, 20 Jul 2007 22:42:17 -0700
Subject: Permutations with generators
Message-ID: <1184996537.069416.211730@g4g2000hsf.googlegroups.com>

Hey guys!
For the last couple of days, I've been fighting a war against
generators and they've beaten the crap out of me several times. What I
want to do is implement one that yields every possible permutation of
a given sequence (I had lists in mind, but I could swear that this
would work on strings too...if it worked at all).

Here's what I have so far:

def perm(seq):
	"Reshuffles the elements of seq in every possible way"
	if len(seq) == 1:
		yield seq
	else:
		for p in perm(seq[1:]):
			for i in range(len(seq)):
				yield p.insert(i, seq[0])

Basically, I let the recursion reshuffle the elements of the
subsequence that starts from the second element of the original one,
and then I insert seq[0], the first element of the original sequence,
in every position of the shuffled sublist.

Here's what I get when I try to list the permutations of [1, 2, 3, 4]
(print list(perm([1, 2, 3, 4]))):

Traceback (most recent call last):
  File "perm.py", line 15, in 
    print list(perm([1, 2, 3, 4]))
  File "perm.py", line 11, in perm
    for p in perm(seq[1:]):
  File "perm.py", line 13, in perm
    yield p.insert(i, seq[0])
AttributeError: 'NoneType' object has no attribute 'insert'

Could somebody please explain to me why my p variable has no type at
all?
For every call to perm(seq), seq should always be of the same type as
the sequence that was used in the first call. Any ideas as to where
seq loses it's type?

Thanks in advance,
Pablo



From steve at holdenweb.com  Fri Jul 13 14:42:54 2007
From: steve at holdenweb.com (Steve Holden)
Date: Fri, 13 Jul 2007 14:42:54 -0400
Subject: sys.exit versus termination of source code
In-Reply-To: <9246A60D003B924F9F28DFA2F26935C201C3E2E9@MSEVS01.outlook.hostbasket.com>
References: <9246A60D003B924F9F28DFA2F26935C201C3E2E9@MSEVS01.outlook.hostbasket.com>
Message-ID: 

Carl DHalluin wrote:
> Hi,
> 
>  
> 
> I am playing with the atexit module but I don?t find a way to see the 
> difference
> 
> between a script calling sys.exit() and the interpreting 
> arriving at the end
> 
> of the source code file. This has a semantic difference for my applications.
> 
> Is there a way to determine in an exithandler (that is registered using 
> atexit.register)
> 
> how I exited?
> 
I don't believe so.

>  
> 
> Second question: is there a way to determine in my exithandler what the 
> return code was.
> 
> atexit doesn?t seem to support that
> 
I don't believe so.
>  
> 
> Third question: I can solve part of my problem by reassigning sys.exit = 
> myfunction
> 
> Is that a wise idea?
> 
>  
> 
> Thanks
> 
> Carl D?Halluin
> 
> www.qlayer.com
> 
It would be much more sensible to replace the calls to sys.exit with 
calls to some function that sets the required "this was not falling off 
the end" indication and then calls sys.exit.

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  Wed Jul 25 17:07:18 2007
From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann)
Date: Wed, 25 Jul 2007 23:07:18 +0200
Subject: first, second, etc line of text file
References: <5f56302b0707251244p24080f1ct87a5f459cb175dae@mail.gmail.com>
	
	<13afdpp7a6t24c5@corp.supernews.com>
Message-ID: <5gpsc6F3h88a9U1@mid.individual.net>

Grant Edwards wrote:
> On 2007-07-25, Jeff McNeil  wrote:
 
>> Depending on the size of your file, you can just use
>> file.readlines. Note that file.readlines is going to read the
>> entire file into memory, so don't use it on your plain-text
>> version of War and Peace.
> 
> I don't think that would actually be a problem for any recent
> machine.
> 
> The Project Gutenberg version of W&P is 3.1MB of text in 67403
> lines.  I just did an f.readlines() on it and it was pretty
> much instantaneous, and the python interpreter instance that
> contains that list of 67403 lines is using a bit less than 8MB
> of RAM. 

YMMD :)

Regards,


Bj?rn

-- 
BOFH excuse #335:

the AA battery in the wallclock sends magnetic interference



From bj_666 at gmx.net  Wed Jul 11 02:17:45 2007
From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch)
Date: 11 Jul 2007 06:17:45 GMT
Subject: concatenate file-like objects -> file-like object
References: <1184115352.818085.250500@e16g2000pri.googlegroups.com>
Message-ID: <5fjb09F3d2eqeU2@mid.uni-berlin.de>

On Tue, 10 Jul 2007 17:55:52 -0700, kgk wrote:

> I would like to concatenate several file-like objects
> to create a single file-like object.  I've looked at fileinput,
> however
> this returns a fileinput object that is not very file-like.
> 
> something like
> # a has 50 bytes, and b has 100 bytes
> f = FileList (open('a'), open('b'))
> f.read (100)  #  read 50 bytes from a and 50 from b
> 
> My interest is in passing several files to an incremental parser
> as if they came from a single file.   I would rather not load them
> in memory using StringIO and the parser reads only from file-like
> objects.

Then program a file like object yourself.  Something like this (untestet):

class FileList(object):
    def __init__(self, files):
        self.files = reversed(files)
        self.current_file = self.files.pop()
    
    def read(size):
        result = ''
        while self.files:
            data = self.current_file.read(size)
            result += data
            if len(data) != size:
                self.current_file = self.files.pop()
                size = size - len(data)
        return result

Ciao,
	Marc 'BlackJack' Rintsch


From ratchetgrid at googlemail.com  Tue Jul  3 05:19:07 2007
From: ratchetgrid at googlemail.com (Nathan Harmston)
Date: Tue, 3 Jul 2007 10:19:07 +0100
Subject: Programming Idiomatic Code
In-Reply-To: <468a0768$0$14120$426a74cc@news.free.fr>
References: 
	<468a0768$0$14120$426a74cc@news.free.fr>
Message-ID: <676224240707030219h27547eddo730ee918b96cc6d1@mail.gmail.com>

HI,

Thanks to everyone for your comments ( i never knew "with" existed,
but to quote Borat "I like", unfortunately I cant apply for the job as
i m in the UK and dont have the experience but hey 10 minutes of
programming python beats 12 hours of programming in Clipper-derived
unreadable drivel (you dont know how much I appreciate Python atm).

I have one question though:

Using a module global for this kind of data is usually a bad idea
(except eventually for run-once throw-away scripts, and even then...)

Why is this a bad idea?

Thanks in advance

Nathan

PS I am very ashamed I wrote:
  if (len(sys.argv)) is 1         ......................
              I would ask that this is never spoken of again, oh well
off to work I go


From exarkun at divmod.com  Tue Jul  3 09:25:43 2007
From: exarkun at divmod.com (Jean-Paul Calderone)
Date: Tue, 3 Jul 2007 09:25:43 -0400
Subject: what is wrong with that r"\"
In-Reply-To: <1183468603.714314.241430@n60g2000hse.googlegroups.com>
Message-ID: <20070703132543.4947.398827579.divmod.quotient.6398@ohm>

On Tue, 03 Jul 2007 06:16:43 -0700, kyosohma at gmail.com wrote:
>On Jul 3, 7:15 am, alf  wrote:
>> question without words:
>>
>>  >>> r"\"
>>    File "", line 1
>>      r"\"
>>         ^
>> SyntaxError: EOL while scanning single-quoted string
>>  >>> r"\ "
>> '\\ '
>
>One slash escapes the following character, so the proper way of
>writing it is either
>
>r"\\" or r"\""
>
>See http://docs.python.org/ref/strings.html for more information.

I wonder if the OP was asking how to spell the one-length string \?
In that case, the answer is that it can't be done using raw strings,
but "\\" does it.  Backslash escapes aren't interpreted in raw strings,
but you still can't end a raw string with a backslash.

Jean-Paul


From bdesth.quelquechose at free.quelquepart.fr  Tue Jul  3 23:14:28 2007
From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers)
Date: Wed, 04 Jul 2007 05:14:28 +0200
Subject: Programming Idiomatic Code
In-Reply-To: 
References: 	<468a0768$0$14120$426a74cc@news.free.fr>		<468a373a$0$22943$426a74cc@news.free.fr>
	
Message-ID: <468a9ff2$0$30136$426a74cc@news.free.fr>

Nathan Harmston a ?crit :
>> > Using a module global for this kind of data is usually a bad idea
>> > (except eventually for run-once throw-away scripts, and even then...)
>> >
>> > Why is this a bad idea?
>>
>> Don't you have any idea ?
> 
> Not really.....problem with access, using unneeded memory... I
> grasping at straws here...

It makes generate_cound needlessly dependent on this global. It makes 
code harder to read. It makes code harder to test. It makes code harder 
to maintain. It makes code harder to reuse.

Ok, I understand this is probably not going to be a problem in this 
particular case. But you asked how idiomatic your code was, and using 
globals where not necessary is not pythonic.


From bearophileHUGS at lycos.com  Thu Jul 26 06:14:58 2007
From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com)
Date: Thu, 26 Jul 2007 03:14:58 -0700
Subject: From D
In-Reply-To: 
References: <1185272393.484032.125180@22g2000hsm.googlegroups.com>
	<46a6086d$0$8399$9b622d9e@news.freenet.de>
	<5gmthsF3hc0n2U1@mid.individual.net>
	
Message-ID: <1185444898.842917.226640@b79g2000hse.googlegroups.com>

Sorry for the slow feedback.

Stargaming>Sounds like a good thing to be but the arbitrary
positioning doesnt make any sense.<

The arbitrary positioning allows you to denote 4-digit groups too in
binary/hex literals, like in my example:
auto x = 0b0100_0011;


Stargaming>fits into the current movement towards generator'ing
everything. But (IIRC) this idea came up earlier and there has been a
patch, too.<

Python is old so most simple ideas aren't new :-)


Steven D'Aprano>Underscores in numerics are UGLY.<

I presume it's a matter of taste too. I use them often in D code, and
the _ symbol is very different from the 0..F/0..f digits so you can
tell them apart with no problems.


Steven D'Aprano>Why not take a leaf out of implicit string
concatenation and allow numeric literals to implicitly concatenate?<

The "_" helps my eyes see that those digit groups are part of the same
number. With spaces I think my eyes may need a bit of extra time to
decide if they are parts of the same number literal.


Eric Dexter>I think there is a language bridge so that you can compile
d for python..  looks realy easy but I have python 2.5 and panda and
it try's to go for the panda instalation.  It looks much easier than c
to use with python in fact..<

Are you talking about "Pyd"? It's a good bridge, and I like it. It's
actively updated, soon in version 1.0.

Bye,
bearophile



From steven.bethard at gmail.com  Tue Jul 10 15:13:38 2007
From: steven.bethard at gmail.com (Steven Bethard)
Date: Tue, 10 Jul 2007 13:13:38 -0600
Subject: bool behavior in Python 3000?
In-Reply-To: 
References:  
	
Message-ID: 

Alan G Isaac wrote:
>  > Do you care to explain what is broken?
> 
> I suppose one either finds coercion of arithmetic operations to int
> to be odd/broken or does not.  But that's all I meant.
> 
> My preference would be for the arithmetic operations *,+,-
> to be given the standard interpretation for a two element
> boolean algebra:
> http://en.wikipedia.org/wiki/Two-element_Boolean_algebra

If I understand this right, the biggest difference from the current 
implementation would be that::

     True + True == True

instead of:

     True + True == 2

What's the advantage of that? Could you give some use cases where that 
would be more useful than the current behavior?

It's much easier to explain to newcomers that *, + and - work on True 
and False as if they were 1 and 0 than it is to introduce them to a two 
element boolean algebra. So making this kind of change needs a pretty 
strong motivation from real-world code.

Steve


From leena_kirank at yahoo.com  Thu Jul 19 03:28:08 2007
From: leena_kirank at yahoo.com (Kan)
Date: Thu, 19 Jul 2007 00:28:08 -0700
Subject: Direct Client  -Sr.Software Engineer Python-San Jose CA -Locals only
Message-ID: <1184830088.560038.317800@x40g2000prg.googlegroups.com>

Hello,


We have requirement for Sr.Software Engineer in San Jose CA with very
strong experinece in PYTHON AND LINUX .  If your skills and experience
matches with the same, send me your resume asap with contact # and
rate to 'kanchan at tbiinc.org'. Locals only pls apply

TECHNICAL SKILLS REQUIREMENTS:

* Knowledge of Internet protocols such as TCP/IP, HTTP, FTP, POP3,
IMAP, SMTP, SNMP, etc. is a huge plus
*Very Strong Knowledge of Python, Java, C++ or other object-oriented
language is a plus



Kan
BTech Inc
Recruiter
510-438-6834
kanchan at tbiinc.org
www.tbiinc.org



From axjacob at comcast.net  Mon Jul  9 13:40:58 2007
From: axjacob at comcast.net (axjacob at comcast.net)
Date: Mon, 09 Jul 2007 17:40:58 +0000
Subject: Class file location
Message-ID: <070920071740.14970.4692732A0007317500003A7A22007340760D010C0E06A10407020E@comcast.net>


Is there a way to define a different directory for the generated .class(*$py.class) files than the current directory where the python scripts are located and executed from?

Thanks.


From damienlmoore at gmail.com  Thu Jul 19 16:24:01 2007
From: damienlmoore at gmail.com (dmoore)
Date: Thu, 19 Jul 2007 20:24:01 -0000
Subject: Embedding/Extending Python in/with C++: non-static members?
In-Reply-To: <1184823343.546273.253870@e9g2000prf.googlegroups.com>
References: <1184593533.995878.123010@k79g2000hse.googlegroups.com>
	<1184689489.343144.178550@g37g2000prf.googlegroups.com>
	<1184823343.546273.253870@e9g2000prf.googlegroups.com>
Message-ID: <1184876641.636052.76140@d55g2000hsg.googlegroups.com>

thanks for the responses Nick and "AnonMail"

> I'm doing a similar thing, and I would imagine others are also.
>
> 1. In a python file, set up wrapper functions that the python user
> actually uses (e.g FunctionA).  Each function corresponds to a
> particular C/C++ extension function that you are exposing (e.g.
> CFunctionA).
>
...
> 4. Now when you enter you C/C++ function you can find your object by
> looking
> it up in some predefined table using the id.  What we actually do is
> not use
> an integer but instead use a void pointer which is cast appropriately
> once
> inside C/C++.  This avoids the lookup.

step 4 is smart :)

It's good to know that there is at least one data point of success
using the approach. I won't give up just yet.



From yoav.goldberg at gmail.com  Sat Jul 14 12:03:01 2007
From: yoav.goldberg at gmail.com (Yoav Goldberg)
Date: Sat, 14 Jul 2007 19:03:01 +0300
Subject: defaultdicts pickling
Message-ID: 

Hello,

I need to have a dictionary of dictionaries of numbers, and I would like the
dictionaries to be defaultdicts, because it makes the code much nicer
(I want to be able to do:  d['foo']['bar']+=1 ).

So naturally, I used:

d = defaultdict(lambda :defaultdict(int))

It works great, but now I can not pickle it.

I could ofcourse used a real function and not a lambda, but this would make
things (a) somewhat slower and (b) a bit ugly.

Is there another way of achieving the same behaviour, that allow for
pickling?


Thanks,
Yoav
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From nospam at nospam.com  Sat Jul 28 11:18:38 2007
From: nospam at nospam.com (Gilles Ganault)
Date: Sat, 28 Jul 2007 17:18:38 +0200
Subject: Why no maintained wrapper to Win32?
Message-ID: 

Hello

	It looks like the development of the PyWin32 wrapper to the
Win32 API stopped years ago, which is too bad because it means that
writing GUI apps in Python even just for Windows means adding
megabytes when using eg. wxWidgets.

How come no one too over this project, or offered another wrapper? Or
even better, why no company offered a RAD IDE so that we could write
GUI apps in Python for Windows? It's such a waste not being apple to
just send someone a small EXE.

Thanks.


From bignose+hates-spam at benfinney.id.au  Tue Jul 17 01:53:42 2007
From: bignose+hates-spam at benfinney.id.au (Ben Finney)
Date: Tue, 17 Jul 2007 15:53:42 +1000
Subject: sqlite3 db update extremely slow
References: <1184613750.873464.312390@r34g2000hsd.googlegroups.com>
	
	<1184627356.324577.257470@g4g2000hsf.googlegroups.com>
	
Message-ID: <877iozh8yh.fsf@benfinney.id.au>

Steve Holden  writes:

> # We try to ensure the database is always closed by registering
> # the nodule's close() function to be called on program exit

Ooh! Where do I find more about writing Python nodules? Is it related
to cluster programming?

-- 
 \        "If you go parachuting, and your parachute doesn't open, and |
  `\        you friends are all watching you fall, I think a funny gag |
_o__)          would be to pretend you were swimming."  -- Jack Handey |
Ben Finney


From philr at aspexconsulting.co.nz  Mon Jul  9 17:26:50 2007
From: philr at aspexconsulting.co.nz (Phil Runciman)
Date: Tue, 10 Jul 2007 09:26:50 +1200
Subject: S2K DTS and Python
Message-ID: 

Hi All,

 

I am a Python newbie so please be gentle on me.

 

I have created a program that takes text files within a directory and it
successfully parses the information from them to create 3 CSV files. 

 

However, I now want to update some tables in MSAccess, and it occurred
to me that because Sequel Server 2000 DTS can interface with scripting
languages that maybe I could call my first Python program from within
DTS and then update the tables using DTS. (I am learning DTS hence the
idea).

 

My questions are:

Has anyone used Python within DTS?

Am I off the wall trying such a thing?

 

With regard to the second question: IMHO Python is an elegant language
(thanks Guido) and I just want to use it wherever I can. 

 

Thanks,

 

Phil

 

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From gagsl-py2 at yahoo.com.ar  Thu Jul  5 03:54:34 2007
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Thu, 05 Jul 2007 04:54:34 -0300
Subject: PyRun_String using my module in a def
References: <1183601931.930115.132400@n2g2000hse.googlegroups.com>
	<1i0qtvm.sq102f16mpe7tN%aleax@mac.com>
	<1183609172.421840.171130@n60g2000hse.googlegroups.com>
Message-ID: 

En Thu, 05 Jul 2007 01:19:32 -0300, Stuart   
escribi?:

> What command do you mean when you say "update main_dict with
> dlfl_dict"?

I think Alex Martelly was refering to use main_dict.update(dlfl_dict)  
(Python code) or PyDict_Update(main_dict, dlfl_dict) (in C code).

> I tried PyObject *rstring = PyRun_String( cmd, Py_file_input,
> dlfl_dict, dlfl_dict );
> This worked, but has the side effect of not allowing other commands
> like "execfile"

The idea is to copy all items from dlfl_dict into main_dict, and use  
main_dict for both globals and locals.

-- 
Gabriel Genellina



From the.mindstorm.mailinglist at gmail.com  Thu Jul  5 09:17:51 2007
From: the.mindstorm.mailinglist at gmail.com (Alex Popescu)
Date: Thu, 05 Jul 2007 06:17:51 -0700
Subject: MethodType/FunctionType and decorators
In-Reply-To: 
References: <1183589529.198694.109440@m36g2000hse.googlegroups.com>
	<1183591053.434640.119550@o61g2000hsh.googlegroups.com>
	<1i0qoq9.u1fu2g63fkmxN%aleax@mac.com>
	<1183623479.913816.301230@g4g2000hsf.googlegroups.com>
	<1183626989.983470.94950@o61g2000hsh.googlegroups.com>
	
Message-ID: <1183641471.753457.269030@m36g2000hse.googlegroups.com>

On Jul 5, 3:32 pm, Steve Holden  wrote:
> Alex Popescu wrote:
> > On Jul 5, 11:17 am, Michele Simionato 
> > wrote:
> >> On Jul 5, 3:41 am, a... at mac.com (Alex Martelli) wrote:
>
> >>> 
> >> Alex already explained everything beautifully. I will just add a link
> >> to
> >> the definite guide to descriptors:http://users.rcn.com/python/download/Descriptor.htm
>
> >>  Michele Simionato
>
> >> (who spent lot of brain cycles studying descriptors *before* that
> >> guide was written :-()
>
> > Guys, I appreciate a lot your help and explanations. It looks like I
> > have to read/play a bit more as some of the terms/ideas are pretty new
> > to me (coming to Python with a 10 years Java bag, and only with a
> > small dynlang bag - Ruby, Perl).
>
> > Once again thanks,
>
> Please also realise that for someone new to the language you have dived
> right into the nitty gritty. This isn't necessarily a bad way to learn,
> but it does mean that there's a lot of background to assimilate as you
> go along.
>
> Good luck with your studies.
>

I am starting to realize this on my own :-). The true story is that
while working on Groovy (I am a committer on this dynlang meant to run
on the Java VM: http://groovy.codehaus.org) and reading some Python
materials, my interest grew exponentially. And now I have decided to
see how other succesfull java project I have co-created (TestNG:
http://testng.org) would look like in Python (this giving me the
opportunity to explore Python in more depth).

Thanks for the encouragement.

./alex
--
.w( the_mindstorm )p.

> regards
>   Steve
> --
> Steve Holden        +1 571 484 6266   +1 800 494 3119
> Holden Web LLC/Ltd          http://www.holdenweb.com
> Skype: holdenweb      http://del.icio.us/steve.holden
> --------------- 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  Thu Jul  5 18:45:52 2007
From: sjmachin at lexicon.net (John Machin)
Date: Thu, 05 Jul 2007 15:45:52 -0700
Subject: Where is the syntax for the dict() constructor ?!
In-Reply-To: 
References: <468D1D9D.6060002@gmail.com>
	
	<468D3445.2060408@gmail.com>
	
Message-ID: <1183675552.466967.136360@i13g2000prf.googlegroups.com>

On Jul 6, 5:31 am, Neil Cerutti  wrote:
>
> Mostly you can use the default 'excel' dialect and be quite
> happy, since Excel is the main reason anybody still cares about
> this unecessarily hard to parse (it requires more than one
> character of lookahead for no reason except bad design) data
> format.

One cares about this format because people create data files of
millions of rows (far exceeding the capacity of Excel (pre-2007)) in
many imaginative xSV dialects, some of which are not handled by the
Python csv module.

I don't know what you mean by "requires more than one
character of lookahead" -- any non-Mickey-Mouse implementation of a
csv reader will use a finite state machine with about half-a-dozen
states, and data structures no more complicated than (1) completed
rows received so far (2) completed fields in current row (3) bytes in
current field. When a new input byte arrives, what to do can be
determined based on only that byte and the current state; no look-
ahead into the input stream is required, nor is any look-back into
those data structures.



From wildemar at freakmail.de  Fri Jul 27 13:29:58 2007
From: wildemar at freakmail.de (Wildemar Wildenburger)
Date: Fri, 27 Jul 2007 19:29:58 +0200
Subject: a simple string question
In-Reply-To: <1185549793.114644.62170@k79g2000hse.googlegroups.com>
References: <1185549793.114644.62170@k79g2000hse.googlegroups.com>
Message-ID: <46AA2B96.6060201@freakmail.de>

vedrandekovic at v-programs.com wrote:
> I have one question about string.I am trying to make an function to
> analyze line  of some text, this is my example: "HELLO;HELLO2:WORLD:",
>  if that function in this text find ";" and ":" ( in this example will
> find both)
>
> e.g  that function must return this:
>
>
> "HELLO;\nHELLO2:\n\t\t\t\t\t\t\tWORLD:"
>   

If I understand you correctly you want to replace ";" by ";\n" and ":" 
by ":\n\t\t\t\t\t\t\t".
Well guess what? The replace() method does just this. Have a read: 


/W


From vasudevram at gmail.com  Thu Jul 26 14:53:07 2007
From: vasudevram at gmail.com (vasudevram)
Date: Thu, 26 Jul 2007 18:53:07 -0000
Subject: Generating PDF reports
In-Reply-To: <13ahbear9nuv841@corp.supernews.com>
References: <13ahbear9nuv841@corp.supernews.com>
Message-ID: <1185475987.291274.230170@o61g2000hsh.googlegroups.com>

On 2007-07-26, marcpp  wrote:

>Hi i'm introducing to do reports from python, any recomendation?

Yes, ReportLab is quite a good PDF library for Python. I used it as
the main underlying component in my xtopdf toolkit - see:

http://www.dancingbison.com/products.html

For most general uses, ReportLab is good choice.

You might want to check out xtopdf if your needs are somewhat simple,
mainly needing to convert text (from any source - plain text files,
CSV, DBF, TDV, XLS (limited support), or other sources) to PDF - as it
provides a slightly easier to use API for people who are not familiar
with ReportLab.

This article should help you use xtopdf for the above-mentioned
purposes:

http://www.packtpub.com/article/Using_xtopdf

xtopdf doesn't support images as of now, nor any sophisticated
formatting - you'll have to use ReportLab if you need that.

Both ReportLab (the open source version) and xtopdf are released under
the BSD license - so you can use them for any purpose you want.

Good luck!

Vasudev Ram

http://www.dancingbison.com
http://jugad.livejournal.com
http://sourceforge.net/projects/xtopdf




From gagsl-py2 at yahoo.com.ar  Fri Jul 13 22:55:30 2007
From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
Date: Fri, 13 Jul 2007 23:55:30 -0300
Subject: Getting values out of a CSV
References: <1184295593.638409.22910@22g2000hsm.googlegroups.com>
	
	
	
	
	
Message-ID: 

En Fri, 13 Jul 2007 09:05:29 -0300, Daniel  escribi?:

>>> > Note that every time you see [x for x in ...] with no condition, you
>>> can
>>> > write list(...) instead - more clear, and faster.
>>> >
>>> > data = list(csv.reader(open('some.csv', 'rb')))
>>>
>>> Faster? No. List Comprehensions are faster.
>>
>> On my system just putting into a list is faster.  I think this is
>> because you don't need to assign each line to the variable 'line' each
>> time in the former case.
>
> I don't know why there seems to be a differece, but I know that list  
> comps
> are python are very heavily optimised.

In principle both ways have to create and populate a list, and a list  
comprehension surely is better than a loop using append() - but it still  
has to create and bind the intermediate variable on each iteration.
I think that testing with a csv file can't show the difference between  
both ways of creating the list because of the high overhead due to csv  
processing.
Using another example, with no I/O involved (a generator for the first  
10000 fibonacci numbers):

C:\TEMP>python -m timeit -s "import fibo" "list(fibo.fibo())"
10 loops, best of 3: 39.4 msec per loop

C:\TEMP>python -m timeit -s "import fibo" "[x for x in fibo.fibo()]"
10 loops, best of 3: 40.7 msec per loop

(Generating less values shows larger differences - anyway they're not  
terrific)

So, as always, one should measure in each specific case if optimization is  
worth the pain - and if csv files are involved I'd say the critical points  
are elsewhere, not on how one creates the list of rows.

-- 
Gabriel Genellina



From paddy3118 at googlemail.com  Mon Jul 30 17:31:07 2007
From: paddy3118 at googlemail.com (Paddy)
Date: Mon, 30 Jul 2007 21:31:07 -0000
Subject: Comparing Dictionaries
In-Reply-To: 
References: 
	<1185611025.943782.162330@w3g2000hsg.googlegroups.com>
	
Message-ID: <1185831067.700679.284510@l70g2000hse.googlegroups.com>

On Jul 30, 8:30 pm, Kenneth Love  wrote:
> At 03:23 AM 7/28/2007, you wrote:
>
> >Hi Kenneth,  being new to Python i wondered if you at least considered
> >Doctests as part of your testing solution.
> >Other languages don't have Doctest.
>
> >- Paddy.
>
> Until I read your post, I had never even heard of Doctest.  I will look
> into it.
>
> Here is the list of online sources I've found:
>
> http://www.ibiblio.org/obp/thinkCSpy/index.htmlhttp://www.diveintopython.org/toc/index.htmlhttp://aspn.activestate.com/ASPN/Cookbook/Python
>
> Here are the O'Reilly books I purchased from Barnes & Noble:
>
> Python in a Nutshell (2nd ed.)
> Python Cookbook (2nd ed.)
> Programming Python (3rd ed.)
>
> I am a slow reader.  So, if Doctests are mentioned in any of the above,
> I haven't encountered it yet.
>
> Specifically, my information on unit testing comes from reading about
> half of this online chapter:
>
> http://www.diveintopython.org/unit_testing/index.html
>
> I will search on Google for more info on Doctest.
>
> Thanks!
>
> Sincerely,
> Kenneth Love

Add to your list:
  http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-2-doctest.html
  http://en.wikipedia.org/wiki/Doctest

Have fun.

- Paddy.



From brotherjenos at gmail.com  Wed Jul 18 00:04:22 2007
From: brotherjenos at gmail.com (Walker Lindley)
Date: Tue, 17 Jul 2007 21:04:22 -0700
Subject: a=0100; print a ; 64 how to reverse this?
In-Reply-To: <1184730853.521234.307760@o11g2000prd.googlegroups.com>
References: <1184670575.205759.115360@i13g2000prf.googlegroups.com>
	<1184673934.660465.228280@i13g2000prf.googlegroups.com>
	<1184676038.231330.115220@e16g2000pri.googlegroups.com>
	<1184730853.521234.307760@o11g2000prd.googlegroups.com>
Message-ID: <9c8d48280707172104y40a641c6tccde4a60cae278b8@mail.gmail.com>

This is probably way more simple than you mean, but str() can turn an int
into a string and int() to go the opposite direction. Is that what you're
talking about or do you need something else?


-Walker Lindley

On 7/17/07, Dan Bishop  wrote:
>
> On Jul 17, 7:40 am, mosi  wrote:
> > Thank you,
> > this is great,
> > I thought that this should be standard in python 2.4 or 2.5 or in some
> > standard library (math ???)
> > Didn`t find anything.
>
> The bin() function is slated to be added to the next version of
> Python.
>
> Why there isn't a general itoa() function, I don't know.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From cai.haibin at gmail.com  Wed Jul 25 23:07:56 2007
From: cai.haibin at gmail.com (james_027)
Date: Thu, 26 Jul 2007 03:07:56 -0000
Subject: cls & self
Message-ID: <1185419276.645373.83570@d30g2000prg.googlegroups.com>

hi,

is cls & self the same thing?

I have seen something like

class A:
    def dosomething(cls):
       #doing something

How is cls & self differ? How is it use?

Thanks
james



From ken at seehart.com  Sat Jul 21 17:07:24 2007
From: ken at seehart.com (Ken Seehart)
Date: Sat, 21 Jul 2007 14:07:24 -0700
Subject: UnicodeDecodeError
In-Reply-To: <46A2709C.3040602@seehart.com>
References: <46A2709C.3040602@seehart.com>
Message-ID: <46A2758C.2050705@seehart.com>

Um, never mind.  The recent unicode conversation gave me my answer  :-)
unicode(s, 'Windows-1252')

Ken Seehart wrote:
> I get this whenever I encounter a non-ascii character in a non-unicode 
> string:
>
> UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 23: 
> ordinal not in range(128)
>
> The string in question is "... ESPA\xd1OL ..."
>
> I completely understand why I get the error, and my solution will be to 
> simply convert to unicode (since the code that uses the string is 
> unicode ready).
>
> I am wondering if anyone knows where I can find a mapping from this 
> particular extended ascii code (where \xd1 is ?), to the corresponding 
> unicode characters.
>
> Ken
>
>
>   



From willmaier at ml1.net  Thu Jul 19 15:49:32 2007
From: willmaier at ml1.net (Will Maier)
Date: Thu, 19 Jul 2007 14:49:32 -0500
Subject: Pure Python equivalent of unix "file" command?
In-Reply-To: <2007071915293516807-w3@w3com>
References: <2007071915293516807-w3@w3com>
Message-ID: <20070719194932.GB12728@lass.lfod.us>

On Thu, Jul 19, 2007 at 03:29:35PM -0400, W3 wrote:
> Just a quick one... Is there such a thing?

Debian et al ship Python bindings[0] for file(1)[1]. file works by
using a file (/etc/magic) with 'magic' numbers in it to figure out
the type of a file. Googling 'python magic' will turn up a few
interesting threads.

[0] http://packages.debian.org/unstable/python/python-magic
[1] http://www.darwinsys.com/file/

-- 

[Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/]


From http  Sun Jul  8 02:20:22 2007
From: http (Paul Rubin)
Date: 07 Jul 2007 23:20:22 -0700
Subject: PEP 3107 and stronger typing (note: probably a newbie question)
References: <5dveb4F360un0U1@mid.individual.net>
	
	<1182858785.886469.93060@n60g2000hse.googlegroups.com>
	<46824d8d$0$2324$426a74cc@news.free.fr>
	
	<5ehokpF38ov3jU2@mid.individual.net>
	<4683d5cd$0$8993$426a74cc@news.free.fr>
	<7xps3e3g9x.fsf@ruckus.brouhaha.com>
	<468565a0$0$3686$426a74cc@news.free.fr>
	<7xhcopj10g.fsf@ruckus.brouhaha.com>
	<46863ea7$0$970$426a34cc@news.free.fr>
	<1i0ikru.1uccqtm1efnzn3N%aleax@mac.com>
	
	<1i0n0tr.ve0o791347ugyN%aleax@mac.com>
	<7xd4za1086.fsf@ruckus.brouhaha.com>
	<5f0mhuF3b0stbU1@mid.individual.net>
	<7xd4z837e2.fsf@ruckus.brouhaha.com>
	<468b7426$0$9063$426a34cc@news.free.fr>
	<7x4pkkun56.fsf@ruckus.brouhaha.com>
	<1183575597.272150.152200@w5g2000hsg.googlegroups.com>
	
	<7xzm2budfv.fsf@ruckus.brouhaha.com>
	
Message-ID: <7xir8vju1l.fsf@ruckus.brouhaha.com>

Steve Holden  writes:
> > Python even leaks the index variable of list comprehensions (I've
> > mostly stopped using them because of this), though that's a
> > recognized wart and is due to be fixed.
> >
> Wow, you really take non-pollution of the namespace seriously. I agree
> it's a wart, but it's one I have happily worked around since day one.

Well, the obvious workaround is just say "list()"
instead of [] so that's what I do.


From mcbooczech at gmail.com  Mon Jul 23 13:10:08 2007
From: mcbooczech at gmail.com (Petr Jakes)
Date: Mon, 23 Jul 2007 17:10:08 -0000
Subject: Catching a key press
In-Reply-To: <1185193381.092023.182050@g4g2000hsf.googlegroups.com>
References: <1185173730.345615.284940@q75g2000hsh.googlegroups.com>
	<1185174340.795377.13800@r34g2000hsd.googlegroups.com>
	<1185182869.893136.139870@k79g2000hse.googlegroups.com>
	<1185193381.092023.182050@g4g2000hsf.googlegroups.com>
Message-ID: <1185210608.377809.258030@w3g2000hsg.googlegroups.com>

On 23  ec, 14:23, westymatt  wrote:
> linux primarily still a little lost in how to implementent this,
> however I understand what you are saying.

maybe you can use this:
http://tinyurl.com/2zyfmw

HTH

Petr Jakes



From jeff at taupro.com  Tue Jul 24 02:35:58 2007
From: jeff at taupro.com (Jeff Rush)
Date: Tue, 24 Jul 2007 01:35:58 -0500
Subject: Python Trainers, Promote Thyself!
Message-ID: <46A59DCE.2080004@taupro.com>

With the recent establishment of the wiki page on python.org for those who
offer training services for the Python language, we now have 23 listed, worldwide.

    http://wiki.python.org/moin/PythonTraining

Many of the trainers are individuals or small companies, and it can be hard to
get the attention of the big IT houses.  While skill credentials and a
portfolio of past training gigs are important, perhaps one of the best
promoters is when someone has actually experienced one of your classes.  They
gain insight into your speaking style, how you relate to the students and your
ability to explain complex technical subjects in an approachable way.  No
class syllabus can convey that.  The Python community has a valuable resource
that can give you the next best thing.  Screencasting!

Screencasting is a multimedia creation that focuses on the instructor's
desktop, with voiceover guidance.  It can be in the format of an online
slideshow, a guided sourcecode walkthrough or a follow-along interactive
session.  They can be as long or short as you wish and they have opportunities
for branding, by using custom wallpaper behind your talks desktop and musical
lead-in/fade-out.

Screencasts can be hosted on www.showmedo.com or, if done with a large font,
video.google.com.  They can also be embedded in your website while hosted
elsewhere, as shown at:

    http://www.python.org/doc/av/5minutes/

You can learn more about the details with a talk series I put together:

    Casting Your Knowledge, With Style
    http://www.showmedo.com/videos/series?name=bETR23HwS

But perhaps you're really busy on current projects and short on time. Consider
 arranging an audio interview about an upcoming seminar you're offering and
making it available as a podcast.  Ron Stephens of Python 411 makes available
an excellent collection of podcasts and may be interested in hosting yours.

Unlike face-to-face presentation opportunities, screencasts/podcasts have the
additional benefit that they promote your training offerings while you're busy
on other gigs.  It's almost like cloning yourself and having more time for
promotion.  It's all about leverage.

Jeff Rush
Python Advocacy Coordinator


From usenet-mail-0306.20.chr0n0ss at spamgourmet.com  Mon Jul  9 07:16:50 2007
From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann)
Date: Mon, 09 Jul 2007 13:16:50 +0200
Subject: What is the most efficient way to test for False in a list?
References: <1183938194.761283.97950@57g2000hsv.googlegroups.com>
	<7x7ipajvst.fsf@ruckus.brouhaha.com>
Message-ID: <5fejp2F3cp3igU1@mid.individual.net>

Paul Rubin wrote:
> lex  writes:

>> list = [1, True, True, False, False, True]
>> status = True
>> for each in list:
>>     status = status and each
>> 
>> but what is your best way to test for for False in a list?
> 
> status = all(list)

Am I mistaken, or is this no identity test for False at all?

Regards,


Bj?rn

-- 
BOFH excuse #317:

Internet exceeded Luser level, please wait until a luser logs off
before attempting to log back on.



From steve at REMOVE.THIS.cybersource.com.au  Sun Jul 29 00:10:20 2007
From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano)
Date: Sun, 29 Jul 2007 14:10:20 +1000
Subject: Pythonic way for missing dict keys
References: 
	
	
	
	<1185041243.323915.161230@x40g2000prg.googlegroups.com>
	
	<87lkd0eprj.fsf@pobox.com>
	
Message-ID: 

On Sat, 28 Jul 2007 11:52:48 +0000, Alex Popescu wrote:

> jjl at pobox.com (John J. Lee) wrote in news:87lkd0eprj.fsf at pobox.com:
> 
>> Alex Popescu  writes:
>> 
>>> Zentrader  wrote in
>>> news:1185041243.323915.161230 @x40g2000prg.googlegroups.com:
>>>
>>>> On Jul 21, 7:48 am, Duncan Booth 
>>>> wrote: 
>>>>
>>>> [snip...]
>>>>
>>>> 
>>>>>From the 2.6 PEP #361 (looks like dict.has_key is deprecated)
>>>> Python 3.0 compatability: ['compatibility'-->someone should use a
>>>> spell-checker for 'official' releases]
>>>>         - warnings were added for the following builtins which no
>>>> longer exist in 3.0:
>>>>              apply, callable, coerce, dict.has_key, execfile,
>>>>              reduce, 
>>>> reload
>>>> 
>>>
>>> I see... what that document doesn't describe is the alternatives to
>>> be used. And I see in that list a couple of functions that are
>>> probably used a lot nowadays (callable, reduce, etc.).
>> 
>> callable and reduce are rarely used, at least in code I've seen.  
> 
> I thought G would be using that function a lot. 

Who or what is G? Guido?

And which of the two functions mentioned is "that function"? callable()?


Instead of doing:


if callable(function): function()

you should do:

try:
    function()
except TypeError:
    pass


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_?)


> 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.

It's a shame really. Oh well, maybe it will sneak back in via a functional
module, or itertools, or something. What a waste, what a waste.


>> Certainly has_key will be
>> the most common of those listed above (but trivial to fix).
> 
> dict.has_key(key) becomes key in dict (correct?)

Yes.



>> apply
>> will be common in old code from the time of Python 1.5.2.
> 
> I think there were some advises to not use apply.


help(apply) already tells you how to replace apply():

    Deprecated since release 2.3. Instead, use the extended call syntax:
    function(*args, **keywords).



>> execfile is
>> perhaps more common that callable (?) but again is really a "maybe 1
>> call in a big program" sort of thing.
> 
> What is the replacement for this one?


Slurp the file into a string, execute the string.


But the thing that makes my brain melt is reload(). No, reload() probably
isn't good enough to use in production code, but for interactive use it is
Good Enough. I'm boggled that it is going away!



-- 
Steven.



From tuom.larsen at gmail.com  Wed Jul  4 08:49:25 2007
From: tuom.larsen at gmail.com (tuom.larsen at gmail.com)
Date: Wed, 04 Jul 2007 05:49:25 -0700
Subject: CGI vs WSGI
Message-ID: <1183553365.160758.29320@q75g2000hsh.googlegroups.com>

Dear all,

what is the difference? Middleware?

I'm wondering because the only variables I ever needed were PATH_INFO,
REQUEST_METHOD, QUERY_STRING and maybe one more, all of which should
be available from CGI, too.

Thanks.



From deets at nospam.web.de  Mon Jul 23 08:30:27 2007
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Mon, 23 Jul 2007 14:30:27 +0200
Subject: Need Help with base64
References: <1185193741.420611.302290@z28g2000prd.googlegroups.com>
Message-ID: <5gjlb4F3g61srU1@mid.uni-berlin.de>

pycraze wrote:

> Hi ,
> 
>   I am currently trying to implement base64 encoding and decoding
> scheme in C . Python has a module , base64 , that will  do the
> encoding and decoding with ease . I am aware of OpenSSL having support
> for base64 encoding and decoding , but i will have to now implement
> both in C without using the openssl libraries .
> 
>     I was able to download a code w.r.t. base 64 encoding and
> decoding . I am attaching the code below .
> 
> 
> void encodeblock( unsigned char cin[3], unsigned char cout[4], int
> nlen )
> {
> 
>     cout[0] = cb64[ cin[0] >> 2 ];
>     cout[1] = cb64[ ((cin[0] & 0x03) << 4) | ((cin[1] & 0xf0) >> 4) ];
>     cout[2] = (unsigned char) (nlen > 1 ? cb64[ ((cin[1] & 0x0f) << 2)
> | ((cin[2] & 0xc0) >> 6) ] : '=');
>     cout[3] = (unsigned char) (nlen > 2 ? cb64[ cin[2] & 0x3f ] :
> '=');
> }
> 
> 
> void decodeblock( unsigned char cin[4], unsigned char cout[3] )
> {
>     cout[ 0 ] = (unsigned char ) (cin[0] << 2 | cin[1] >> 4);
>     cout[ 1 ] = (unsigned char ) (cin[1] << 4 | cin[2] >> 2);
>     cout[ 2 ] = (unsigned char ) (((cin[2] << 6) & 0xc0) | cin[3]);
> }
> 
> 
> int base641_decodestring(char* pcstr,int size,char** ppcdest)
> {
>       unsigned char cin[4] = {""};
>   unsigned char cout[3] = {""};
>       unsigned char  cv = 0;
>       int ni = 0;
>   int nlen = 0;
>       char* cptr = pcstr;
>       *ppcdest = malloc(sizeof(char)*160);
>       if (!*ppcdest)
>         {
>             return 1;
>         }
>       memset(*ppcdest,0,sizeof(char)*160);
> 
>   char* pcstring = malloc( sizeof(char) * SIZE);
>     if (!pcstring)
>       {
>           aps_log("APS_log.txt","\nbae64.c:base64encode:malloc failed
> \n");
>           return 1;
>       }
>   memset(pcstring,'\0',SIZE);
> 
>         for( nlen = 0, ni = 0; ni < 4; ni++ )
>   {
>             cv = 0;
>             while(  cv == 0 )
>       {
>                 cv = (unsigned char) *cptr;
>                 cv = (unsigned char) ((cv < 43 || cv > 122) ? 0 :
> cd64[ cv - 43 ]);
>                 if( cv )
>     {
>                     cv = (unsigned char) ((cv == '$') ? 0 : cv - 61);
>                 }
>             }
>             if( cptr++ )
>       {
>                 nlen++;
>                 if( cv )
>     {
>                     cin[ ni ] = (unsigned char) (cv - 1);
>                 }
>             }
>             else
>       {
>                 cin[ni] = 0;
>             }
>         }
>         if( nlen )
>   {
>             decodeblock( cin, cout );
> 
>         }
>   memcpy(*ppcdest,cout,160);
>   return 0;
> }/*end of base64_decode */
> 
> char* base64_encode(char* pcstr)
> {
>   unsigned char cin[3] = {""};
>   unsigned char cout[4] = {""};
>   int ni = 0;
>   int nlen = 0;
>   int flag = 1;
>   char* cptr = pcstr;
>   char* pcstring = malloc( sizeof(char) * SIZE);
>     if (!pcstring)
>       {
>           aps_log("APS_log.txt","\nbae64.c:base64encode:malloc failed
> \n");
>           return (void*)0;
>       }
>   memset(pcstring,'\0',SIZE);
>   while( flag )
>   {
>     for( ni = 0; ni < 3; ni++ )
>     {
>       cin[ni] = (unsigned char)*cptr;
>       if( *++cptr != '\0' )
>         nlen++;
>       else
>       {
>         cin[ni] = 0;
>               flag = 0;
>         break;
>       }
>     }
>     encodeblock(cin, cout,nlen);
>     strcat(pcstring,cout);
>   }
> 
>   return pcstring;
> 
> }/* end of base64_encode */
> 
> 
>           But this code gives different hex values as compared to the
> python base64.encodestring and base64.decodestring respectively .
> 
>          I need some help on this matter . I need some pointers on
> where is the mistake for the above file .

How about posting that in a C-newsgroup? python _has_ base64-encoding
support.

Diez


From tazmaster at rocketmail.com  Tue Jul 10 00:47:17 2007
From: tazmaster at rocketmail.com (Jim Langston)
Date: Mon, 9 Jul 2007 21:47:17 -0700
Subject: 2**2**2**2**2 wrong? Bug?
References: 
	<7xbqek7ty1.fsf@ruckus.brouhaha.com>
Message-ID: 

"Paul Rubin"  wrote in message 
news:7xbqek7ty1.fsf at ruckus.brouhaha.com...
> "Jim Langston"  writes:
>> In Python 2.5 on intel, the statement
>> 2**2**2**2**2
>> evaluates to
>> >>> 2**2**2**2**2
>
> I get the same number from hugs--why do you think it might be wrong?

2**2 = 4
4**2 = 16
16**2 = 256
256**2 = 65536
65536**2 = 4294967296

In fact, if I put (2**2)**2**2**2
it comes up with the correct answer, 4294967296




From deets at nospam.web.de  Sun Jul  1 08:15:45 2007
From: deets at nospam.web.de (Diez B. Roggisch)
Date: Sun, 01 Jul 2007 14:15:45 +0200
Subject: Python + Google Calendar API issue
In-Reply-To: <1183246269.152344.3510@c77g2000hse.googlegroups.com>
References: <1183246269.152344.3510@c77g2000hse.googlegroups.com>
Message-ID: <5epk7jF39ch77U1@mid.uni-berlin.de>

kyosohma at gmail.com schrieb:
> Hi,
> 
> I was trying to hook into Google Calendar today using their gdata
> module for Python, but I can't seem to get Python to work with it.
> When I run the setup.py from the command line, I get the following:
> 
> Traceback (most recent call last):
>   File "J:\Python\Lib\site-packages\gdata\setup.py", line 39, in ?
>     package_dir = {'gdata':'src/gdata', 'atom':'src/atom'}
>   File "J:\Python\lib\distutils\core.py", line 137, in setup
>     raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" %
> msg
> SystemExit: usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2
> [cmd2_opts] ...]
>    or: setup.py --help [cmd1 cmd2 ...]
>    or: setup.py --help-commands
>    or: setup.py cmd --help
> 
> error: no commands supplied
> 
> 
> I tried using some different commands, like --verbose, but it would
> just give me the same traceback. I also tried manually copying all the
> files into my site-packages directory (as you can see from the
> traceback) in hopes that it might work without running the setup.py
> file.
> 
> Does anyone have any ideas? I don't usually have any problem getting
> these things to work. I am using Python 2.4.3 on Windows XP Pro SP2.

Did you supply an install command:


python setup.py install

--verbose is no command.

Diez


From info at gegereka.org  Mon Jul 16 19:15:03 2007
From: info at gegereka.org (GEGEREKA!)
Date: 16 Jul 2007 23:15:03 GMT
Subject: [Music Movies Soft] Free binaries search & download = www.GEGEREKA.com
Message-ID: <469bfbf6$0$14557$f69f905@mamut2.aster.pl>

Project of the year: Incredible unique search machine like nothing on earth.
MP3,MPEG,AVI,DIVX,DLL,PHP,EXE,ISO, ...and much more
Millions files for everyone. Music, movies, soft and other media.
http://www.GEGEREKA.com : THE LORD OF DOWNLOADS.


From nytrokiss at gmail.com  Thu Jul 19 13:14:53 2007
From: nytrokiss at gmail.com (James Matthews)
Date: Thu, 19 Jul 2007 10:14:53 -0700
Subject: Copy List
In-Reply-To: <5g9js0F3eddssU1@mid.uni-berlin.de>
References: <-29831789359750479@unknownmsgid>
	<6a2ccd190707180544k4909ad3enc6a962917a26f43d@mail.gmail.com>
	
	<1184862114.094387.257580@i13g2000prf.googlegroups.com>
	<5g9js0F3eddssU1@mid.uni-berlin.de>
Message-ID: <8a6b8e350707191014m2fc5543aq944ed1f4a6f7c0f0@mail.gmail.com>

A slice still has some references to the old objects a deep copy is a
totally new object!

On 19 Jul 2007 17:04:00 GMT, Marc 'BlackJack' Rintsch 
wrote:
>
> On Thu, 19 Jul 2007 09:21:54 -0700, Falcolas wrote:
>
> > On Jul 18, 6:56 am, "Rustom Mody"  wrote:
> >> This is shallow copy
> >> If you want deep copy then
> >> from copy import deepcopy
> >
> > What will a "deep copy" of a list give you that using the slice
> > notation will not?
>
> Well, a deep copy of course.  ;-)
>
> In [6]: import copy
>
> In [7]: a = [[1, 2], [3, 4]]
>
> In [8]: b = a[:]
>
> In [9]: c = copy.deepcopy(a)
>
> In [10]: a[0][1] = 42
>
> In [11]: a
> Out[11]: [[1, 42], [3, 4]]
>
> In [12]: b
> Out[12]: [[1, 42], [3, 4]]
>
> In [13]: c
> Out[13]: [[1, 2], [3, 4]]
>
> Ciao,
>         Marc 'BlackJack' Rintsch
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://www.goldwatches.com/Watches.asp?Brand=14
http://www.jewelerslounge.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From zyzhu2000 at gmail.com  Sat Jul 28 08:10:48 2007
From: zyzhu2000 at gmail.com (beginner)
Date: Sat, 28 Jul 2007 05:10:48 -0700
Subject: Tkinter program with a usable interpreter console
In-Reply-To: <46aa7d01$0$21933$157c6196@dreader1.cybercity.dk>
References: <1185572221.020114.192650@z24g2000prh.googlegroups.com>
	<46aa7d01$0$21933$157c6196@dreader1.cybercity.dk>
Message-ID: <1185624648.646425.9390@j4g2000prf.googlegroups.com>

On Jul 27, 6:17 pm, Ivan Johansen  wrote:
> beginner wrote:
> > The problem is that the Tkinter program ends with a .mainloop() call
> > and it is not going to give back control to the command prompt. I feel
> > it is almost like I need to implement the python shell myself. Is
> > there any better way of doing this?
>
> Take a look at this:http://lfw.org/python/Console.py
>
> I haven't really used it myself yet, but it looks really great.
>
> Ivan Johansen

It looks interesting. Let me take a close look.



From evan at yelp.com  Fri Jul 13 02:32:22 2007
From: evan at yelp.com (Evan Klitzke)
Date: Thu, 12 Jul 2007 23:32:22 -0700
Subject: Fast powerset function
In-Reply-To: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com>
References: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com>
Message-ID: 

On 7/12/07, Arash Arfaee  wrote:
> I need a powerset generator function. It's really slow with recursion. Does
> anybody have any idea or code(!!) to do it in an acceptable time?
> Thanks
> -Arash

I thought that this was a really interesting question, so I wrote up a
solution that doesn't use recursion. I didn't test it a whole lot, but
I'm pretty sure it works -- let me know if there are any oversights or
if you can make any improvements ;-) Also, not sure if the line breaks
will be mangled by my mail client, so bear with me if there are any
errors.

def fact(n):
        '''Factorial'''
        r = 1
        for i in xrange(1, n + 1):
                r *= i
        return r

def nCr(n, r):
        '''Number of combinations of r items from n things'''
        return fact(n) / (fact(r) * fact(n - r))

def get_combinations(slots, tokens):
        '''A generator yielding combinations from slots of size tokens'''
        maxcombos = nCr(len(slots), tokens)
        for index in xrange(maxcombos):
                token_copy = tokens
                combo = []
                for val in xrange(1, len(slots) + 1):
                        if not token_copy:
                                break
                        thresh = nCr(len(slots) - val, token_copy - 1)
                        if index < thresh:
                                combo.append(slots[val-1])
                                token_copy -= 1
                        else:
                                index -= thresh
                yield tuple(combo)

def powerset(s):
        '''Returns the powerset of s'''
        pset = set()
        for num_tokens in xrange(1, len(s)):
                for combo in get_combinations(s, num_tokens):
                        pset.add(combo)
        # These two are special cases
        pset.add(s)
        pset.add(tuple())
        return pset

if __name__ == '__main__':
        print powerset((1, 2, 3, 4))


-- 
Evan Klitzke 


From axjacob at comcast.net  Thu Jul  5 19:23:08 2007
From: axjacob at comcast.net (axjacob at comcast.net)
Date: Thu, 05 Jul 2007 23:23:08 +0000
Subject: Htmllib help
Message-ID: <070520072323.4867.468D7D5C000207F00000130322058861720D010C0E06A10407020E@comcast.net>


I am using html and formater as shown below. They are used as part of a larger program.

Even though I don't use any print statements, the htmllib seems to be throwing parts of the html page on to the standard out(my screen in this case). Is there a way to disable the output?

import htmllib
w = formatter.DumbWriter() 
format = formatter.AbstractFormatter(w)
p = htmllib.HTMLParser(format)
    p.feed(inhtml)
    p.close()
    for x in p.anchorlist:
       ...."Use x in regex"


Thanks


From mensanator at aol.com  Sat Jul 28 03:19:02 2007
From: mensanator at aol.com (mensanator at aol.com)
Date: Sat, 28 Jul 2007 00:19:02 -0700
Subject: 128 or 96 bit integer types?
In-Reply-To: 
References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com>
	
	<1185562901.206212.52570@j4g2000prf.googlegroups.com>
	
Message-ID: <1185607142.096574.209200@e16g2000pri.googlegroups.com>

On Jul 28, 12:30 am, Tim Roberts  wrote:
> "mensana... at aol.com"  wrote:
>
> >On Jul 27, 1:27 pm, Peter Otten <__pete... at web.de> wrote:
> >> Robert Dailey wrote:
> >> > Is there build-in or third party support for large integer types, such
> >> > as 96 or 128 bits in size? I require such large sizes for precision
> >> > issues (nanoseconds). Thanks.
> >> >>> SECOND = 10**9
> >> >>> YEAR = 365*24*60*60
> >> >>> 2**128/SECOND/YEAR
>
> >> 10790283070806014188970L
>
> >> What are you measuring? The age of the universe? In nanoseconds?
>
> >> :-)
>
> >Well, 2**96 would only be 2512308552583 years.
>
> Yes, but that's still roughly 100 times the estimated age of the universe.

Yeah, I know. I thought it was so obvious I didn't need a :-).

But _I_ won't question the need for numbers that large.
That's how I got into Python in the first place,
looking for Big Arithmetic. And I've been very happy
with it. Especially compared to the competition.
Would you believe that new F# language from Microsoft
doesn't even have an exponentiation operator? It has
a power function for floats, but not for Big Integers.
Completely worthless.

Some very simple questions can have very big answers.

For example, how many ways can you put 492 marbles into
264 ordered bins such that each bin has at least 1 marble?

The answer

66189415264331559482776409694993032407028709677550
59629130019289014193777349831417543311612293951363
4124491233746912456893016976209252459301489030

has 146 digits. And that's just the begining. The above
actually represents a polynomial with 264 terms, the
exponents of which range from 0 to 492. One of those
polynomials can have over 50000 decimal digits when
solved.

So I never let the age of the universe intimidate me.

Of course, I can't solve ALL the polynomials.
Gotta be a bit selective. :-)




From reddyist at gmail.com  Thu Jul 19 19:03:23 2007
From: reddyist at gmail.com (Reddy)
Date: Fri, 20 Jul 2007 02:03:23 +0300
Subject: idiom for RE matching
In-Reply-To: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com>
References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com>
Message-ID: 

On 7/19/07, Gordon Airporte  wrote:
>
> I have some code which relies on running each line of a file through a
> large number of regexes which may or may not apply. For each pattern I
> want to match I've been writing
>
> gotit = mypattern.findall(line)



Try to use iterator function finditer instead of findall. To see the
difference run below code by calling findIter or findAll function one at a
time in for loop.  You can have achieve atleast 4x better performance.

-----------------------------------------------------------------------------------
import re
import time

m = re.compile(r'(\d+/\d+/\d+)')
line = "Today's date is 21/07/2007 then yesterday's  20/07/2007"

def findIter(line):
    m.finditer(line)
    glist = [x.group(0) for x in g]

def findAll(line):
    glist = m.findall(line)

start = time.time()
for i in xrange(1000000):
    #findIter(line)
    findAll(line)
end = time.time()

print end-start

--------------------------------------------------------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: 

From bj_666 at gmx.net  Mon Jul 30 02:22:49 2007
From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch)
Date: 30 Jul 2007 06:22:49 GMT
Subject: Hex editor display - can this be more pythonic?
References: 
	<5h49ijF3iormrU1@mid.uni-berlin.de> 
Message-ID: <5h5edpF3hmufcU2@mid.uni-berlin.de>

On Sun, 29 Jul 2007 18:27:25 -0700, CC wrote:

> Marc 'BlackJack' Rintsch wrote:
>> I'd use `string.printable` and remove the "invisible" characters like '\n'
>> or '\t'.
> 
> What is `string.printable` ?  There is no printable method to strings, 
> though I had hoped there would be.  I don't yet know how to make one.

In [8]: import string

In [9]: string.printable
Out[9]: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'(
)*+,-./:;<=>?@[\\]^_`{|}~\t\n\r\x0b\x0c'

>>>for c in ln:
>>>     if c in printable: sys.stdout.write(c)
>>>     else: sys.stdout.write('.')
> 
>> The translation table can be created once and should be faster.
> 
> I suppose the way I'm doing it requires a search through `printable` for 
> each c, right?  Whereas the translation would just be a lookup 
> operation?

Correct.  And it is written in C.

Ciao,
	Marc 'BlackJack' Rintsch


From ironfroggy at gmail.com  Sun Jul 22 14:15:17 2007
From: ironfroggy at gmail.com (Calvin Spealman)
Date: Sun, 22 Jul 2007 14:15:17 -0400
Subject: Advice on sending images to clients over network
In-Reply-To: <46A39BC8.6030106@ulmcnett.com>
References: <1185095666.627415.108450@w3g2000hsg.googlegroups.com>
	<7xlkd8mktt.fsf@ruckus.brouhaha.com> <46A39BC8.6030106@ulmcnett.com>
Message-ID: <76fd5acf0707221115y5cfa7742s3228263640376436@mail.gmail.com>

On 7/22/07, Paul McNett 

wrote: > Paul Rubin wrote: > > Frank Millman writes: > >> Any suggestions will be much appreciated. > > > > Why on earth don't you write the whole thing as a web app instead of > > a special protocol? Then just use normal html tags to put images > > into the relevant pages. > > I believe he has a full desktop client app, not a web app. Believe it or > not, there's still a solid place for desktop applications even in this > ever-increasing webified world. > > Use the right tool for the job... There is no reason that something being a "desktop app" means they can't use HTTP instead of reinventing the protocol wheel all over again. > -- > pkm ~ http://paulmcnett.com > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From stefan.behnel-n05pAM at web.de Sat Jul 14 07:28:55 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 14 Jul 2007 13:28:55 +0200 Subject: Right tool and method to strip off html files (python, sed, awk?) In-Reply-To: <1184353058.660535.140110@m3g2000hsh.googlegroups.com> References: <1184353058.660535.140110@m3g2000hsh.googlegroups.com> Message-ID: <4698B377.8040306@web.de> sebzzz at gmail.com wrote: > 1- Find all html files in the folders (sub-folders ...) > 2- Do some file I/O and feed Sed or Python or what else with the file. > 3- Apply recursively some regular expression on the file to do the > things a want. (delete when it encounters certain tags, certain > attributes) > 4- Write the changed file, and go through all the files like that. Use the lxml.html.clean module, which is made exactly for that purpose. It's not released yet, but you can use it from the current html branch of lxml. There will soon be an official alpha of the 2.0 series, which will contain lxml.html: http://codespeak.net/svn/lxml/branch/html/ It looks like you're on Ubuntu, so compiling it from sources after an SVN checkout should be as simple as the usual setup.py dance. Please report back to the lxml mailing list if you find any problems or have any further ideas on how to make it even more versatile than it already is. For lxml is general, see: http://codespeak.net/lxml/ Stefan From nagle at animats.com Mon Jul 23 00:59:41 2007 From: nagle at animats.com (John Nagle) Date: Sun, 22 Jul 2007 21:59:41 -0700 Subject: URL parsing for the hard cases In-Reply-To: References: <1185138747.707836.69740@n2g2000hse.googlegroups.com> Message-ID: Here's another hard case. This one might be a bug in urlparse: import urlparse s = 'ftp://administrator:password at 64.105.135.30/originals/6 june 07/ebay/login/ebayisapi.html' urlparse.urlparse(s) yields: (u'ftp', u'administrator:password at 64.105.135.30', u'/originals/6 june 07/ebay/login/ebayisapi.html', '', '', '') That second field is supposed to be the "hostport" (per the RFC usage of the term; Python uses the term "netloc"), and the username/password should have been parsed and moved to the "username" and "password" fields of the object. So it looks like urlparse doesn't really understand FTP URLs. That's a real URL, from a search for phishing sites. There are lots of hostile URLs out there. Some of which can fool some parsers. John Nagle John Nagle wrote: > memracom at yahoo.com wrote: > >> Once you eliminate IPv6 addresses, parsing is simple. Is there a >> colon? Then there is a port number. Does the left over have any >> characters not in [0123456789.]? Then it is a name, not an IPv4 >> address. >> >> --Michael Dillon >> > > You wish. Hex input of IP addresses is allowed: > > http://0x525eedda > > and > > http://0x52.0x5e.0xed.0xda > > are both "Python.org". Or just put > > 0x52.0x5e.0xed.0xda > > into the address bar of a browser. All these work in Firefox on Windows > and > are recognized as valid IP addresses. > > On the other hand, > > 0x52.com > > is a valid domain name, in use by PairNIC. > > But > > http://test.0xda > > is handled by Firefox on Windows as a domain name. It doesn't resolve, > but it's > sent to DNS. > > So I think the question is whether every term between dots can be parsed as > a decimal or hex number. If all terms can be parsed as a number, and > there are > no more than four of them, it's an IP address. Otherwise it's a domain > name. > > There are phishing sites that pull stuff like this, and I'm parsing a > long list > of such sites. So I really do need to get the hard cases right. > > Is there any library function that correctly tests for an IP address vs. a > domain name based on syntax, i.e. without looking it up in DNS? > > John Nagle From steve at holdenweb.com Sat Jul 7 19:36:06 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 07 Jul 2007 19:36:06 -0400 Subject: httplib module In-Reply-To: References: Message-ID: Boris Ozegovic wrote: > Boris Ozegovic wrote: > >> Why do I get double new lines when geting data from server? Example: > > Fixed. > How? It's customary to include details when you've solved your own problem in case someone else gets the same 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 michele.simionato at gmail.com Mon Jul 16 00:23:08 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 16 Jul 2007 04:23:08 -0000 Subject: How to determine which method was used in an inheritance heirarchy? In-Reply-To: References: Message-ID: <1184559788.712146.238190@q75g2000hsh.googlegroups.com> On Jul 16, 5:51 am, Erik Jones wrote: > Say you're given a call event frame for a method call. How can you > tell if the code being executed came from a super class of the object > or class the method was called on? > > Erik Jones You look if the method was defined in self.__class__.__dict__. Michele Simionato From nagle at animats.com Fri Jul 13 12:54:16 2007 From: nagle at animats.com (John Nagle) Date: Fri, 13 Jul 2007 09:54:16 -0700 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: Chris Carlen wrote: > Hi: > > From what I've read of OOP, I don't get it. I have also found some > articles profoundly critical of OOP. I tend to relate to these articles. > > However, those articles were no more objective than the descriptions of > OOP I've read in making a case. Ie., what objective > data/studies/research indicates that a particular problem can be solved > more quickly by the programmer, or that the solution is more efficient > in execution time/memory usage when implemented via OOP vs. procedural > programming? > > The problem for me is that I've programmed extensively in C and .asm on > PC DOS way back in 1988. Then didn't program for nearly 10 years during > which time OOP was popularized. Starting in 1999 I got back into > programming, but the high-level-ness of PC programming and the > completely foreign language of OOP repelled me. My work was in analog > and digital electronics hardware design, so naturally I started working > with microcontrollers in .asm and C. Most of my work involves low-level > signal conditioning and real-time control algorithms, so C is about as > high-level as one can go without seriously loosing efficiency. The > close-to-the-machine-ness of C is ideal here. This is a realm that I > truly enjoy and am comfortable with. > > Hence, being a hardware designer rather than a computer scientist, I am > conditioned to think like a machine. I think this is the main reason > why OOP has always repelled me. Why? I've written extensively in C++, including hard real-time programming in C++ under QNX for a DARPA Grand Challenge vehicle. I have an Atmel AVR with a cable plugged into the JTAG port sitting on my desk right now. Even that little thing can be programmed in C++. You can sometimes get better performance in C++ than in C, because C++ has "inline". Inline expansion happens before optimization, so you can have abstractions that cost nothing. If it has state and functions, it probably should be an object. The instances of the object can be static in C++; dynamic memory allocation isn't required in C++, as it is in Python. Python is a relatively easy language, easier than C++, Java, or even Perl. It's quite forgiving. The main implementation, CPython, is about 60x slower than C, though, so if you're trying to implement, say, a rapidly changing digital oscilloscope display, the result may be sluggish. John Nagle From sjmachin at lexicon.net Tue Jul 24 19:25:54 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 24 Jul 2007 16:25:54 -0700 Subject: how to get next month string? In-Reply-To: References: <1185279342.863711.246700@d30g2000prg.googlegroups.com> Message-ID: <1185319554.711890.138180@z24g2000prh.googlegroups.com> On Jul 24, 11:16 pm, Carsten Haese wrote: > On Tue, 2007-07-24 at 05:15 -0700, John Machin wrote: > > On Jul 24, 8:31 pm, "Yinghe Chen" wrote: > > > Hi, > > > Could someone help on how to use python to output the next month string like > > > this? > > > > "AUG07", suppose now is July 2007. > > > > I think also need to consider Dec 07 case, it is supposed to output as > > > below: > > > "JAN07". > > > > datetime module seems not supporting the arithmatic operations, any hints? > > > > Thanks in advance, > > > > Yinghe Chen > > > >>> import datetime > > >>> def nextmo(d): > > ... mo = d.month > > ... yr = d.year > > ... mo += 1 > > ... if mo > 12: > > ... mo = 1 > > ... yr += 1 > > ... return datetime.date(yr, mo, 1).strftime('%b%y').upper() > > A more concise variant:>>> import datetime > >>> def nextmo(d): > > ... mo = d.month > ... yr = d.year > ... nm = datetime.date(yr,mo,1)+datetime.timedelta(days=31) > ... return nm.strftime('%b%y').upper() > > Going 31 days from the first of any month will always get us into the > next month. The resulting day of the month will vary, but we're throwing > that away with strftime. +1 for the "+ 31 days" trick Sorry about the assembly language :-) Here's an alternative for folks who prefer legibility: >>> def nextmo(d): ... yr, mo = divmod(d.year * 12 + d.month, 12) ... return datetime.date(yr, mo + 1, 1).strftime('%b%y').upper() <:-)> And for the other folks, one of these days I'll get around to writing a PEP for the /% operator. From captainpoutine at gmail.com Thu Jul 5 12:34:37 2007 From: captainpoutine at gmail.com (Captain Poutine) Date: Thu, 05 Jul 2007 12:34:37 -0400 Subject: Where is the syntax for the dict() constructor ?! Message-ID: <468D1D9D.6060002@gmail.com> I'm simply trying to read a CSV into a dictionary. (if it matters, it's ZIP codes and time zones, i.e., 35983,CT 39161,CT 47240,EST Apparently the way to do this is: import csv dictZipZones = {} reader = csv.reader(open("some.csv", "rb")) for row in reader: # Add the row to the dictionary But how to do this? Apparently there is no dict.append() nor dict.add() But what is there? I see vague references to "the dict() constructor" and some examples, and news that it has been recently improved. But where is the full, current documentation for the dict() constructor? Frustrated, Captain Poutine From bignose+hates-spam at benfinney.id.au Wed Jul 18 00:31:27 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 18 Jul 2007 14:31:27 +1000 Subject: Single-stepping through a python script References: Message-ID: <87myxufi3k.fsf@benfinney.id.au> Craig Howard writes: > Sorry, I didn't give enough detail. Is it possible to single-step > through a code object without using pdb? (Pdb uses the console which > is not what I want.) Rather than play elimination, could you tell us more about what you *do* want? That is, please describe what you want as a positive instead of "not using the console". -- \ "Pinky, are you pondering what I'm pondering?" "Wuh, I think | `\ so, Brain, but how will we get three pink flamingos into one | _o__) pair of Capri pants?" -- _Pinky and The Brain_ | Ben Finney From star.public at gmail.com Fri Jul 27 15:01:05 2007 From: star.public at gmail.com (star.public at gmail.com) Date: Fri, 27 Jul 2007 12:01:05 -0700 Subject: Imported globals? In-Reply-To: References: Message-ID: <1185562865.896992.112860@w3g2000hsg.googlegroups.com> On Jul 27, 1:30 pm, Valentina Vaneeva wrote: > Thank you, Gary, but I still have one question. What happens in the > second case? If I add a call to change_value() to module_a, the value > in module_b is imported changed. Why? What exactly does the import > statement import in my example? Because then by the time you import the thing, that action has been carried out. Consider: from module_a import change_value change_value() from module a import value print value It's not significantly different from this: ----- class NotaModule(object): pass nota = NotaModule() nota.a = 1 def change_it(): global nota # not even sure you need this nota.a = 2 a = nota.a change_it() print a, nota.a ------ Modules and (singleton) objects are rather similar from the outside, afaik. Also consider that this is yet another case where if value or A was a list and you appended to it, both prints would show the change, mutable objects, etc. -- Tired Weaver From cam.ac.uk at mh391.invalid Mon Jul 23 21:55:34 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 24 Jul 2007 02:55:34 +0100 Subject: pylint style convention In-Reply-To: <46a53823$0$3769$80265adb@spool.cs.wisc.edu> References: <46a53823$0$3769$80265adb@spool.cs.wisc.edu> Message-ID: Mick Charles Beaver wrote: > Hello, > > I've been looking into using PyLint on some of my programs, just as a > best practices kind of thing. > > Here's a snippet: > #====================================================================== > if __name__ == '__main__': > parser = optparse.OptionParser(usage='usage: %prog [OPTIONS]') > parser.add_option('-c', '--config', > action='store', > type='string', > dest='configFilename', > help='config file containing defaults') > (options, args) = parser.parse_args() > #====================================================================== > > Now, PyLint reports the following convention warnings: > C:158: Invalid name "parser" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) > C:170: Invalid name "options" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) > C:170: Invalid name "args" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) > > Which style convention is it referring to? Should these really be all > caps? There's a style convention that global constants at file scope are defined in all caps. Personally, I do all my optparsing in a special function rather than in the __name__ == '__main__' block. -- Michael Hoffman From apetresc at uwaterloo.ca Thu Jul 12 22:14:04 2007 From: apetresc at uwaterloo.ca (Adrian Petrescu) Date: Thu, 12 Jul 2007 19:14:04 -0700 Subject: Client-side cookies on Python in Mac OSX Message-ID: <1184292844.383002.128420@n2g2000hse.googlegroups.com> Hi, all. I'm writing an app for OS X; therefore I'd prefer to use only the default python install that comes with Tiger. For the moment, however, this means: NaviOSX:~ adrianpetrescu$ python -V Python 2.3.5 Therefore, I was not surprised to find out that cookielib did not exist here, since I knew that it was a 2.4+ feature. However, I *was* shocked to find out that ClientCookie, which I'd thought was a Python 2.0+ feature, also cannot be found: >>> import ClientCookie Traceback (most recent call last): File "", line 1, in ? ImportError: No module named ClientCookie Why would Apple go out of their way to remove this functionality from their shipped version of Python? More importantly, considering I need to programatically access a website that uses cookies for authentication, how can I do this in OSX's Python install? Do they provide some other library they'd prefer you to use? I'm sure SOMEONE in the world has used cookies on Macs so I'm hoping there is a solution for this... Thanks in advance! -- Adrian Petrescu From carsten at uniqsys.com Mon Jul 30 21:09:22 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 30 Jul 2007 21:09:22 -0400 Subject: Pysqlite storing file as blob example In-Reply-To: <1185841540.275571.161640@g4g2000hsf.googlegroups.com> References: <1185841540.275571.161640@g4g2000hsf.googlegroups.com> Message-ID: <1185844162.4042.47.camel@localhost.localdomain> On Tue, 2007-07-31 at 00:25 +0000, rustyhowell at gmail.com wrote: > I'm trying to store binary data in a sqlite database and call into the > db using pysqlite 3. > What I've got so far is this: > > import sqlite > con = sqlite.connect(DB_PATH) > cur = con.cursor()mean > query = """create table t1( > ID INTEGER PRIMARY KEY, > data BLOB );""" > cur.execute(query) > con.commit() > b = buffer('/path/to/binary/file') > query = 'insert into table (ID,data) values (1,?);' > result = cur.execute(query,(b)) The second argument to execute() must be a sequence of parameter values. You have one parameter value, the string b. To make a one-tuple, you need a comma, as in "(b,)". > con.commit() > > The error message I get is : > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/site-packages/sqlite/main.py", line 255, in > execute > self.rs = self.con.db.execute(SQL % parms) This traceback line worries me. I'm almost certain that you're not using the latest version of the sqlite module. The module that is included with Python2.5 is called sqlite3, and it lives in .../python/site-packages/sqlite3/* and .../python/lib-dynload/_sqlite3.so. HTH, -- Carsten Haese http://informixdb.sourceforge.net From josiah.carlson at sbcglobal.net Wed Jul 4 11:27:58 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Wed, 04 Jul 2007 08:27:58 -0700 Subject: Memory leak issue with complex data structure In-Reply-To: References: Message-ID: Alan Franzoni wrote: > I have a root node which is not referenced by any other node. So, I > created a "clear()" method which is called on all children (by calling > their clear() method" and then clears the set with the references of the > node itself. Using the .clear() method on sets (or dictionaries) does not reduce the memory that the underlying hash tables use, it only removes references to the keys (and values) that the sets (and dictionaries) contain(s). If your sets used to be large, I could have sworn that you could force a resize down by adding some items to the set, but I seem to be mistaken: #memory use is 3440k s = set(xrange(1000000)) #memory use is 31,864k s.clear() #memory use is 15,460k s.add(0) s.remove(0) #memory use is 15,460k Then again, this may be an artifact of my operating system memory freeing semantics. As is usually the case, read the C source from svn.python.org/view (or some other means) for more information. - Josiah From mail at microcorp.co.za Wed Jul 11 02:04:21 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 11 Jul 2007 08:04:21 +0200 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com><1183576255.668414.256990@q69g2000hsb.googlegroups.com><5f31fvF3asl6lU1@mid.individual.net><1183665370.643503.157060@m36g2000hse.googlegroups.com> <5fh0imF3cjte7U1@mid.individual.net> Message-ID: <000201c7c3be$40558ee0$03000080@hendrik> "greg" wrote: > > Another thought: If the cosmologists ever decide if > and when the Big Crunch is going to happen, we may be > able to figure out once and for all how many bits we > need in the timestamp. > Unless of course, its all an oscillation - bang, crunch, bang, crunch, as the cosmic engine ticks over... But of course, cycles other than our own are kind of unreachable. - Hendrik From horpner at yahoo.com Thu Jul 5 15:11:58 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 05 Jul 2007 19:11:58 GMT Subject: Re-raising exceptions with modified message References: Message-ID: On 2007-07-05, Christoph Zwerschke wrote: > Neil Cerutti wrote: >> The documentation for BaseException contains something that might >> be relevant: >> >> [...] If more data needs to be attached to the exception, >> attach it through arbitrary attributes on the instance. All >> >> Users could get at the extra info you attached, but it wouldn't >> be automatically displayed by the interpreter. > > Yes, that's the problem here. It wouldn't be displayed > automatically and the users must be aware of this attribute. > I'd like to have a more transparent solution. You ought to be able to use the third arg of raise to raise a new exception as if it were from the previous location, but now with a new message. You may need the traceback module to get at the error message, if trying to read e.message can fail. Something like this mess here: ;) ... except Exception, e: etype, evalue, etb = sys.exc_info() ex = traceback.format_exception_only(etype, evalue) message = ex[0].partition(':')[2].strip() raise etype, message+". Sorry!", etb Note that the above will break for SyntaxError (who's message contains more than one line) and any kind of exception that doesn't inherit from Exception. You might need some crufty try, finally to avoid having a circular reference hang around, according to the docs for sys.exc_info. -- Neil Cerutti From deets at nospam.web.de Wed Jul 11 05:31:46 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 11 Jul 2007 11:31:46 +0200 Subject: Visualizing a wav file? References: <46948baa$0$79693$dbd41001@news.wanadoo.nl> Message-ID: <5fjmc2F3d3qsqU1@mid.uni-berlin.de> kaens wrote: > On 7/11/07, Wim Vogelaar > wrote: >> Perhaps you can use parts/routines of Audacity. >> See: http://en.wikipedia.org/wiki/Audacity >> >> Wim Vogelaar, http://home.wanadoo.nl/w.h.vogelaar/ >> >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> > > I'm aware of audacity. > > Correct me if I'm wrong, but I don't think Audacity is written in > Python, although I think someone wrote a way to script it a bit using > python. > > While looking at their code might prove useful to me, I'm looking for > a way to implement this in python. > > To provide a clearer (and audacity related) example, I'd like to be > able to show the waveform as it's playing - like if you zoomed in > decently far on a sample in audacity while playing it back. If I can > accomplish that, I think I can figure out most of the other stuff I'd > like to do on my own. > > Just looking for some points in the right direction. For the visualization, you'll need a GUI-toolkit. Google this group for a plethora of discussions which are available and the respective advantages/disadvantages. The main problem will be the synchronization between the playing-process and your display. I have no idea if there is any feedback from the sound system that you can faciliate to compute the actual playing position. diez From enleverlesX.XmcX at XmclaveauX.com Thu Jul 5 01:39:57 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Thu, 5 Jul 2007 07:39:57 +0200 Subject: IDEs for COM scripting: C# v. Python v. Iron Python v. JPython References: Message-ID: <468c844b$0$27401$ba4acef3@news.orange.fr> Hi! >I love the typing assist I get when using C# in VS2005 to write COM >clients. But this run only for static-COM-servers. Dynamic-COM-servers are not supported by these assists. And, all COM-servers builds with Python are dynamic-COM-server. And also, dynamic-COM-server is a marvelous way for developpment. @-salutations Michel Claveau PS : C# can use dynamic COM servers, with "late binding" From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jul 18 03:53:05 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 18 Jul 2007 09:53:05 +0200 Subject: a=0100; print a ; 64 how to reverse this? In-Reply-To: <1184705018.586170.59080@g12g2000prg.googlegroups.com> References: <1184670575.205759.115360@i13g2000prf.googlegroups.com> <469cb76f$0$7584$426a34cc@news.free.fr> <1184705018.586170.59080@g12g2000prg.googlegroups.com> Message-ID: <469dc6d6$0$27893$426a74cc@news.free.fr> Karthik Gurusamy a ?crit : > On Jul 17, 5:35 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> mosi a ?crit : >> >> >> >>> Problem: >>> how to get binary from integer and vice versa? >>> The simplest way I know is: >>> a = 0100 >>> a >>> 64 >>> but: >>> a = 100 (I want binary number) >>> does not work that way. >>> a.__hex__ exists >>> a.__oct__ exists >>> but where is a.__bin__ ??? >>> What`s the simplest way to do this? (snip) >> >>> a = int('100', 2) >> >>> a >> 4 (snip) > While it's interesting to know we can go from binary to int, the OP > wanted the other way. Please reread more carefully the OP's question and code snippet (which are just above). From bdesth.quelquechose at free.quelquepart.fr Sun Jul 22 19:17:21 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 23 Jul 2007 01:17:21 +0200 Subject: Reading files, splitting on a delimiter and newlines. In-Reply-To: <1185407770.462158.57490@z24g2000prh.googlegroups.com> References: <1185378363.166434.172190@r34g2000hsd.googlegroups.com> <1185407770.462158.57490@z24g2000prh.googlegroups.com> Message-ID: <46a9018a$0$29037$426a74cc@news.free.fr> attn.steven.kuo at gmail.com a ?crit : > On Jul 25, 8:46 am, chris... at gmail.com wrote: > >>Hello, >> >>I have a situation where I have a file that contains text similar to: >> >>myValue1 = contents of value1 >>myValue2 = contents of value2 but >> with a new line here >>myValue3 = contents of value3 >> >>My first approach was to open the file, use readlines to split the >>lines on the "=" delimiter into a key/value pair (to be stored in a >>dict). >> >>After processing a couple files I noticed its possible that a newline >>can be present in the value as shown in myValue2. >> >>In this case its not an option to say remove the newlines if its a >>"multi line" value as the value data needs to stay intact. >> >>I'm a bit confused as how to go about getting this to work. >> >>Any suggestions on an approach would be greatly appreciated! > > > > > Check the length of the list returned from split; this allows > your to append to the previously extracted value if need be. > > import StringIO > import pprint > > buf = """\ > myValue1 = contents of value1 > myValue2 = contents of value2 but > with a new line here > myValue3 = contents of value3 > """ > > mockfile = StringIO.StringIO(buf) > > record=dict() > > for line in mockfile: > kvpair = line.split('=', 2) You want : kvpair = line.split('=', 1) >>> toto = "x = 42 = 33" >>> toto.split('=', 2) ['x ', ' 42 ', ' 33'] > if len(kvpair) == 2: > key, value = kvpair > record[key] = value > else: > record[key] += line Also, this won't handle the case where the first line doesn't contain an '=' (NameError, name 'key' is not defined) From sjmachin at lexicon.net Sun Jul 15 00:28:48 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 14 Jul 2007 21:28:48 -0700 Subject: CSV without first line? In-Reply-To: References: Message-ID: <1184473728.675046.149640@m37g2000prh.googlegroups.com> On Jul 15, 1:30 pm, "Sebastian Bassi" wrote: > Hi, > > In my CSV file, the first line has the name of the variables. So the > data I want to parse resides from line 2 up to the end. Here is what I > do: > > import csv > lines=csv.reader(open("MYFILE")) > lines.next() #this is just to avoid the first line > for line in lines: > DATA PARSING > > This works fine. But I don't like to do "lines.next()" just to get rid > of the first line. So I wonder if the reader function on the csv > module has something that could let me parse the file from the second > line (w/o doing that lines.next()). > Why do you wonder, instead of looking in the manual? From gh at gregor-horvath.com Thu Jul 5 07:24:33 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Thu, 05 Jul 2007 13:24:33 +0200 Subject: The best platform and editor for Python In-Reply-To: <1183627699.941481.92660@g4g2000hsf.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183627699.941481.92660@g4g2000hsf.googlegroups.com> Message-ID: <44fc5$468cd4f1$547078de$24824@news.chello.at> kimiraikkonen schrieb: > My another aim is: Can i develop graphical applications (like in > Windows) which contain menus, interactive dialog boxes etc. using > Ptyhon? > > I got it quite but not sure. I don't know Ptyhon's capability skills > for creating interactive softwares like in Windows's created by C++ or > Delphi. > have a look at Dabo http://www.dabodev.com/ Gregor From deets at nospam.web.de Tue Jul 17 03:01:36 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 17 Jul 2007 09:01:36 +0200 Subject: Is it possible to run two "while 1:" loops in two threadings respectively? In-Reply-To: <1184648352.400425.322440@e9g2000prf.googlegroups.com> References: <1184648352.400425.322440@e9g2000prf.googlegroups.com> Message-ID: <5g37qmF3earqjU1@mid.uni-berlin.de> zxo102 schrieb: > Hi, > I would like to combine two python applications into a single one > with two threadings. Both of them have a "while 1:" loop respectively. > For example, one application is to monitoring serial port 'com1' and > another application is a TCP/IP server which has used threadings > already. I write the following demo code but it does not work right. > It stays in the first "while 1:" and never thingOne.start(). The > second threading never be started. > Any ideas? > > Thanks a lot. > > Ouyang > ################################################################# > import threading, time > class serial_port_com1: > def spc(self): > i = 0 > while 1: > time.sleep(5) > print "%d: hello, I am here in spc()"%i > i += 1 > > class TCP_IP: > def tcpip(self): > i = 0 > while 1: > time.sleep(5) > print "%d: hello, I am here in tcpip()"%i > i += 1 > > class ThreadOne ( threading.Thread ): > def run ( self ): > print 'Thread', self.getName(), 'started.' > time.sleep ( 5 ) > print 'Thread', self.getName(), 'ended.' > > class ThreadTwo ( threading.Thread ): > def run ( self ): > print 'Thread', self.getName(), 'started.' > thingOne.join() > print 'Thread', self.getName(), 'ended.' > > if __name__=="__main__": > spc = serial_port_com1() > tcpip = TCP_IP() > thingOne = ThreadOne(target=spc.spc()) > thingOne.start() > thingTwo = ThreadTwo(target=tcpip.tcpip()) > thingTwo.start() > There are several problems here. First of all, one either subclasses Thread and implements run - then your code should look like this: class ThreadTwo(Thread): def run(self): tcpip.tcpip() Or you don't subclass Thread and pass a target. But that target must be a function. You don't pass a function, you call it!! Look at this: Thread(target=tcpip.tcpip) Note the missing parentheses! Apart from that, you should seriously consider applying a consistent naming style to your code. Diez From steve at holdenweb.com Wed Jul 25 12:32:45 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Jul 2007 12:32:45 -0400 Subject: wxGlade: Who knows how to drive this application? Message-ID: I've been trying to use wxGlade recently and I am finding it something of a challenge. Is there any user who finds the user interface satisfactory and the operation of the program predictable? If so I would love to hear from 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 steve at REMOVE.THIS.cybersource.com.au Wed Jul 25 21:21:22 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 26 Jul 2007 11:21:22 +1000 Subject: Flatten a list/tuple and Call a function with tuples References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> Message-ID: On Wed, 25 Jul 2007 15:46:58 +0000, beginner wrote: > I know the * operator. However, a 'partial unpack' does not seem to > work. > > def g(): > return (1,2) > > def f(a,b,c): > return a+b+c > > f(*g(),10) will return an error. No it doesn't, it _raises_ an exception. This is a function that returns an error: def function(): """Returns an error.""" return Error() # defined elsewhere But to answer your question: > Do you know how to get that to work? It's a little bit messy, but this works: >>> f(*(g() + (10,))) 13 This is probably easier to read: >>> t = g() + (10,); f(*t) 13 -- Steven. From horpner at yahoo.com Wed Jul 25 07:26:32 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 25 Jul 2007 11:26:32 GMT Subject: classmethod & staticmethod References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> <46a5b2ad$0$18903$426a74cc@news.free.fr> Message-ID: On 2007-07-25, Alex Popescu wrote: > Neil Cerutti wrote in news:eRwpi.36813$G23.28496 > @newsreading01.news.tds.net: > >> On 2007-07-25, Alex Popescu wrote: >>> As a matter of style, how do you figure out that class_list is >>> a class attribute and not an instance attribute? (I don't >>> remember seeing anything in the PEP describing the coding >>> style). >> >> Check out dir(MyClass) and dir(MyClass()) for some insight, if it >> turns out that it matters. > > I must confess that I am a bit confused by this advise, as both > are returning exactly the same thing. Oops! I misthought myself. I was thinking of MyClass.__dict__.keys() and MyClass().__dict__.keys(). -- Neil Cerutti To succeed in the world it is not enough to be stupid, you must also be well- mannered. --Voltaire From bthate at gmail.com Mon Jul 9 02:35:08 2007 From: bthate at gmail.com (bthate) Date: Mon, 09 Jul 2007 06:35:08 -0000 Subject: ANN: gozerbot 0.7 released In-Reply-To: <1183962623.941986.109670@w3g2000hsg.googlegroups.com> References: <1183935992.848431.131890@r34g2000hsd.googlegroups.com> <87lkdqm9mc.fsf@benfinney.id.au> <1183962623.941986.109670@w3g2000hsg.googlegroups.com> Message-ID: <1183962908.169397.197290@22g2000hsm.googlegroups.com> here is the about: gozerbot is a Python IRC and Jabber bot Requirements * a shell * python 2.4 or higher * if you want to remotely install plugins: the gnupg module * if you want mysql support: the py-MySQLdb module * if you want jabber support: the xmpppy module Why gozerbot? * user management by userhost .. bot will not respond if it doesn't know you (see /docs/USER/) * fleet .. use more than one bot in a program (list of bots) (see / docs/FLEET/) * use the bot through dcc chat .. partyline * fetch rss feeds (see /docs/RSS/) * keep todo and shop lists * karma * quote * remember items * relaying between bots (see /docs/RELAY/) * program your own plugins (see /docs/PROGRAMPLUGIN/) * run the builtin webserver (see /docs/WEBSERVER/) * query other bots webserver via irc (see /docs/COLLECTIVE/) * other stuff From gagsl-py2 at yahoo.com.ar Mon Jul 23 03:18:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Jul 2007 04:18:59 -0300 Subject: problem with exec References: <1185099810.772825.284620@m3g2000hsh.googlegroups.com> <1185111419.177524.131870@d55g2000hsg.googlegroups.com> Message-ID: En Sun, 22 Jul 2007 10:36:59 -0300, escribi?: >> Since the application is transforming >> its input, it could transform braces into indentation. Of course >> *Python* >> doesn't use braces, but the question was how to write "pseudo-Python" >> without using indentation to indicate grouping. >> > This previously is exactly what I need can you help me somehow about > this > code > indentation, on any way you know.Plese help I will really appreciate > this!!!!!!!!!!!!!! If you are using the tokenize module as suggested some time ago, try to analyze the token sequence you get using { } (or perhaps begin/end pairs in your own language, that are easier to distinguish from a dictionary display) and the sequence you get from the "real" python code. Then write a script to transform one into another: from tokenize import generate_tokens from token import tok_name from cStringIO import StringIO def analyze(source): g = generate_tokens(StringIO(source).readline) for toknum, tokval, _, _, _ in g: print tok_name[toknum], repr(tokval) I think you basically will have to ignore INDENT, DEDENT, and replace NAME+"begin" with INDENT, NAME+"end" with DEDENT. -- Gabriel Genellina From KREUZRSK at DFW.WA.GOV Mon Jul 23 14:41:27 2007 From: KREUZRSK at DFW.WA.GOV (Randy Kreuziger) Date: Mon, 23 Jul 2007 11:41:27 -0700 Subject: Maintaining leading zeros with the lstrip string function? Message-ID: I need just the file name from a string containing the path to a file. The name of the file starts with zeros. This is problematic because the lstrip function strips them leaving this as the result: 6128.jpg How do I strip the path without losing the leading zeros in the file name? ?--------------------------------------------- import sys, os, win32com.client, string teststring = 'C:\shoreline\dvd\prep area\800x\\006128.jpg' print string.lstrip(teststring, 'C:\shoreline\dvd\prep area\800x\\') -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Fri Jul 13 05:02:44 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 13 Jul 2007 11:02:44 +0200 Subject: Class decorators do not inherit properly In-Reply-To: References: Message-ID: <5fotdnF3cvoc2U1@mid.uni-berlin.de> Chris Fonnesbeck schrieb: > I have a class that does MCMC sampling (Python 2.5) that uses decorators > -- one in particular called _add_to_post that appends the output of the > decorated method to a class attribute. However, when I > subclass this base class, the decorator no longer works: > > Traceback (most recent call last): > File "/Users/chris/Projects/CMR/closed.py", line 132, in > class M0(MetropolisHastings): > File "/Users/chris/Projects/CMR/closed.py", line 173, in M0 > @_add_to_post > NameError: name '_add_to_post' is not defined > > yet, when I look at the dict of the subclass (here called M0), I see the > decorator method: > > In [5]: dir(M0) > Out[5]: > ['__call__', > '__doc__', > '__init__', > '__module__', > '_add_to_post', > ... > > I dont see what the problem is here -- perhaps someone could shed > some light. I thought it might be the underscore preceding the name, > but I tried getting rid of it and that did not help. Does this simple example show your problem? class Meta(type): def __init__(cls, *args): print "Meta.__init__ called" return super(Meta, cls).__init__(*args) class A(object): __metaclass__ = Meta def decorator(f): print "decorator called" return f @decorator def foo(self): pass class B(A): #@decorator def bar(self): pass print dir(A()) print dir(B()) then it explains the problem easily: the class-statement (class Name(base): <003201c7ba21$8c77ff70$a567fe50$@com> <468585BB.8090800@v.loewis.de> Message-ID: On Fri, 29 Jun 2007 21:15:00 -0600, William Heymann wrote: > On Friday 29 June 2007, Martin v. L?wis wrote: >> > There was no need for me to use 64 so I have switched back to 32 and >> > works fine. >> > >> > Python is not ready for the 64 world yet ;) >> >> It's a matter of standpoint. 64 bit is not ready for the world, yet. > > I think you mean 64bit windows. 64bit linux has been working great. Put differently: when everybody has a C compiler and the C source code for things tends to be available, any change to the CPU architecture is mostly painless. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From aahz at pythoncraft.com Sat Jul 21 09:26:31 2007 From: aahz at pythoncraft.com (Aahz) Date: 21 Jul 2007 06:26:31 -0700 Subject: class C: vs class C(object): References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> <469f1557$0$26759$426a74cc@news.free.fr> <46a082ed$0$431$426a74cc@news.free.fr> Message-ID: In article <46a082ed$0$431$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: >Aahz a ?crit : >> In article <469f1557$0$26759$426a74cc at news.free.fr>, >> Bruno Desthuilliers wrote: >>> >>> To make a long story short: Python 2.2 introduced a new object model >>> which is more coherent and more powerful than the original one. The old >>> one was kept so far for compatibility reasons, but there's absolutely no >>> reason to use it no more since "new-style" classes can do anything >>> "Classic" classes did and much more. IOW, don't even bother with >>> old-style classes. >> >> And I'll make my usual knee-jerk response disagreeing with this. For >> more info, search groups.google.com. > >And you'll still make it harder for newcomers to understand why a lot of >things don't work correctly with their classes. How helpful... Enh. *All* of the standard Python documentation currently starts with teaching classic classes, so it seems to me that this comment in fact points toward difficulty understanding why things don't work correctly in new-style classes. >Aahz, the object model switch happened *years* ago, and it's quite >clear that old style classes have been kept so far for compatibility >reasons only. It's obvious that one doesn't gain *anything* - except >compat with years-old pre-2.2 versions of Python - using old-style >classes. So *why* on earth are you still *advocating* the use of old >style classes ?????? Saying that I'm "advocating" the use of old-style classes is not precisely correct. The simple fact is that you are wrong about the switch having happened already. There is almost no basic documentation that starts with new-style classes; the vast majority of the Python Standard Library still uses classic classes; there is no requirement in PEP8 that new code for adding into Python 2.x use new-style classes. Moreover, there are still plenty of people (me included) who use Python 2.2 for production purposes, and because of the small but critical differences between new-style classes in 2.2 and 2.3+, I cannot recommend new-style classes for anyone who has not switched to using only 2.3+. (For that matter, there are still people using 2.1 and earlier, which is why some developers such as Fredrik Lundh still support all the way back to 1.5.2.) *YOU* are the one confusing people by your dogmatic insistance that classic classes should be ignored. Grow up. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I support the RKAB From info at fabis-site.net Tue Jul 17 13:43:45 2007 From: info at fabis-site.net (Fabian Steiner) Date: Tue, 17 Jul 2007 19:43:45 +0200 Subject: chmod directories recursively References: <469CF0C4.3020808@unm.edu> Message-ID: Jennifer Thacher wrote: > Fabian Steiner wrote: >> As far as I can see os.chmod() doesn't adjust permissions on directories >> recusively. Is there any other possibility to achieve this aim except for >> calling os.system('chmod -R /dir') directly? >> >> Thanks, >> Fabian > > Check out os.path.walk. Thanks for your advice. This pointed me into the right direction. For those who are interested the function passed to os.path.walk looks like this: def _chownRecursive(arg, dirname, fnames): os.chown(dirname, arg[0], arg[1]) for file in fnames: os.chown(os.path.join(dirname, file), arg[0], arg[1]) Fabian From gagsl-py2 at yahoo.com.ar Wed Jul 11 20:14:58 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Jul 2007 21:14:58 -0300 Subject: 2**2**2**2**2 wrong? Bug? References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> <1184173446.779276.250530@k79g2000hse.googlegroups.com> <1184182757.797808.206480@d55g2000hsg.googlegroups.com> Message-ID: En Wed, 11 Jul 2007 16:39:17 -0300, Paul McGuire escribi?: > As was > pointed out earlier, left-associativity with exponentiation is of > little value, since (2**3)**2 is the same as 2**(3*2) or 2**6=64. Just for curiosity: This helps to find the answer to the problem "Which is the largest number that can be written with only 3 digits?" Some people stop at 999, others try 99**9 and 9**99, and the winner is 9**9**9, or: | 9 | 9 | 9 Sorry, couldn't resist. -- Gabriel Genellina From thomas at jollans.com Thu Jul 5 12:17:55 2007 From: thomas at jollans.com (Thomas Jollans) Date: Thu, 5 Jul 2007 18:17:55 +0200 Subject: Chat programs In-Reply-To: <1183638132.939925.43350@x35g2000prf.googlegroups.com> References: <1183638132.939925.43350@x35g2000prf.googlegroups.com> Message-ID: <200707051817.59558.thomas@jollans.com> On Thursday 05 July 2007, HangZhou Monty Boy wrote: > I'd like to think of building a chat program, could you advise me if > python is good enough for people to get all of my source code ? I'm not sure what the language you use has to do with how people acquire your source code, but (remember: this is a python list) I think python is a brilliant language for many things, including building chat programs [1] ;-) [1]: http://zombiehq.xyzplanet.net/zhq/projects/chat this really needs an update... like automatic client discovery etc... -- 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 nospam at nospam.com Thu Jul 19 21:43:41 2007 From: nospam at nospam.com (Gilles Ganault) Date: Fri, 20 Jul 2007 03:43:41 +0200 Subject: [2.5] Script to POST to web page with cookies? Message-ID: Hello I need to write a script to automate fetching data from a web site: 1. using the POST method, log on, with login/password saved as cookies 2. download page and extract relevent information using regexes 3. log off 4. wait for a random number of minutes, and GOTO 1 I'm a bit confused with how to get POST and cookies in the same script: - urllib vs urllib2 vs httplib? - "ClientCookie.urlopen("www") behaves identically to urllib2.urlopen, except that it deals with cookies automatically" Has anyone some working code that I could borrow (er... steal) to do this? Thank you. From robinsiebler at gmail.com Thu Jul 12 16:15:17 2007 From: robinsiebler at gmail.com (robinsiebler at gmail.com) Date: Thu, 12 Jul 2007 13:15:17 -0700 Subject: Best way to add values from keys Message-ID: <1184271317.992321.6810@r34g2000hsd.googlegroups.com> I have a data structure that looks like this: dates = {}; last_song = [] #; year = {}; week = {}; date = {}; artist = []; song = {} # dates = {'2007': {'25': {'06/23/07': {'aerosmith': [{'sweet emotion': 1}, {'dream on': 2}], # 'Metallica': [{'Fade to Black': 1}, {'Master of Puppets': 1}]}, # 'last_song': [Master of Puppets', 'Fade to Black', 'sweet emotion']}}} What is the most effecient way to go through a week and determine how many times each song was played? From saint.infidel at gmail.com Tue Jul 3 14:04:18 2007 From: saint.infidel at gmail.com (infidel) Date: Tue, 03 Jul 2007 11:04:18 -0700 Subject: Help building GUI with Tix Message-ID: <1183485858.701630.289830@d30g2000prg.googlegroups.com> I am trying to build a GUI using the Tix module. What I want is a paned window with a tree in the left pane and a notebook in the right pane. I keep getting an error that I don't understand when adding these widgets to the panes: PythonWin 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> import Tix >>> app = Tix.Tk("Demo") >>> panes = Tix.PanedWindow(app) >>> panes.pack(fill=Tix.BOTH, expand=True) >>> tree = Tix.Tree(panes) >>> panes.add(tree) Traceback (most recent call last): File "", line 1, in File "C:\Program Files\Python25\lib\lib-tk\Tix.py", line 1220, in add self.tk.call(self._w, 'add', name, *self._options(cnf, kw)) TclError: bad window path name ".16442432..16442432" >>> What am I missing? TIA From wbrehaut at mcsnet.ca Sun Jul 15 17:28:14 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Sun, 15 Jul 2007 15:28:14 -0600 Subject: 2**2**2**2**2 wrong? Bug? References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> <1184351416.166930.290710@k79g2000hse.googlegroups.com> <1184362323.476796.22570@w3g2000hsg.googlegroups.com> Message-ID: On Fri, 13 Jul 2007 14:32:03 -0700, "mensanator at aol.com" wrote: >On Jul 13, 2:52 pm, Wayne Brehaut wrote: >> On Fri, 13 Jul 2007 11:30:16 -0700, Paul McGuire >> wrote: >> >> >> >> >> >> >On Jul 13, 1:20 pm, Wayne Brehaut wrote: >> >> On Mon, 09 Jul 2007 23:51:25 -0700, "mensana... at aol.com" >> >> >> wrote: >> >> >On Jul 9, 11:42?pm, Paul McGuire wrote: >> >> >> On Jul 9, 11:21 pm, "Jim Langston" wrote:> In Python 2.5 on intel, the statement >> >> >> > 2**2**2**2**2 >> >> >> > evaluates to>>> 2**2**2**2**2 === 8< === >> >> >Did you count the 'L'? >> >> >> numdigits(n)? >> >> >> What? 'L' is a digit in Python? I'm going back to Fortran! >> >> >> wwwayne === 8< === >> >'L' counts for 50, but only when you use Roman font. >> >> WTL?! Not Times New Roman I hope? >> >> Now I'll have to extend my remarks below to include: >> >> L**L**L >> D**D**D >> M**M**M >> etc. (since I don't recall what comes next) >> >> though these (L, D, M, ...) would seem to be numbers rather than >> digits: the Romans used a base-1 system > >No, "base" refers to a Positional Number system for which >radix 1 is undefined. > >You can call Roman Numerals a Tally System of Radix 1. I can call it what I want--within reason--so long as those I'm mainly addressing understand what I mean and the context in which I'm saying it. As I note in my other response to your response below, my remark was intended to be humorous, and everyone else who responded took it that way. There's no need to get all formal in such a context, and there's no harm in defining a tally system to be 1-based or to be a base-1 system. If I had intended this to be a formal discussion instead of just having a little fun (and sorry for doing that) I would have instead said: "Define a base-1 number system as...". Since you clearly don;t want to accept my terminology and assume there's just one right one, please see http://www.psinvention.com/zoetic/basenumb.htm for an independent opinion of the reasonableness of using this term: "Base Valued Numbers Any use of numbers implies the use of a base value for the numbers. The simplest base value to use in a numbering scheme is '1'." Because we're most familiar with the use of the term "base" in the context of positional notation in no way implies that's the only possible context in which it can be used--or has been used--with perfectly clear meaning. So the Roman system was based on the number 1 and was, therefore, 1-based or base-1. Even in the context of positional systems it's perfectly clear what a base-1 system would be and the fact that it's generally excluded isn;t because it's not cleaar what it weould be, but only that most assume it isn't of any uise, so exclude it. As we all know: 1^0 = 1 1^1 = 1 1^n = 1 for any positive natural number [and negative natural numbers don't exist, but extension to negative integers is left as an exercise for the reader] In the base 1 positional number system, what is the value of: 1 11 111 1...1 (with n 1s)? And would the value be any different if I wrote them: 1 11 111 1...1 (with n 1s)? In pictures: Pos? ? Value 1 Digit 1 Pos? ? ? Value 1 1 Digit 1 1 Pos? ? ? ? Value 1 1 1 Digit 1 1 1 Pos? ? ... ? Value 1 ... 1 (n positions) Digit 1 ... 1 (n 1s) >Tally sytems ARE defined for radix 1, but operate >completely different from positional systems. Clearly, the algorithm to find the value of a base-1 number is to multiply the value of each position (1) by the digit in that position (1) and add the results--just as you would do for any other positional system. One common assumption for excluding base-1 is that this can't be a proper positional number system because there's no zero digit, so how can we represent the 0 value of a position? The obvious answer is that there is no way of knowing what power of 1 each position represents anyway, since the value of each and every position is 1, so we just leave out positions whose value is zero; equivalently, we just admit that the base-1 tally system is equivalent to the base-1 positional system so far as counting is concerned, since we don't count things that aren't there. I claim this demonstrates that your statement is incorrect: so far as counting or representing a count is concerned the base-1 tally system is the base-1 positional system, and is the base-1 system I claim Roman numerals represent using various shorthand symbols and rules (like subtracting the value of lesser-valued symbols when immediately to the left of a higher-valued one--and this is a loose description, so please don't look for counter-examples to prove me wrong here too). Of course, by "operate completely different from positional systems" you may have meant that when you go beyond counting to operations on and between such numbers the usual rules and algorithms of positional systems don't apply--but what has that to do with counting the number of digits in a number respresented in this base-1 system? An arithmetic on numbers (whether written using a positional system or not) is a completely different animal than the base set of objects themselves, and doesn't alter the fact of whether the numbers are or aren't written in a positional notation! And the p-adic numbers (http://en.wikipedia.org/wiki/P-adic_number) also use a positional notation, but don't follow what you would probably regard as "the only true rules and algorithms" of a positional notation; so there's no such thing as "_the_ positional notation". But I digress (but only because provoked!)... >> [for purposes of this argument, at least] This statement is the informal equivalent to saying "Define a base-1 number system as...", as I noted above. If you'd noted this, and understood it, or were willing to accept it whether or not you understood it, you'd have saved us both some bother--but me more than you I guess, so maybe you were just trolling? wwwayne >> so I is the only Roman digit* and the others are >> just shorthand for: >> >> I = 1 >> V = IIIII >> X = I*10 >> L = I*50 >> D = I*500 >> M = I*1000 >> etc. >> >> --- >> For those who don't know which Roman digit I represents: >> >> | >> _\|/__ >> >> wwwayne >> >> >> >> >> >> >-- Paul From zyzhu2000 at gmail.com Wed Jul 25 21:01:40 2007 From: zyzhu2000 at gmail.com (beginner) Date: Thu, 26 Jul 2007 01:01:40 -0000 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <46a778e8$0$8323$9b622d9e@news.freenet.de> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <46a778e8$0$8323$9b622d9e@news.freenet.de> Message-ID: <1185411700.095077.58320@i13g2000prf.googlegroups.com> > Well, there are several ways to solve this. You could either invoke f(*g > () + (10,)). Might be a bit nasty and unreadable, though. Or you could > just change your function f to accept them in reversed order (f(10, *g) > should work) or convert g() to return a dictionary like {'b': 1, 'c': 2} > and use f(10, **g). But if your function f's hugest use case is being > called with g(), changing f to accept something and g's result (tuple) -- > unpacking it inside f -- might be better.- Hide quoted text - > > - Show quoted text - These all work. Thanks. From ajaksu at gmail.com Sat Jul 21 22:13:20 2007 From: ajaksu at gmail.com (ajaksu) Date: Sun, 22 Jul 2007 02:13:20 -0000 Subject: pyodbc on linux In-Reply-To: <1185051273.979145.285050@22g2000hsm.googlegroups.com> References: <1185051273.979145.285050@22g2000hsm.googlegroups.com> Message-ID: <1185070400.697048.124540@q75g2000hsh.googlegroups.com> On Jul 21, 5:54 pm, Sean Davis wrote: > I have read a couple of blogs suggesting that pyodbc is buildable > under linux. It is, following these wise words: "Aargghh! I see that possibly there was a typo in cursor.cpp at line 1385: Py_UNICODE* pNull = (Py_UNICODE*)wmemchr(pT, 0, cch) should be Py_UNICODE* pNull = (Py_UNICODE*)memchr(pT, 0, cch) Anyway, uncommented what I had commented out and changed the wmemchr to wmemchr and everything compiled." >From http://sourceforge.net/tracker/index.php?func=detail&aid=1731205&group_id=162557&atid=824254 (I just did it a few hours ago, quite a coincidence :)) HTH, Daniel From jscrerar at compuserve.com Mon Jul 30 13:04:48 2007 From: jscrerar at compuserve.com (Jim) Date: Mon, 30 Jul 2007 10:04:48 -0700 Subject: Making Gridded Widgets Expandable In-Reply-To: References: <1185803688.860152.54210@x40g2000prg.googlegroups.com> Message-ID: <1185815088.040935.87080@x40g2000prg.googlegroups.com> On Jul 30, 8:24 am, "Hamilton, William " wrote: > > From: Jim > > Hi, > > I'm looking at page 548 of Programming Python (3rd Edition) by Mark > > Lutz. > > The following GUI script works with no problem, i.e., the rows and > > columns expand: > > ================================================================= > > # Gridded Widgets Expandable page 548 > > > from Tkinter import * > > colors = ["red", "white", "blue"] > > > def gridbox(root): > > Label(root, text = 'Grid').grid(columnspan = 2) > > r = 1 > > for c in colors: > > l = Label(root, text=c, relief=RIDGE, width=25) > > e = Entry(root, bg=c, relief=SUNKEN, width=50) > > l.grid(row=r, column=0, sticky=NSEW) > > e.grid(row=r, column=1, sticky=NSEW) > > root.rowconfigure(r, weight=1) > > r += 1 > > root.columnconfigure(0, weight=1) > > root.columnconfigure(1, weight=1) > > > root = Tk() > > gridbox(Toplevel(root)) > > Button(root, text="Quit", command=root.quit).grid() > > mainloop() > > ================================================================= > > However, the following GUI script using class does not expand rows and > > columns: > > ================================================================= > > # Gridded Widgets Expandable 2 > > > from Tkinter import * > > colors = ["red", "white", "blue"] > > > class GUI(Frame): > > def __init__(self,master): > > Frame.__init__(self,master) > > self.grid() > > self.gridbox() > > > def gridbox(self): > > Label(self, text = 'Grid').grid(columnspan = 2) > > r = 1 > > for c in colors: > > l = Label(self, text=c, relief=RIDGE, width=25) > > e = Entry(self, bg=c, relief=SUNKEN, width=50) > > l.grid(row=r, column=0, sticky=NSEW) > > e.grid(row=r, column=1, sticky=NSEW) > > self.rowconfigure(r, weight=1) > > r += 1 > > self.columnconfigure(0, weight=1) > > self.columnconfigure(1, weight=1) > > > root = Tk() > > root.title("Gridded Widgets Expandable") > > app = GUI(root) > > Button(root, text="Quit", command=root.quit).grid() > > root.mainloop() > > ================================================================= > > What am I missing? > > In the first, your gridbox has Toplevel(root) as its master, causing it > to be created in a new window. In the second, it has Frame(root) as its > master, which does not create a new window. Changing Frame to Toplevel > in the class statement and the call to __init__ causes them to act > identically. > > -- > -Bill Hamilton- Hide quoted text - > > - Show quoted text - Thank you Bill Hamilton. From alexander.somma at gmail.com Sun Jul 8 19:43:14 2007 From: alexander.somma at gmail.com (lex) Date: Sun, 08 Jul 2007 23:43:14 -0000 Subject: What is the most efficient way to test for False in a list? Message-ID: <1183938194.761283.97950@57g2000hsv.googlegroups.com> Of course there is the always the iteration method: list = [1, True, True, False, False, True] status = True for each in list: status = status and each but what is your best way to test for for False in a list? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jul 18 03:40:10 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 18 Jul 2007 09:40:10 +0200 Subject: accessing javascript variables within psp code In-Reply-To: <1184722167.222423.273040@z28g2000prd.googlegroups.com> References: <1184722167.222423.273040@z28g2000prd.googlegroups.com> Message-ID: <469dc3cf$0$8399$426a74cc@news.free.fr> BAnderton a ?crit : > Hello all, > > Question: Is there any way to access a javascript variable from > within psp code? Short answer : no (or at least: not directly). And it has nothing to do with PSP. Long answer: this has to do with the http protocol. Things go like this: 1/ the client (usually the browser) send a request (via typing an url in the address bar, clicking a link, posting a form...) 2/ the server process the request (this is where your psp - or any other server-side - code is executed) and send back a response (in your case, what has been generated by the psp code). 3/ the client do something (usually: display) the response. This is where Javascript - if any, and if supported by the client - is executed. From the server's POV, once the response is sent, the transaction is finished. The only way to have client-side javascript communicate with the server is via the XmlHttpRequest object (IOW : ajax). This allow javascript code to send a request to a server without reloading the whole page. (snip) > > FYI, I've already found a workaround for the above example (by placing > a "get" variable in the URL, reloading the page, and having psp check > for the existence of that variable before proceeding with deleting the > appropriate file) Beware, GET request should *not* have such side-effects on the server. A GET request is meant - as the name implies - to get data from the server. Use a POST request instead. If you're going to do web development, reading the http RFC might be helpful... > but I'd still like this general capability for > future projects. Then you have to learn how to use XmlHttpRequest. > I've searched several forums, websites, etc. and > the > answer has aluded me for two days now. I'm new to apache, mod_python, > and javascript, so this may be ridiculously simple. > > Since this is my first post on google groups, Small correction : you're not posting "on" google groups, you're posting on usenet *from* google groups. Most people prefer to access usenet via a newsreader. > I'd also appreciate any > helpful suggestions on how to best go about getting answers quickly http://www.catb.org/~esr/faqs/smart-questions.html And remember that usenet is definitively not an help desk. No one get paid for answering your questions. HTH From steve at REMOVE.THIS.cybersource.com.au Mon Jul 30 07:59:48 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 30 Jul 2007 21:59:48 +1000 Subject: Pythonic way for missing dict keys References: <1185041243.323915.161230@x40g2000prg.googlegroups.com> <87lkd0eprj.fsf@pobox.com> Message-ID: On Mon, 30 Jul 2007 07:37:05 +0000, Duncan Booth wrote: > Steven D'Aprano wrote: > >> >> Instead of doing: >> >> >> if callable(function): function() >> >> you should do: >> >> try: >> function() >> except TypeError: >> pass >> >> >> 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_?) > > The replacement for callable(x) is simply hasattr(x, '__call__'). > Once upon a time it may have been that functions didn't have a __call__ > attribute (I haven't checked back on really old Pythons top see if this > was the case), but these Your sentence seems to have run out early :) Thanks, I didn't know that -- I remember that Back In The Day checking if something was callable was tricky, because it could be a function, a method, or a class with __call__. It makes much more sense to make all callables go through __call__. >>> 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(). > > There are of course several replacements for specialised uses of reduce: > sum, any, all. There is no general purpose replacement, but you can > write one in a few lines if you really need it. True. But writing the same basic algorithm over and over again is about as far from best practice as you can get without being a PHP programmer. *wink* Currying is easy to do too, but Python has grown a function functools.partial() to do it properly. That's as it should be. (Yes, I know that's a misuse of the term currying, but it's a common one, and easier than saying "Making a partial function".) >> It's a shame really. Oh well, maybe it will sneak back in via a >> functional module, or itertools, or something. What a waste, what a >> waste. > > I'm sure it will reappear in some other module, but that's the correct > place for a little used function, not in builtins. Oh, I would have no problem at all with reduce being banished to the functtools module. But it's a shame to have to go through the whole PEP process, and risk Guido saying no. -- Steven. From murali.dhanakoti at gmail.com Wed Jul 18 22:02:39 2007 From: murali.dhanakoti at gmail.com (Murali) Date: Thu, 19 Jul 2007 02:02:39 -0000 Subject: Interprocess communication woes Message-ID: <1184810559.180382.179220@j4g2000prf.googlegroups.com> Hi Python Gurus, I am writing a GUI app (on linux) using pygtk which would launch some external applications and display their stdout and stderr inside the output window of my application synchronously. I am using the subprocess module's Popen to launch the external programs and to capture their stdout and stderr. The problem is that, for some external programs that I launch inside my interface, I am not able to capture and display the stdout as the program *runs*. After some investigation, I found out that this problem had nothing to do with my GUI app not getting refreshed and I was able to reproduce this problem with normal python scripts. Here is one such script #File test.py from subprocess import Popen from subprocess import PIPE import sys if __name__ == '__main__': prog = sys.argv[1] proc = Popen(prog, shell = True, stdout = PIPE, bufsize = 0) out = proc.stdout while proc.poll() is None: print out.readline() Run this program as follows $ test.py "ping -c 10 www.google.com" Now, you would see the responses as if you just launched ping on the command line. Now, lets look at another program. Here is a simple C++ program that prints numbers 1 to 10 at the passage of every second (sort of a stopwatch) #include #include #include main ( ) { timeval t1, t2; gettimeofday(&t1, NULL); int prev = -1; int cur = 0; while (true) { gettimeofday(&t2,NULL); if(t2.tv_sec - t1.tv_sec > 10) break; else { cur = t2.tv_sec-t1.tv_sec; if (cur != prev) { printf("%d\r\n",cur); prev = cur; } } } } if you would build this program and call it lets say timer ($ g++ -o timer timer.cpp) and run it with our python script like this $python test.py "./timer" you would see that every time you run the program your results vary and on top of this the stdout of the timer program gets displayed all at once presumably when the timer program has completed execution. Why this discrepancy between the ping and timer programs? Is my test.py script correct? Is there a better or a preferred method for doing interprocess communication in Python. Thanks! Murali. From software at ginstrom.com Thu Jul 26 18:45:13 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Fri, 27 Jul 2007 07:45:13 +0900 Subject: From D In-Reply-To: <1185464361.542540.258800@19g2000hsx.googlegroups.com> References: <1185272393.484032.125180@22g2000hsm.googlegroups.com><46a6086d$0$8399$9b622d9e@news.freenet.de> <1185464361.542540.258800@19g2000hsx.googlegroups.com> Message-ID: <003101c7cfd6$a1621860$0203a8c0@MOUSE> > On Behalf Of Leo Petr > Digits are grouped in 2s in India and in 4s in China and Japan. This is not entirely true in Japan's case. When written without Japanese characters, Japan employs the same format as the US, for example: 1,000,000 (However, they would read this as ?? (hyaku man), literally 100 ten thousands.) Raymond is correct in that Japan traditionally groups in fours (and stills reads it that way regardless, as shown above), but in an ordinary programming context, this almost never comes into play. On the original topic of the thread, I personally like the underscore idea from D, and I like it better than the "concatenation" idea, even though I agree that it is more consistent with Python's string-format rules. Regards, Ryan Ginstrom From apatheticagnostic at gmail.com Wed Jul 11 02:05:04 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 11 Jul 2007 02:05:04 -0400 Subject: Visualizing a wav file? Message-ID: <163f0ce20707102305p7d3c5223r704c64a6f1aff773@mail.gmail.com> Hey everyone, I've done a good bit of google searching, and have found quite a few different libraries available for sound processing. I was wondering if anyone with more experience would like to say which one(s) they would use for displaying the waveform of a .wav file in real-time, or at least as the .wav is being played. Or is this something that would be better handled by the GUI code? Data from whatever's reading the sound, visualization by Tkinter or wx or whatnot? From dennis.varghese at wipro.com Fri Jul 20 11:10:28 2007 From: dennis.varghese at wipro.com (pycraze) Date: Fri, 20 Jul 2007 08:10:28 -0700 Subject: Need Help Message-ID: <1184944228.181886.183550@d30g2000prg.googlegroups.com> Hi , I am currently working on NTLM (Windows NT Lan Manager) APS (Authentication Proxy Server ) . NTLM is MS own proprietary protocol that will allow successful authentication for only MS browsers . NTLM APS was successfully cracked by Rosmanov and i am working on NTLM APS python package version 0.98 . I am currently on it to port to C language . From kyosohma at gmail.com Mon Jul 9 16:18:42 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 09 Jul 2007 13:18:42 -0700 Subject: dealing with nested xml within nested xml within...... In-Reply-To: <1184011424.662766.176530@k79g2000hse.googlegroups.com> References: <1184011424.662766.176530@k79g2000hse.googlegroups.com> Message-ID: <1184012322.363949.306330@n60g2000hse.googlegroups.com> On Jul 9, 3:03 pm, Ultrus wrote: > Hello all, > I don't need specific examples, but I'm trying to wrap my head around > parsing xml within xml and even further, not limiting how far someone > will nest xml. I'm already making great use of BeautifulSoup's > BeautifulStoneSoup to parse xml, but what do I do if I come across > something like this? > > >

  • This is a random response (once parsed)
  • >
  • > >
  • This is a random response within a random response
  • >
  • > >
  • This is a random response within a random response, > within another random response
  • >
  • Like above, this is another random response.
  • > > > > > > > Not knowing how far one will nest random responses, how would one > manage digging into xml like this? Right now I'm thinking about not > even going there. I would presently write scripts that would parse 3 > or so levels deep, but no further. :P It would make an interesting > project, like an interactive adventure story. You'd probably write a function that called itself to parse something like this. Unfortunately, I am not a recursion expert. You can read up on it though: http://www.freenetpages.co.uk/hp/alan.gauld/tutrecur.htm http://pythonjournal.cognizor.com/pyj2.2/RecursionByAJChung.html I haven't used Beautiful Soup, but I think you can use lxml or ElementTree to get a tree object of the XML and then just iterate over the tree. Mike From pyscottishguy at hotmail.com Thu Jul 26 23:40:13 2007 From: pyscottishguy at hotmail.com (pyscottishguy at hotmail.com) Date: Fri, 27 Jul 2007 03:40:13 -0000 Subject: pyparser and recursion problem In-Reply-To: <1185504855.745706.241590@d55g2000hsg.googlegroups.com> References: <1185479408.520124.40670@k79g2000hse.googlegroups.com> <1185504855.745706.241590@d55g2000hsg.googlegroups.com> Message-ID: <1185507613.143993.175840@19g2000hsx.googlegroups.com> Hey, Thanks Neil and Paul! After reading Neil's advice I started playing around with the setParseAction method, and then I found Paul's script 'macroExpander.py' (http://pyparsing.wikispaces.com/space/showimage/ macroExpander.py). With only a few modifications to macroExpander.py (and reversing my string!) I had an almost complete answer of: first [second1_1 second1_2 | second2 | second3 ] [third1 third2 | [sixth1_1 sixth1_2 | sixth2 ] ] | fourth [fifth1 | [[eighth1 | eighth2] | seventh1]] I was in the process of tyding this up so that I could do an eval() to get the array when I saw Paul's answer (thanks!) Here is macroExpander.py with my minimal changes: #!/usr/bin/python from pyparsing import * # define the structure of a macro definition (the empty term is used # to advance to the next non-whitespace character) label = Suppress(":") + Word(alphas + "_").setResultsName("macro") + Suppress(":") values = restOfLine.setResultsName("value") macroDef = label + empty + values # define a placeholder for defined macros - initially nothing macroExpr = Forward() # global dictionary for macro definitions macros = {} # parse action for macro definitions def processMacroDefn(s,l,t): macroVal = macroExpander.transformString(t.value) macros[t.macro] = macroVal macroExpr << MatchFirst( map(Keyword,macros.keys()) ) # parse action to replace macro references with their respective definition def processMacroRef(s,l,t): return '[' + macros[t[0]] +']' # attach parse actions to expressions macroExpr.setParseAction(processMacroRef) macroDef.setParseAction(processMacroDefn) # define pattern for scanning through the input string macroExpander = macroExpr | macroDef # test macro substitution using transformString testString = """ :EIGHTH: eighth1 | eighth2 :SEVENTH: EIGHTH | seventh1 :SIXTH: sixth1_1 sixth1_2 | sixth2 :FIFTH: fifth1 | SEVENTH :THIRD: third1 third2 | SIXTH :SECOND: second1_1 second1_2 | second2 | second3 :Start: first SECOND THIRD | fourth FIFTH """ macroExpander.transformString(testString) print macros['Start'] From ask at me Tue Jul 3 08:15:49 2007 From: ask at me (alf) Date: Tue, 03 Jul 2007 07:15:49 -0500 Subject: what is wrong with that r"\" Message-ID: question without words: >>> r"\" File "", line 1 r"\" ^ SyntaxError: EOL while scanning single-quoted string >>> r"\ " '\\ ' From bsneddon at yahoo.com Sun Jul 8 13:53:54 2007 From: bsneddon at yahoo.com (bsneddon) Date: Sun, 08 Jul 2007 10:53:54 -0700 Subject: Pretty Printing Like Tidy for HTML In-Reply-To: <87ejjjlz4p.fsf@pobox.com> References: <1183833340.610662.197060@o11g2000prd.googlegroups.com> <87ejjjlz4p.fsf@pobox.com> Message-ID: <1183917234.730744.123410@n60g2000hse.googlegroups.com> On Jul 8, 10:59 am, j... at pobox.com (John J. Lee) wrote: > David writes: > > Is there a pretty printing utility for Python, something like Tidy for > > HTML? > > > That will change: > > > xp=self.uleft[0]+percentx*(self.xwidth) > > > To: > > > xp = self.uleft[0] + percentx * (self.xwidth) > > > And other formatting issues. > > Googled and found these; no idea if they're any good (latter is > commercial): > > http://cheeseshop.python.org/pypi/PythonTidy/1.11 > > http://python.softalizer.com/ > > See also: > > http://svn.python.org/view/python/trunk/Tools/scripts/reindent.py?vie... > > John I did this useing the BeautifulSoup module. Used it on XML created by msWord which had no formating was all on one line. >>> import BeautifulSoup >>> soupStr = open('c:/data/quotes.xml').read() >>> soup = BeautifulSoup.BeautifulSoup(soupStr) >>> pSoup = soup.prettify() >>> outFile = open('c:/data/quotesTidy.xml','w') >>> outFile.write(pSoup) >>> outFile.close() From rokadvertising at googlemail.com Wed Jul 4 08:47:28 2007 From: rokadvertising at googlemail.com (rokadvertising at googlemail.com) Date: Wed, 04 Jul 2007 05:47:28 -0700 Subject: issues with htmlparser.getpos In-Reply-To: References: <1183548847.515341.293540@q69g2000hsb.googlegroups.com> Message-ID: <1183553248.891042.324870@57g2000hsv.googlegroups.com> Steve, thanks for reply there are newlines present, it looks like the files in question are from a mac, (my text editor tells me they are UTF8 & use CR for marking newlines) Cheers From python at jayloden.com Sun Jul 8 22:23:34 2007 From: python at jayloden.com (Jay Loden) Date: Sun, 08 Jul 2007 22:23:34 -0400 Subject: How to Machine A python script execute Machine B python script? In-Reply-To: <1183945503.875939.292420@57g2000hsv.googlegroups.com> References: <1183945503.875939.292420@57g2000hsv.googlegroups.com> Message-ID: <46919C26.2030505@jayloden.com> If you're running on a UNIX platform, one option would be to use SSH to execute the command remotely. Otherwise, you could also use a client/server setup to have the two scripts communicate across the network and trigger actions etc. It may also be possible to remotely execute an application on Windows using the win32api extensions, but I haven't any idea how you'd go about that. Perhaps others can chime in with detailed information if you let us know what kind of platform you're on and what you're trying to accomplish. -Jay johnny wrote: > Anyone know how I can make Machine A python script execute a python > script on Machine B ? > From brotherjenos at gmail.com Fri Jul 20 01:29:37 2007 From: brotherjenos at gmail.com (Walker Lindley) Date: Thu, 19 Jul 2007 22:29:37 -0700 Subject: Pickled objects over the network In-Reply-To: References: Message-ID: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com> Right, I could use Pyro, but I don't need RPC, I just wanted an easy way to send objects across the network. I'm sure both Pyro and Yami can do that and I may end up using one of them. For the initial version pickle will work because we have the networking issues figured out with it, just not the security problem. So we may end up just sending strings back and forth that will let us fill out an object's member variables on the other end. It's much less cool, but it seems like it'd be more secure. -Walker On 7/19/07, Rustom Mody wrote: > > Irmen de Jong wrote > > In what way would Pyro be overkill where Yaml (also a module that you > need > > to install separately) wouldn't be? > > Sure they are the same to install and sure pyro can do the job (pyro > is a nice package). > > But I got the impression that the questioner wanted to do the > networking stuff himself at a low level (using sockets) and the data > management using some available library -- pickle. > > Since pickle has problems > -- does not interface well with networking > -- security issues > -- has an xml option that according to the docs is an order of magnitude > slower > > I thought I would point out yaml (with safe-load) which sits somewhere > inbetween the xml-pickle and the default pickle. > > I should also mention here that I find yaml is much more known and > used in the ruby and perl world than in the python world. This is > unfortunate considering that both ruby and perl have a traditional > syntax (begin end, { } etc ). On the other hand, python and yaml have > similar modern syntactic structures -- structure follows indentation > -- and are therefore well matched to each other. > > So in summary the 'competition' is not between yaml and pyro -- pyro > could easily have a pickle-using-yaml option -- but between yaml and > xml. > -- > http://mail.python.org/mailman/listinfo/python-list > -- 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: From samwyse at gmail.com Sat Jul 28 10:02:22 2007 From: samwyse at gmail.com (samwyse) Date: Sat, 28 Jul 2007 14:02:22 -0000 Subject: How to programmatically insert pages into MDI. In-Reply-To: <1185626816.422978.8290@57g2000hsv.googlegroups.com> References: <1185280597.184328.152920@k79g2000hse.googlegroups.com> <1185626816.422978.8290@57g2000hsv.googlegroups.com> Message-ID: <1185631342.809366.156610@i38g2000prf.googlegroups.com> On Jul 28, 7:46 am, fynali iladijas wrote: > On Jul 24, 4:36 pm, fynali iladijas wrote: > > > > > Hi, this query is regarding automating page insertions in Microsoft > > Document Imaging. > [...] > > > All help and advice will be most appreciated. > > > Thank you. > > > s|a fynali > > )-: > > -- > s|a fynali Perhaps you should post to a Microsoft-related newsgroup. This is the place for questions about the Python programming language, and the word "Python" didn't appear anywhere in your initial question. From ndbecker2 at gmail.com Fri Jul 27 19:52:34 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 27 Jul 2007 19:52:34 -0400 Subject: problem with change to exceptions References: Message-ID: Alex Popescu wrote: > Neal Becker wrote in > news:f8dspe$fm2$1 at sea.gmane.org: > >> import exceptions >> >> class nothing (exceptions.Exception): >> def __init__ (self, args=None): >> self.args = args >> >> if __name__ == "__main__": >> raise nothing >> >> Traceback (most recent call last): >> File "", line 1, in >> File "/usr/tmp/python-3143hDH", line 5, in __init__ >> self.args = args >> TypeError: 'NoneType' object is not iterable >> >> I'll have to say, I don't understand this error. >> > > You can pass to the exception: > a) a string (it will become the message) > b) a tuple of values (can it be a list also?) > > In your case there is no message, no values so args is NoneType. > Yes, args is None. So the assignment: self.args = args should set self.args to None. Nothing wrong there, and what has this got to do with NoneType being iterable? From nagle at animats.com Fri Jul 20 00:45:39 2007 From: nagle at animats.com (John Nagle) Date: Fri, 20 Jul 2007 04:45:39 GMT Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <7x8x9lwka9.fsf@ruckus.brouhaha.com> Message-ID: Juergen Erhard wrote: > On proving programs correct... from my CS study days I distinctly > remember thinking "sure, you can prove it correct, but you cannot do > actual useful stuff with it". We might have come a long way since > then (late 80s :P), but I don't hold out much hope (especially since > the halting problem does exist, and forever will). The halting problem only applies to systems with infinite memory. Proof of correctness is hard, requires extensive tool support, and increases software development costs. But it does work. Check out the "Spec#" effort at Microsoft for current work. Work continues in Europe on Extended Static Checking for Java, which was developed at DEC before DEC disappeared. John Nagle From bbxx789_05ss at yahoo.com Sun Jul 1 15:40:59 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 01 Jul 2007 12:40:59 -0700 Subject: unicode In-Reply-To: References: <1183267580.178435.265640@o61g2000hsh.googlegroups.com> Message-ID: <1183318859.305908.218960@w5g2000hsg.googlegroups.com> Erik Max Francis wrote: > 7stud wrote: > > > Based on this example and the error: > > > > ----- > > u_str = u"abc\u9999" > > print u_str > > > > UnicodeEncodeError: 'ascii' codec can't encode character u'\u9999' in > > position 3: ordinal not in range(128) > > ------ > > > > it looks like when I try to display the string, the ascii decoder > > parses each character in the string and fails when it can't convert a > > numerical code that is higher than 127 to a character, i.e. the > > character \u9999. > > If you try to print a Unicode string, then Python will attempt to first > encode it using the default encoding for that file. Here, it's apparent > the default encoding is 'ascii', so it attempts to encode it into ASCII, > which it can't do, hence the exception. The error is no different from > this: > > >>> u_str = u'abc\u9999' > >>> u_str.encode('ascii') > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\u9999' in > position 3: ordinal not in range(128) > > > In the following example, I use encode() to convert a unicode string > > to a regular string: > > > > ----- > > u_str = u"abc\u9999" > > reg_str = u_str.encode("utf-8") > > print repr(reg_str) > > ----- > > > > and the output is: > > > > 'abc\xe9\xa6\x99' > > > > 1) Why aren't the characters 'a', 'b', and 'c' in hex notation? It > > looks like python must be using the ascii decoder to parse the > > characters in the string again--with the result being python converts > > only the 1 byte numerical codes to characters. 2) Why didn't that > > cause an error like above for the 3 byte character? > > Since you've already encoded the Unicode object as a normal string, > Python isn't trying to do any implicit encoding. As for why 'abc' > appears in plain text, that's just the way repr works: > > >>> s = 'a' > >>> print repr(s) > 'a' > >>> t = '\x99' > >>> print repr(t) > '\x99' > > repr is attempting to show the string in the most readable fashion. If > the character is printable, then it just shows it as itself. If it's > unprintable, then it shows it in hex string escape notation. > > > Then if I try this: > > > > --- > > u_str = u"abc\u9999" > > reg_str = u_str.encode("utf-8") > > print reg_str > > --- > > > > I get the output: > > > > abc > > > > Here it looks like python isn't using the ascii decoder anymore. 2) > > What determines which decoder python uses? > > Again, that's because by already encoding it as a string, Python isn't > doing any implicit encoding. So it prints the raw string, which happens > to be UTF-8, and which your terminal obviously supports, so you see the > proper character. > > -- > 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 > Let us not seek the Republican answer or the Democratic answer but > the right answer. -- John F. Kennedy So let me see if I have this right: Here is some code: ----- print "print unicode string:" #print u"abc\u9999" #error print repr(u'abc\u9999') print print "print regular string containing chars in unicode syntax:" print 'abc\u9999' print repr('abc\u9999') print print "print regular string containing chars in utf-8 syntax:" #encode() converts unicode strings to regular strings print u'abc\u9999'.encode("utf-8") print repr(u'abc\u9999'.encode("utf-8") ) ----- Here is the output: ------- print unicode string: u'abc\u9999' print regular string containing chars in unicode syntax: abc\u9999 'abc\\u9999' print regular string containing chars in utf-8 syntax: abc 'abc\xe9\xa6\x99' ------ 1) If you print a unicode string: *print implicitly calls str()* a) str() calls encode(), and encode() tries to convert the unicode string to a regular string. encode() uses the default encoding, which is ascii. If encode() can't convert a character, then encode() raises an exception. b) repr() calls encode(), but if encode() raises an exception for a character, repr() catches the exception and skips over the character leaving the character unchanged. 2) If you print a regular string containing characters in unicode syntax: a) str() calls encode(), but if encode() raises an exception for a character, str() catches the exception and skips over the character leaving the character unchanged. Same as 1b. b) repr() similar to a), but repr() then escapes the escapes in the string. 3) If you print a regular string containing characters in utf-8 syntax: a) str() outputs the string to your terminal, and if your terminal can convert the utf-8 numerical codes to characters it does so. b) repr() blocks your terminal from interpreting the characters by escaping the escapes in your string. Why don't I see two slashes like in the output for 2b? From steve at holdenweb.com Sun Jul 15 15:06:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 15 Jul 2007 15:06:03 -0400 Subject: zipfile 2GB problems? In-Reply-To: <1184525970.082235.238200@q75g2000hsh.googlegroups.com> References: <1184474112.081258.111490@n60g2000hse.googlegroups.com> <1184525970.082235.238200@q75g2000hsh.googlegroups.com> Message-ID: xamdam wrote: > On Jul 15, 12:35 am, xamdam wrote: >> Hi fellas, >> I am experiencing problems reading a 2GB zipfile consisting of >> multiple zipped files. I found a thread http://mail.python.org/pipermail/python-dev/2005-April/053027.html >> that mentions a problem on the writing side, does such a problem exist >> on a reading side? I am using 2.4.1, perhaps there is a fix in a later >> version? > > Additional info: my file is from a data provider, do not know what > they used to compress it. Previous files worked ok, this one is the > 1st over 2GB. Winzip has no problem with it. > > It could be you are using a Python with an in-built limit of 2GB on file size. What happens if you open the file, seek past the 2GB point and then try and read data? 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 duncan.booth at invalid.invalid Sun Jul 1 05:00:45 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jul 2007 09:00:45 GMT Subject: howto resend args and kwargs to other func? References: <1183279997.244378.105810@n60g2000hse.googlegroups.com> Message-ID: dmitrey wrote: > I need something like this: > > def func1(*args, **kwargs): > if some_cond: > return func2(*args, **kwargs) > else: > return func3(some_other_args, **kwargs) > > Thank you in advance, D. > > You 'need something like this', so write something like that. Did you intend to ask a question? From exarkun at divmod.com Fri Jul 6 12:09:20 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 6 Jul 2007 12:09:20 -0400 Subject: Expandable 2D Dictionaries? In-Reply-To: <1183736635.415927.208450@57g2000hsv.googlegroups.com> Message-ID: <20070706160920.4947.2015818722.divmod.quotient.7938@ohm> On Fri, 06 Jul 2007 15:43:55 -0000, Robert Dailey wrote: >Hi, > >I am interested in creating an expandable (dynamic) 2D dictionary. For >example: > >myvar["cat"]["paw"] = "Some String" > >The above example assumes "myvar" is declared. In order for this to >work, I have to know ahead of time the contents of the dictionary. For >the above to work, my declaration must look like: > >myvar = {"cat": {"paw":""} } > >I would like to not have to declare my dictionary like this, as it >does not allow it to be expandable. I'm very new to Python (I'm a >professional C++ programmer. Any comparisons to C++ would help me >understand concepts). > >Is there a way that when I index into my dictionary using an "unknown" >index (string), that python will dynamically add that key/value pair? This gets much easier if you change your structure around a bit: d = {} d["cat", "paw"] = "some string" Jean-Paul From python at jayloden.com Thu Jul 26 03:32:01 2007 From: python at jayloden.com (Jay Loden) Date: Thu, 26 Jul 2007 03:32:01 -0400 Subject: datetime.time() class - How to pass it a time string? In-Reply-To: <87hcntjqu3.fsf@benfinney.id.au> References: <1185297087.998644.53940@r34g2000hsd.googlegroups.com> <87hcntjqu3.fsf@benfinney.id.au> Message-ID: <46A84DF1.9090309@jayloden.com> Ben Finney wrote: > Neil Cerutti writes: > >> On 2007-07-24, Robert Dailey wrote: >>> Hi, >>> >>> I have a string in the following format: >>> >>> "00:00:25.886411" >>> >>> I would like to pass this string into the datetime.time() class >>> and have it parse the string and use the values. However, the >>> __init__() method only takes integers (which means I'd be >>> forced to parse the string myself). Does anyone know of a way I >>> can make it use the string? Thanks. >> Consult the documentation about time.strptime (to start) and then >> datetime.strptime (which refers back to the time.strptime docs, >> in a rather unfortunate manner). > > Unfortunately 'strptime' also only seems to parse the components as > integers: > > >>> import datetime > >>> time_format = "%H:%M:%S" > >>> time_value = datetime.datetime.strptime("09:45:31.064371", time_format) > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/_strptime.py", line 334, in strptime > data_string[found.end():]) > ValueError: unconverted data remains: .064371 > > The same thing happens with 'time.strptime'. So this isn't yet a > solution for the OP. How about something like this? >>> import time >>> import datetime >>> >>> time_fmt = "%H:%M:%S" >>> timestamp = "00:00:25.886411" >>> stamp,msec = timestamp.split('.') >>> dtime = datetime.datetime(*(time.strptime(stamp, time_fmt)[0:6] + (int(msec),))) >>> dtime datetime.datetime(1900, 1, 1, 0, 0, 25, 886411) -Jay From Afro.Systems at gmail.com Sat Jul 14 05:26:43 2007 From: Afro.Systems at gmail.com (Tzury) Date: Sat, 14 Jul 2007 09:26:43 -0000 Subject: MaildirMessage In-Reply-To: References: <1184287592.509355.310110@g4g2000hsf.googlegroups.com> <874pk8kedo.fsf@benfinney.id.au> <87vecniw4u.fsf@benfinney.id.au> Message-ID: <1184405203.481400.171600@m3g2000hsh.googlegroups.com> > What do you actually think > > ... for m in msg: > ... print m > > should do? Why do you believe that what you think it should do would be > a natural choice? I needed to know how to extract particular parts of a message, such as the message 'body', 'subject', 'author', etc. I couldn't find it in the documentation this kind of information until I ran the inspect.getmembers(msg) and found out that the message body stored in _payload. that is msg._payload is the content of the message. Regarding the *bug* thing it is very simple. If you iterate an int you get an exception , clear enough. Yet here I got the following exception which suggest an attempt to iterate ---. I do think that a message should support iteration for the very fact that each can contain a different type and amount of headers, and iteration in this case will make application's code clean and unified. From orsenthil at users.sourceforge.net Mon Jul 2 23:53:14 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Tue, 3 Jul 2007 09:23:14 +0530 Subject: what is the PythonWin In-Reply-To: <35pnl4-748.ln1@lairds.us> References: <1183330410.164963.151790@c77g2000hse.googlegroups.com> <35pnl4-748.ln1@lairds.us> Message-ID: <20070703035314.GB5532@gmail.com> * Cameron Laird [2007-07-02 17:27:31]: > >PythonWin is a separate project by Mark Hammond providing win32 extensions for > >python. > > > >http://sourceforge.net/projects/pywin32/ > . > . > . > I believe there's confusion afoot. > > Pythonwin is a > Python-oriented editor for Windows. Mark bundles Pythonwin > with a couple of other equally-intriguing pieces to make > pywin32. When I read, "win32 extensions for python", I think > of what Mark labels "win32api". I'm reasonably certain that, Thanks for the explaination, Cameron. Yeah, there was a confusion from my end. I hope the OP, got what he needed from the URL tough. -- O.R.Senthil Kumaran http://uthcode.sarovar.org From steve at holdenweb.com Mon Jul 30 11:53:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Jul 2007 11:53:42 -0400 Subject: How to write GUI and event separately in wxPython?? In-Reply-To: <4866bea60707300842m4f81d37ay34d46d30a8885a6@mail.gmail.com> References: <1185777254.925902.204500@z28g2000prd.googlegroups.com> <5h5kmiF3hmufcU3@mid.uni-berlin.de> <5h5upbF3hmufcU5@mid.uni-berlin.de> <4866bea60707300842m4f81d37ay34d46d30a8885a6@mail.gmail.com> Message-ID: Chris Mellon wrote: > On 7/30/07, Steve Holden wrote: >> Marc 'BlackJack' Rintsch wrote: >>> On Mon, 30 Jul 2007 06:32:55 -0400, Steve Holden wrote: >>> >>>> >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)] >>>> True >>> First I thought: Why the unnecessary list comprehension but to my surprise: >>> >>> In [33]: xrange(42) == xrange(42) >>> Out[33]: False >>> >>> That's strange. >>> >> Not so strange really. The two xrange objects are different (though I >> confess I haven't looked to see how they implement comparisons), but >> iterating over them produces the same result. > > > nitpick: list(xrange(42)) == list(xrange(42)) is slightly more concise > than the list comp.. Indeed. I wonder if anyone will pick a nit with the nit you picked on my nitpick ... nitty-gritti-ly y'rs - steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- 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 Jul 4 15:28:31 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 04 Jul 2007 12:28:31 -0700 Subject: Does Python work with QuickBooks SDK? In-Reply-To: <1183575085.446434.13410@z28g2000prd.googlegroups.com> References: <1183575085.446434.13410@z28g2000prd.googlegroups.com> Message-ID: <1183577311.623904.80360@n2g2000hse.googlegroups.com> On Jul 4, 1:51 pm, walterbyrd wrote: > My guess is that it would, but I can find no mention of python in the > intuit developers site. I can find some references to PHP and Perl, > but no Python. > > I looks to me like Intuit develops have a strong preference for visual- > basic, then c/c++, then delphi. > > I find it just a little bit surprising, since Python does work > with .Net and all. I'm not seeing a Python wrapper for the SDK, but it looks like you can access it with COM. This thread talks a little about doing just that: http://mail.python.org/pipermail/python-win32/2004-May/001990.html To learn more about Python and how to work with COM, check this site out: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html I hope that helps you out. Mike From cito at online.de Thu Jul 5 09:53:34 2007 From: cito at online.de (Christoph Zwerschke) Date: Thu, 05 Jul 2007 15:53:34 +0200 Subject: Re-raising exceptions with modified message Message-ID: What is the best way to re-raise any exception with a message supplemented with additional information (e.g. line number in a template)? Let's say for simplicity I just want to add "sorry" to every exception message. My naive solution was this: try: ... except Exception, e: raise e.__class__, str(e) + ", sorry!" This works pretty well for most exceptions, e.g. >>> try: ... 1/0 ... except Exception, e: ... raise e.__class__, str(e) + ", sorry!" ... Traceback (most recent call last): File "", line 4, in ZeroDivisionError: integer division or modulo by zero, sorry! But it fails for some exceptions that cannot be instantiated with a single string argument, like UnicodeDecodeError which gets "converted" to a TypeError: >>> try: ... unicode('\xe4') ... except Exception, e: ... raise e.__class__, str(e) + ", sorry!" ... Traceback (most recent call last): File "", line 4, in TypeError: function takes exactly 5 arguments (1 given) Another approach is using a wrapper Extension class: class SorryEx(Exception): def __init__(self, e): self._e = e def __getattr__(self, name): return getattr(self._e, name) def __str__(self): return str(self._e) + ", sorry!" try: unicode('\xe4') except Exception, e: raise SorryEx(e) But then I get the name of the wrapper class in the message: __main__.SorryEx: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128), sorry! Yet another approach would be to replace the __str__ method of e, but this does not work for new style Exceptions (Python 2.5). Any suggestions? -- Chris From martin at v.loewis.de Tue Jul 31 01:38:36 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 31 Jul 2007 07:38:36 +0200 Subject: Why no maintained wrapper to Win32? In-Reply-To: References: <46ab694e$0$17577$9b622d9e@news.freenet.de> <59kna3p8r0cu2gk6hs5lbig8cjj8klatju@4ax.com> <1185762820.496821.298530@19g2000hsx.googlegroups.com> <1185770944.301464.85060@b79g2000hse.googlegroups.com> Message-ID: <46aecadd$0$7318$9b622d9e@news.freenet.de> > Guess I have the answer as to no one seems to write GUI apps for > Windows natively :-) That's certainly an important factor. If I wanted to ship a small application, I would write a web server, and run that locally. GUI programming is so last-century :-) Regards, Martin From xing93111 at gmail.com Fri Jul 13 14:35:16 2007 From: xing93111 at gmail.com (xing93111 at gmail.com) Date: Fri, 13 Jul 2007 18:35:16 -0000 Subject: A Python newbie ask a simple question Message-ID: <1184351716.298630.80670@z28g2000prd.googlegroups.com> what does the statement "choice = raw_input(prompt)[0]" mean? I don't know why there is a '[0]' in the statement. Thank you very much From lgfang at localhost.my.domain Mon Jul 9 10:13:34 2007 From: lgfang at localhost.my.domain (lgfang) Date: Mon, 09 Jul 2007 22:13:34 +0800 Subject: patching pylint.el Message-ID: <86ps3164xd.fsf@localhost.my.domain.i-did-not-set--mail-host-address--so-tickle-me> Hi, I think this is a bug of pylint.el. But I failed finding a way to submit the bug neither in its official site nor in google. So I post it here wishing it may be useful for some buddies. The bug is that it uses "compile-internal" from "compile" without require compile. So "M-x pylint" will fail if compile hadn't been loaded in advance by any means. My fix is rather straightforward: add "(require 'compile)" in the code. ------ begin diff output ------ 2a3 > (require 'compile) ------ end diff output ------ Fang lungang From infocat at earthlink.net Tue Jul 3 22:18:43 2007 From: infocat at earthlink.net (Frank Swarbrick) Date: Tue, 03 Jul 2007 20:18:43 -0600 Subject: Tiny/small/minimalist Python? In-Reply-To: <1183428099.746633.252870@m37g2000prh.googlegroups.com> References: <1183332951.122782.212720@o11g2000prd.googlegroups.com> <7xved3satm.fsf@ruckus.brouhaha.com> <1183389420.175712.59460@z28g2000prd.googlegroups.com> <7xmyyeizf8.fsf@ruckus.brouhaha.com> <468997c7$0$327$e4fe514c@news.xs4all.nl> <1183428099.746633.252870@m37g2000prh.googlegroups.com> Message-ID: <5f0ec2F3an36qU1@mid.individual.net> rtk wrote: > > I did look briefly at Python 1.5.2, since it is simpler, but I'm > taking the trouble I've had as an excuse to learn a new language. So > far, I'm liking Lua, save the big pet peeve of starting indices at 1 > and not 0 as all sane people do. Hmm, that in and of itself sounds like a good enough reason for me to check it out! I despise zero-based subscripts. If I wanted to program in assembler then I'd program in assembler! :-) Frank From nospam at nospam.com Tue Jul 31 00:03:59 2007 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 31 Jul 2007 06:03:59 +0200 Subject: [2.5] Reading a two-column file into an array? Message-ID: Hello I'm sure there's a much easier way to read a two-column, CSV file into an array, but I haven't found it in Google. Should I use the Array module instead? ========= a = [] i = 0 #itemitem p = re.compile("^(.+)\t(.+)$") for line in textlines: m = p.search(line) if m: a[i,0] = m.group(1) a[i,1] = m.group(2) i = i + 1 for i in a.count: for j in 2: print a[i,j] ======= Thank you. From http Thu Jul 12 05:49:47 2007 From: http (Paul Rubin) Date: 12 Jul 2007 02:49:47 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: <7xsl7ux878.fsf@ruckus.brouhaha.com> Donn Cave writes: > I've wondered if programmers might differ a lot in how much they > dread errors, or how they react to different kinds of errors. > For example, do you feel a pang of remorse when your program > dies with a traceback - I mean, what a horrible way to die? I'm reminded of the time I found out that a program I had worked on had crashed due to a coding bug. It was the control software for an ATM switch. I had moved on from that job a year or so earlier, but I found out about the crash because it took out vast swaths of data communications for the whole US northeast corridor for 2+ days (almost like the extended power outage of 2003) and it was on the front page of the New York Times. The first thing I thought of was that a certain subroutine I had rewritten was the culprit. I got on the phone with a guy I had worked with to ask what the situation was, and I was very relieved to find out that the error was in a part of the code that I hadn't been anywhere near. That program was a mess of spaghetti C code but even more carefully written code keeps crashing the same way. It was one of the incidents that now has me interested in the quest for type-safe languages with serious optimizing compilers, that will allow us to finally trash every line of C code currently in existence ;-). From yuxi at ece.gatech.edu Sat Jul 14 17:32:58 2007 From: yuxi at ece.gatech.edu (Yu-Xi Lim) Date: Sat, 14 Jul 2007 17:32:58 -0400 Subject: Screen Scraping Question In-Reply-To: <1184245290.056488.178630@57g2000hsv.googlegroups.com> References: <1184157921.488811.295570@n60g2000hse.googlegroups.com> <1184245290.056488.178630@57g2000hsv.googlegroups.com> Message-ID: jeffbg123 wrote: > The numbers are always rendered the same. So I don't know if OCR is a > necessary step. > > Also, what if I just got the data from the packets? Any disadvantages > to that? Any good python packet capturing libraries? > > Thanks > Packet capture is probably a bad idea for two reasons. 1) It will give you a lot of packets you don't need and at a OSI layer so low that reassembly is painful. Try writing a HTTP or SOCKS proxy and get the Flash game to use that proxy. 2) Many Flash games would probably store (in the Flash file) or generate their scenarios instead of retrieving them over the Internet. From crcarleRemoveThis at BOGUSsandia.gov Fri Jul 13 16:32:30 2007 From: crcarleRemoveThis at BOGUSsandia.gov (Chris Carlen) Date: Fri, 13 Jul 2007 13:32:30 -0700 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: Neil Cerutti wrote: > Going back to the stack machine question, and using it as an > example: Assume you design your program as a state machine. > Wouldn't it be easier to implement in a (hypothetical) > state-machine-based programming language than in a procedural > one? I think John was insinuating that a state-machine is more > like an object than it is like a procedure. I think at this point, I should stop questioning and just learn for a while. But regarding state machines, I had probably written a few in C the past before really understanding that it was a state machine. Much later I grasped state machines from digital logic. Then it became much clearer how to use them as a tool and to code them intentionally. Once I have written a state table, I can implement using flip-flops and gates or in C as either a state variable and a switch statement or something table driven. The switch code can be written as fast as I can read through the state table. That's the easiest implementation, but the least easy to change later unless it's fairly small. I will be eager to see how to do this in Python. I have found the comments in response to my doubts about OOP very encouraging. I will do some learning, and come back when I have more Python specific problems... Thanks for the input! -- Good day! ________________________________________ Christopher R. Carlen Principal Laser&Electronics Technologist Sandia National Laboratories CA USA crcarleRemoveThis at BOGUSsandia.gov NOTE, delete texts: "RemoveThis" and "BOGUS" from email address to reply. From tkondal at gmail.com Wed Jul 18 16:13:52 2007 From: tkondal at gmail.com (tkondal) Date: Wed, 18 Jul 2007 13:13:52 -0700 Subject: Deleting files and folders used by other processes on Windows Message-ID: <1184789632.425007.259000@i13g2000prf.googlegroups.com> Hi, I have been looking into making my file cleaning script more intelligent. The goal of the script is to delete everything on a drive except for a couple of folders which are skipped by the script. Recently, I noticed that some files where not being deleted because a process was using them. Is there a recipe (needs to run on Windows XP/ 2003) for doing the following (more specifically, I need a way to determine which process is holding a lock on my file): file=GetFilename(); bLock = IsThereAFileLockOnFile(file) If (bLock) { process = GetLockingProcess(file); TerminateProcess(process); } DeleteFile(file); Thanks. From boris.dusek at gmail.com Tue Jul 24 18:51:30 2007 From: boris.dusek at gmail.com (=?utf-8?B?Qm9yaXMgRHXFoWVr?=) Date: Tue, 24 Jul 2007 15:51:30 -0700 Subject: Base class for file-like objects? (a.k.a "Stream" in Java) Message-ID: <1185317490.607920.100200@z24g2000prh.googlegroups.com> Hello, (sorry to begin with Java in a Python list ;-) in Java, when I want to pass input to a function, I pass "InputStream", which is a base class of any input stream. In Python, I found that "file" objects exist. While specifying argument types in Python is not possible as in Java, it is possible to check whether an object is an instance of some class and that's what I need - I need to check if an argument is a "file"-like object, and if yes, behave accordingly, if not, treat the argument as string with URL. But I am afraid there is no such a base class - I tried the following: >>> import urllib >>> >>> f = open("test.txt", "r") >>> g = urllib.urlopen("http://www.google.com/") >>> >>> isinstance(f, file) True >>> isinstance(f, file) False ... Is there some base class to "file"-like (or "stream"-like) objects in Python? And if not, is it at least planned for Python 3.0? Thanks for any suggestions, Boris Du?ek P.S.: The code should finally look in esence something like this: if isinstance(f, file): pass elif isinstance(f, string): f = urllib.urlopen(f) else: raise "..." process_stream(f) From arnoreg at gmail.com Sun Jul 8 12:20:46 2007 From: arnoreg at gmail.com (Arno Stienen) Date: Sun, 08 Jul 2007 18:20:46 +0200 Subject: xmlrpclib hangs execution In-Reply-To: <465DED55.6040106@gmail.com> References: <45AC0631.8080601@ctw.utwente.nl> <465890FB.4030405@utwente.nl> <465A9DC7.2010708@gmail.com> <465d9040$0$326$e4fe514c@news.xs4all.nl> <465DED55.6040106@gmail.com> Message-ID: <46910EDE.5010207@gmail.com> Arno Stienen wrote: > I'll now try this to fool the client into thinking the server 'should' > keep the connection open: > > http://www.velocityreviews.com/forums/t329401-re-xmlrpc-httplib-and-ssl-http-11-xmlrpc-client.html Just to conclude. Above actually worked and solved my problems with xmlrpclib hanging. Here you can find the above link with correct indentation: http://mail.python.org/pipermail/python-list/2004-April/256360.html Thanks for all the advice, especially from Tijs! Bye, Arno. From deets at nospam.web.de Sun Jul 1 07:25:49 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 01 Jul 2007 13:25:49 +0200 Subject: Reading image dimensions before it is loaded from a web form using python. In-Reply-To: References: <46869EE1.4020608@khine.net> <6vajl4-vf.ln1@lairds.us> Message-ID: <5eph9vF39tb5lU1@mid.uni-berlin.de> > > Without running some special client-side application, I think you'd > have to do some trickery with the web server involving artificially > stopping the upload after receiving enough bytes to constitute the > image header, and then deciding whether or not to proceed with the > upload at that point. I think that this is definitely nontrivial since > it would most likely involve some hacking of Apache (or whatever web > server you are using). Certainly not. The upload is a simple HTTP POST request, and it's dealt by with your application. For example, you could put a simple CGI script behind a certain url, and once it has read a few bytes or KBytes from stdin, it will test for compliance. Admittedly, most people use some webframework - which usually abstracts away the uploading and passes some file-like object to you when the upload is finished. But then it's an extension to that framework, and given the fact that most of these support out of the box file upload meters, or at least there are recipies how to do so, things should work pretty easy. Diez From http Wed Jul 4 04:22:45 2007 From: http (Paul Rubin) Date: 04 Jul 2007 01:22:45 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> Message-ID: <7xd4z837e2.fsf@ruckus.brouhaha.com> greg writes: > > E.g. your program might pass its test and run properly for years > > before some weird piece of input data causes some regexp to not quite > > work. > > Then you get a bug report, you fix it, and you add a test > for it so that particular bug can't happen again. Why on earth would anyone prefer taking a failure in the field over having a static type check make that particular failure impossible? > > Once I got the function to work, I deployed it without writing > > permanent tests for it. > > That suggests you had a temporary test at some point. I ran the function on real, dynamic data and made sure the results were right. > So, keep it and make it a permanent test. Even if it's just a small > manually-created directory, it's still better than nothing, and you > can add to it over time to cover any bugs that turn up. That doesn't obviously fit into the doctest framework; such a test would be considerably more complex than the function itself, and the types of situations that I could imagine causing failures wouldn't be included in a test like that. Basically I had to get on to the next thing. Given the somewhat throwaway nature of this particular code, nothing else really made sense. But I think I'm going to look into using dejagnu for more heavyweight testing of some other parts of the program, so I guess some good came out of discussing this issue. Thanks. From robert.rawlins at thinkbluemedia.co.uk Wed Jul 18 05:19:50 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 18 Jul 2007 10:19:50 +0100 Subject: Subprocess Poll Message-ID: <02a301c7c91c$cbafc5b0$630f5110$@rawlins@thinkbluemedia.co.uk> Hello Guys, I have an application which launches a sub-process using the sub process/Popen module, which seems to work great. However on occasion the launched process will crash, it doesn't appear to full terminate though as when I run a 'top' command from the Linux system the process is still displayed in the list, it just appears to be dormant and the TIME+ for the application stops incrementing. Can I use the poll() method from the sub-process object to test for this? I would love to test it however the crash is so rare it's very difficult to simulate, so thought I'd try and see if anyone has any experience of this. Thanks chaps, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From phd at phd.pp.ru Fri Jul 27 11:27:54 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Fri, 27 Jul 2007 19:27:54 +0400 Subject: SQLObject 0.7.8 In-Reply-To: <000201c7d061$bcfe3550$c9b6d5cf@george644090dd> References: <20070726142305.GC30176@phd.pp.ru> <000201c7d061$bcfe3550$c9b6d5cf@george644090dd> Message-ID: <20070727152754.GA30355@phd.pp.ru> Hello! On Fri, Jul 27, 2007 at 08:21:00AM -0700, george williams wrote: > ----- Original Message ----- And what is the question? Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From kay.schluehr at gmx.net Thu Jul 5 06:18:50 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 05 Jul 2007 03:18:50 -0700 Subject: The best platform and editor for Python In-Reply-To: References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> Message-ID: <1183630730.251890.238900@m36g2000hse.googlegroups.com> On Jul 3, 8:12 pm, cla... at lairds.us (Cameron Laird) wrote: > Python is simply easier than C++; you might > well find that a debugger, for example, doesn't feel as essential > as it is for you with C++. That's what I love most about the Python community. Whenever there is just a non-standard, platform-dependent or crappy implementation of a feature you get told that you don't need it. When printf was good for little David print is good enough for me. Among the first things I examine about an IDE ( for Python ) is the integration of a good REPL and how well recursive functions can be debugged ( yes, I know, Pythonistas can't recurse and so it is not recommended as well but sometimes ... ) From aisaac at american.edu Tue Jul 10 11:58:23 2007 From: aisaac at american.edu (Alan Isaac) Date: Tue, 10 Jul 2007 15:58:23 GMT Subject: bool behavior in Python 3000? Message-ID: Is there any discussion of having real booleans in Python 3000? Say something along the line of the numpy implementation for arrays of type 'bool'? Hoping the bool type will be fixed will be fixed, Alan Isaac From stesch at no-spoon.de Thu Jul 26 07:56:40 2007 From: stesch at no-spoon.de (Stefan Scholl) Date: Thu, 26 Jul 2007 13:56:40 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> Message-ID: <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> Stefan Behnel wrote: > Stefan Scholl wrote: >> After an hour searching for a potential bug in XML parsing >> (PyXML), after updating from 2.4 to 2.5, I found this one: >> >> $ python2.5 >> Python 2.5 (release25-maint, Dec 9 2006, 14:35:53) >> [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import StringIO >>>>> x = StringIO.StringIO(u"m\xf6p") >>>>> import cStringIO >>>>> x = cStringIO.StringIO(u"m\xf6p") >> Traceback (most recent call last): >> File "", line 1, in >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 1: ordinal not in range(128) >> $ python >> Python 2.4.4 (#2, Apr 5 2007, 20:11:18) >> [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 >> Type "help", "copyright", "credits" or "license" for more information. >>>>> import StringIO >>>>> x = StringIO.StringIO(u"m\xf6p") >>>>> import cStringIO >>>>> x = cStringIO.StringIO(u"m\xf6p") >> >> >> OK, that's why my code was fine with Python 2.4 and breaks with >> 2.5. > > It wasn't fine with 2.4 either: Worked in my test, a few lines above ... > > """ > Unlike the memory files implemented by the StringIO module, those provided by > this module are not able to accept Unicode strings that cannot be encoded as > plain ASCII strings. > """ > > http://docs.python.org/lib/module-cStringIO.html > > Read the docs... Well, http://docs.python.org/lib/module-xml.sax.html is missing the fact, that I can't use Unicode with parseString(). This parseString() uses cStringIO. -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From xah at xahlee.org Wed Jul 18 09:17:00 2007 From: xah at xahlee.org (Xah Lee) Date: Wed, 18 Jul 2007 06:17:00 -0700 Subject: The Modernization of Emacs: exists already In-Reply-To: <1182272678.877166.209640@j4g2000prf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272678.877166.209640@j4g2000prf.googlegroups.com> Message-ID: <1184764620.778937.264760@m37g2000prh.googlegroups.com> About a month ago, i posted a message about modernization of emacs. I enlisted several items that i think emacs should adapt. Today I added another section to the frequestly asked questions. The new section is pasted below. The full article can be found at http://xahlee.org/emacs/modernization.html ------------------------------ Q: The Meta key is logical and proper, it shouldn't be renamed to Alt. A: Most computer geekers think that the so-called "Meta" key of Emacs is a more general and logical naming, and they believe in Emacs documentation the term "Meta key" should not be called the "Alt key" to fit the mundane PC keyboard. [image] above: The Space-cadet keyboard (Source , 2007-07) . Emacs's naming of Meta key isn't actually a general naming scheme. It is simply the name of a special modifier key on a particular keyboard popularly used with Emacs in the 1980s. (see Space-cadet keyboard ) On this keyboard, it has several modifier keys, including Ctrl, Meta, Super, Hyper. The Emacs's use of the term "Meta key" simply referred to that key on that keyboard. Emacs actually also support the other modifier keys Super and Hyper to this day. The Space-cadet keyboard fell out of use along with Lisp machine . The IBM PC keyboard (and its decendents) becomes the most popular since the 1990s and is practically the standard keyboard used today. The IBM PC keyboard does not have Super and Hyper keys, so Emacs's support for them becomes little known, but Ctrl remains Ctrl while Meta is mapped to the Alt key. In Emacs's documentation, the term Meta key should be replaced with the Alt key, to reflect current usage, since that is the keyboard 99% of personal computer users know. The "Meta key" name is a major point of confusion for getting people to learn Emacs. The abbreviation C- and M- to represent keyboard shortcuts should similarly be updated to the more easy-to-understand and universal Ctrl- and Alt-. Xah xah at xahlee.org http://xahlee.org/ From aahz at pythoncraft.com Wed Jul 4 11:57:48 2007 From: aahz at pythoncraft.com (Aahz) Date: 4 Jul 2007 08:57:48 -0700 Subject: Reversing a string References: <1i0kjpx.wjw44j15np22dN%aleax@mac.com> Message-ID: In article , Martin Durkin wrote: >aleax at mac.com (Alex Martelli) wrote in >news:1i0kjpx.wjw44j15np22dN%aleax at mac.com: >> >> So, something like: >> >> for c in reversed(x): print c >> >> is mostly likely how I'd present the solution to the task. > >This is an interesting point to me. I am just learning Python and >I wonder how I would know that a built in function already exists? >At what point do I stop searching for a ready made solution to a >particular problem and start programming my own function? Is it just a >matter of reading *all* the documentation before I start coding? You should at least know that you can do: l = list(s) l.reverse() for c in l: print c This works in all versions of Python back to 1.5.2 IIRC. reversed() is a moderately new built-in function; I would agree with people who claim that you should memorize most of the built-in functions (which is precisely why there is a high barrier to adding more built-in functions). But certainly if you're using a datatype you should make a point of reading all its documentation, which would mean you'd know that list() can convert any iterable type. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I support the RKAB From steve at holdenweb.com Tue Jul 10 22:14:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Jul 2007 22:14:17 -0400 Subject: Where is the syntax for the dict() constructor ?! (OT) In-Reply-To: <02c201c7c2c6$e460a2c0$03000080@hendrik> References: <468D1D9D.6060002@gmail.com><468D3445.2060408@gmail.com><1183675552.466967.136360@i13g2000prf.googlegroups.com><5f6fo1F3b25tsU1@mid.uni-berlin.de><5f8rrpF3c8qopU1@mid.uni-berlin.de> <1183853628.296224.107400@i13g2000prf.googlegroups.com><00bc01c7c13f$573770a0$03000080@hendrik> <003801c7c1ef$afcf6e60$03000080@hendrik> <02c201c7c2c6$e460a2c0$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "Steve Holden" wrote: > >> Sorry - dreadful joke. Since teeth chew, I wondered whether esteeth >> might eschew. [Graon ...] >> > > *grin* > > *Wonders if he can extend this troll to get Steve to explain what "teeth" are.* > > ; - ) > > - Hendrik > Bite 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 ndbecker2 at gmail.com Tue Jul 31 07:34:09 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Tue, 31 Jul 2007 07:34:09 -0400 Subject: interaction of 'with' and 'yield' Message-ID: I'm wondering if a generator that is within a 'with' scope exits the 'with' when it encounters 'yield'. I would like to use a generator to implement RAII without having to syntactically enclose the code in the 'with' scope, and I am hoping that the the yield does not exit the 'with' scope and release the resource. From spamtrap at dot-app.org Thu Jul 26 17:59:28 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Thu, 26 Jul 2007 17:59:28 -0400 Subject: SQLObject 0.9.1 References: <20070726143614.GI30176@phd.pp.ru> Message-ID: Gerardo Herzig writes: > So..at 11:23 we got version 0.7.8...at 11:30 was version 0.8.5...now > there is a 0.9.1 version?? Have a coffe dude Sounds more to me like he needs to lay off the coffee, or at least switch to decaffeinated for a while. :-) sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From bignose+hates-spam at benfinney.id.au Tue Jul 10 21:18:56 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 11 Jul 2007 11:18:56 +1000 Subject: bool behavior in Python 3000? References: Message-ID: <87lkdnlou7.fsf@benfinney.id.au> Steven Bethard writes: > It's much easier to explain to newcomers that *, + and - work on > True and False as if they were 1 and 0 than it is to introduce them > to a two element boolean algebra. I've found exactly the opposite. When explaining that None is a value that is not equal to any other, and that is a useful property, I've received little confusion. Whereas when someone discovers that arithmetic works on True and False as if they were numbers, or that they are in fact *equal to* numbers, their function as boolean values is much harder to explain. So, it's for the purposes of explaining True and False to newcomers (let alone keeping things clear when observing a program) that I would welcome True and False as discrete values, so that when those values are produced by an expression or function the result is clearly a boolean value and not a faked one that is "really" an integer. -- \ "Pinky, are you pondering what I'm pondering?" "Wuh, I think | `\ so, Brain, but wouldn't anything lose its flavor on the bedpost | _o__) overnight?" -- _Pinky and The Brain_ | Ben Finney From byte8bits at gmail.com Mon Jul 9 11:31:05 2007 From: byte8bits at gmail.com (brad) Date: Mon, 09 Jul 2007 11:31:05 -0400 Subject: execute script in certain directory Message-ID: When I use idle or a shell to execute a python script, the script executes in the directory it is currently in (in this case, my desktop). However, when using GNOME and right clicking the py script and selecting 'open with python', the execution occurs in my home directory, not my desktop. Is there a way to force py scripts to always run within the directory that they reside in? Thanks Brad /home/brad/Desktop/output - python from shell /home/brad/Desktop/output - python from idle /home/brad/output - python from Gnome 'right click' open with menu From mccredie at gmail.com Thu Jul 12 19:54:21 2007 From: mccredie at gmail.com (Matimus) Date: Thu, 12 Jul 2007 23:54:21 -0000 Subject: Fastest way to convert a byte of integer into a list In-Reply-To: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> Message-ID: <1184284461.506663.75500@g12g2000prg.googlegroups.com> On Jul 12, 3:34 pm, Godzilla wrote: > Hello, > > I'm trying to find a way to convert an integer (8-bits long for > starters) and converting them to a list, e.g.: > > num = 255 > numList = [1,1,1,1,1,1,1,1] > > with the first element of the list being the least significant, so > that i can keep appending to that list without having to worry about > the size of the integer. I need to do this because some of the > function call can return a 2 lots of 32-bit numbers. I have to find a > way to transport this in a list... or is there a better way? num = 255 numlist = [num >> i & 1 for i in range(8)] From pyscottishguy at hotmail.com Thu Jul 26 15:50:08 2007 From: pyscottishguy at hotmail.com (pyscottishguy at hotmail.com) Date: Thu, 26 Jul 2007 19:50:08 -0000 Subject: pyparser and recursion problem Message-ID: <1185479408.520124.40670@k79g2000hse.googlegroups.com> Hi, Using pyparser, I'm trying to parse a string like this: :Start: first SECOND THIRD :SECOND: second1 | second2 :THIRD: third1 | FOURTH :FOURTH: fourth1 | fourth2 I want the parser to do the following: 1) Get the text for the :Start: label e.g ('first SECOND THIRD') 2) Do nothing with the lower-case words e.g ('first') 3) For each upper-case word find the corresponding entries, and replace the word with these entries (the '|' indicates separate records) e.g. for 'SECOND', replace the word with ("second1", "second2") 4 Do this recursively, because each item in '3' can have upper-case words I can do this - but not within pyparser. I had to write a recursive function to do it. I would like to do it within pyparser however. I'm pretty sure I have to use the Forward() function along with a few setResultsName() - but after reading the documentation, many examples, and trying for hours, I'm still totally lost. Please help! Here is the program I have so far: #!/usr/bin/python from pyparsing import Word, Optional, OneOrMore, Group, alphas, alphanums, Suppress, Dict import string def allIn( as, members ): "Tests that all elements of as are in members""" for a in as: if a not in members: return False return True def allUpper( as ): """Tests that all strings in as are uppercase""" return allIn( as, string.uppercase ) def getItems(myArray, myDict): """Recursively get the items for each CAPITAL word""" myElements=[] for element in myArray: myWords=[] for word in element: if allUpper(word): items = getItems(myDict[word], myDict) myWords.append(items) else: myWords.append(word) myElements.append(myWords) return myElements testData = """ :Start: first SECOND THIRD fourth FIFTH :SECOND: second1_1 second1_2 | second2 | second3 :THIRD: third1 third2 | SIXTH :FIFTH: fifth1 | SEVENTH :SIXTH: sixth1_1 sixth1_2 | sixth2 :SEVENTH: EIGHTH | seventh1 :EIGHTH: eighth1 | eighth2 """ label = Suppress(":") + Word(alphas + "_") + Suppress(":") words = Group(OneOrMore(Word(alphanums + "_"))) + Suppress(Optional("|")) data = ~label + OneOrMore(words) line = Group(label + data) doc = Dict(OneOrMore(line)) res = doc.parseString(testData) # This prints out what pyparser gives us for line in res: print line print print startString = res["Start"] items = getItems([startString], res)[0] # This prints out what we want for line in items: print line From stefan.behnel-n05pAM at web.de Fri Jul 6 07:17:36 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 06 Jul 2007 13:17:36 +0200 Subject: Learn Oracle Database Administration in 10 Minutes In-Reply-To: <1183719830.310797.31090@n2g2000hse.googlegroups.com> References: <1183719830.310797.31090@n2g2000hse.googlegroups.com> Message-ID: <468E24D0.8070009@web.de> takveen at gmail.com wrote: > Learn Oracle Database Administration in 10 Minutes. No kidding. Check > it yourself, > > http://www.takveen.com It already takes longer than 10 minutes to install, so I have the time to learn more than I find in that book before I even get to using it. Besides, this is completely off-topic spam. Stefan From cito at online.de Thu Jul 5 15:29:33 2007 From: cito at online.de (Christoph Zwerschke) Date: Thu, 05 Jul 2007 21:29:33 +0200 Subject: Proposal: s1.intersects(s2) In-Reply-To: References: <5f1pldF3a62csU5@mid.uni-berlin.de> <1183600138.759015.246040@c77g2000hse.googlegroups.com> Message-ID: Steven D'Aprano wrote: > I'm not a professional set theorist, but in 15-odd years of studying and > teaching maths I've never come across mathematicians using intersect as a > verb except as informal short-hand. I often say "North Street and South > Street don't intersect", but "the intersection of sets A and B is empty". I think mathematicians use more often the inverse predicate, namely "disjoint", which is well defined as having an empty intersection. -- Chris From bj_666 at gmx.net Fri Jul 27 02:23:51 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jul 2007 06:23:51 GMT Subject: C API -- Two questions References: <1185496462.855297.21240@57g2000hsv.googlegroups.com> Message-ID: <5gthbnF3i0lfsU1@mid.uni-berlin.de> On Fri, 27 Jul 2007 00:34:22 +0000, beginner wrote: > 2) How can I make the arguments less picky without writing a lot of > type conversion code? My function really needs a tuple as its > argument. For example, f( (1,2,3) ) would work. However, in order to > make it easy to use, I am thinking that it should be able to take a > list too. In other words, I want f( [1,2,3] ) to work also. I can > certainly check for the types in the code and deal with each > situation. But remember this is tedious to do in C. Is there any > better way to handle this? The same way as you would do in Python: convert the argument into a tuple if you *really* need a tuple, or just use it as sequence or via iterator. And pay attention to errors of course. Ciao, Marc 'BlackJack' Rintsch From ladaan at iptel.org Thu Jul 12 14:55:39 2007 From: ladaan at iptel.org (Ladislav Andel) Date: Thu, 12 Jul 2007 20:55:39 +0200 Subject: lists and dictionaries In-Reply-To: <1184250011.187346.70470@r34g2000hsd.googlegroups.com> References: <1184184582.330491.326600@e9g2000prf.googlegroups.com> <1184208542.948772.50700@w3g2000hsg.googlegroups.com> <1184250011.187346.70470@r34g2000hsd.googlegroups.com> Message-ID: <4696792B.8030206@iptel.org> Thank you to all of you guys. It's exactly I was looking for. Lada Bart Ogryczak wrote: > On 12 jul, 04:49, anethema wrote: > >>> li = [ {'index': 0, 'transport': 'udp', 'service_domain': >>> 'dp0.example.com'}, >>> {'index': 1, 'transport': 'udp', 'service_domain': >>> 'dp1.example.com'}, >>> {'index': 0, 'transport': 'tcp', 'service_domain': >>> 'dp0.example.com'}, >>> {'index': 1, 'transport': 'tcp', 'service_domain': >>> 'dp1.example.com'}] >>> >> I like this solution: >> >> [{ 'transports' : [d['transport'] for d in li if >> d['service_domain'] == dom], >> 'service_domain': dom, >> } for dom in set(d2['service_domain'] for d2 in li)] >> >> merely because it takes one line. Humorously enough, it appears to be >> twice as efficient, >> > > Correct me if I?m wrong, that is a O(n**2) solution, to O(n) problem. > > From BMintern at gmail.com Tue Jul 17 01:40:11 2007 From: BMintern at gmail.com (BMintern at gmail.com) Date: Tue, 17 Jul 2007 05:40:11 -0000 Subject: getting text inside the HTML tag In-Reply-To: <1184436087.239958.228710@r34g2000hsd.googlegroups.com> References: <1184436087.239958.228710@r34g2000hsd.googlegroups.com> Message-ID: <1184650811.476690.232660@m3g2000hsh.googlegroups.com> On Jul 14, 2:01 pm, kyoso... at gmail.com wrote: > Oi! Try Beautiful Soup instead. That seems to be the defacto HTML > parser for Python: > > http://www.crummy.com/software/BeautifulSoup/ After reading the docs through a bit and working through my own examples, I can see why. Thanks for the link! Brandon From mpeters42 at gmail.com Mon Jul 2 01:07:23 2007 From: mpeters42 at gmail.com (Mark Peters) Date: Mon, 02 Jul 2007 05:07:23 -0000 Subject: Probably simple syntax error In-Reply-To: <1183351228.878746.233430@o61g2000hsh.googlegroups.com> References: <1183351228.878746.233430@o61g2000hsh.googlegroups.com> Message-ID: <1183352843.803263.82140@57g2000hsv.googlegroups.com> > **weights_array(randomizing_counter) = small_randomized_int > > The starred line is the one getting the error message: "SyntaxError: > can't assign to function call" > > Now, I do understand what this means. I'm trying to assign to a > function instead of the value that the function should create. But > since when is weights_array or small_randomizing_int a function? Both > are being declared in the code on their first usage. This one has got > me stumped, maybe you guys can help me out with it? Using parens () indicates a function call. I suspect things will work much better using square brackets []. Square brackets indicate the index into a sequence (like a list) From kasimmominov at gmail.com Sun Jul 1 12:35:46 2007 From: kasimmominov at gmail.com (kasim) Date: Sun, 01 Jul 2007 16:35:46 -0000 Subject: hi every one please become a member to this site and win much more money!!!! Message-ID: <1183307746.155013.87250@k79g2000hse.googlegroups.com> http://www.agloco.com/r/BBFR2592 http://www.agloco.com/r/BBFR2592 http://www.agloco.com/r/BBFR2592 Dear ______, I recently joined AGLOCO because of a friend recommended it to me. I am now promoting it to you because I like the idea and I want you to share in what I think will be an exciting new Internet concept. AGLOCO's story is simple: Do you realize how valuable you are? Advertisers, search providers and online retailers are paying billions to reach you while you surf. How much of that money are you making? NONE! AGLOCO thinks you deserve a piece of the action. AGLOCO collects money from those companies on behalf of its members. (For example, Google currently pays AOL 10 cents for every Google search by an AOL user. And Google still has enough profit to pay $1.6 billion dollars for YouTube, an 18-month old site full of content that YouTube's users did not get paid for! AGLOCO will work to get its Members their share of this and more. AGLOCO is building a new form of online community that they call an Economic Network. They are not only paying Members their fair share, but they're building a community that will generate the kind of fortune that YouTube made. But instead of that wealth making only a few people rich, the entire community will get its share. What's the catch? No catch - no spyware, no pop-ups and no spam - membership and software are free and AGLOCO is 100% member owned. Privacy is a core value and AGLOCO never sells or rents member information. So do both of us a favor: Sign up for AGLOCO right now! If you use this link to sign up, I automatically get credit for referring you and helping to build AGLOCO. http://www.agloco.com/r/BBFR2592 Please follow this link and create own membership by this link Thanks From Graham.Dumpleton at gmail.com Sat Jul 14 20:06:42 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 15 Jul 2007 00:06:42 -0000 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> Message-ID: <1184458002.961657.267830@x35g2000prf.googlegroups.com> On Jul 15, 2:47 am, 7stud wrote: > Themod_pythonmanual says this under section 2.1 Prerequisites: > > ------ > In order to compilemod_pythonyou will need to have the include files > for both Apache and Python, as well as the Python library installed on > your system. If you installed Python and Apache from source, then you > already have everything needed. However, if you are using prepackaged > software (e.g. Red Hat Linux RPM, Debian, or Solaris packages from > sunsite, etc) then chances are, you have just the binaries and not the > sources on your system. Often, the Apache and Python include files and > libraries necessary to compilemod_pythonare part of separate > ``development'' package. If you are not sure whether you have all the > necessary files, either compile and install Python and Apache from > source, or refer to the documentation for your system on how to get > the development packages. > ----- > > I installed Apache from source using these instructions: > > http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-o... > > but I used a package to install python 2.4. The package was from > here: > > http://www.pythonmac.org/packages/ > > and it's a "Universal binary version of Python that runs natively on > PPC and Intel systems." > > But my mac came with Python 2.3.5 pre-installed, so I wonder if I > already have the necessary "include files for both Apache and Python, > as well as the Python library" already installed. Have you actually tried to install mod_python? That would be the quickest way of finding out. Because you are using an alternate Apache than the OS supplied one, you will need to use the --with-apxs option to configure when building Python. Unless you really need Python 2.4, it is easier to use the OS supplied version of Python. If you must use an alternate version, use the --with-python option to configure for mod_python to tell it which version. Depending on where that Python version is installed, you may also have to fiddle the Apache 'envvars' file as well to get it to work. Graham From ng6 at padowan.dk Fri Jul 27 19:17:23 2007 From: ng6 at padowan.dk (Ivan Johansen) Date: Sat, 28 Jul 2007 01:17:23 +0200 Subject: Tkinter program with a usable interpreter console In-Reply-To: <1185572221.020114.192650@z24g2000prh.googlegroups.com> References: <1185572221.020114.192650@z24g2000prh.googlegroups.com> Message-ID: <46aa7d01$0$21933$157c6196@dreader1.cybercity.dk> beginner wrote: > The problem is that the Tkinter program ends with a .mainloop() call > and it is not going to give back control to the command prompt. I feel > it is almost like I need to implement the python shell myself. Is > there any better way of doing this? Take a look at this: http://lfw.org/python/Console.py I haven't really used it myself yet, but it looks really great. Ivan Johansen From irmen.NOSPAM at xs4all.nl Sat Jul 7 20:05:20 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 08 Jul 2007 02:05:20 +0200 Subject: socket: connection reset by server before client gets response In-Reply-To: <1183827514.109496.252870@d30g2000prg.googlegroups.com> References: <1183819907.249945.239700@o11g2000prd.googlegroups.com> <1183827514.109496.252870@d30g2000prg.googlegroups.com> Message-ID: <46902a45$0$331$e4fe514c@news.xs4all.nl> ahlongxp wrote: > me again. > > "Connection reset by peer" happens about one in fifth. > I'm using python 2.5.1 and ubuntu 7.04. > > -- > ahlongxp > > Software College,Northeastern University,China > ahlon... at gmail.comhttp://www.herofit.cn > > Post the code. Without it we can only help when our magic crystal balls are back from service. ==irmen From cito at online.de Thu Jul 5 10:40:41 2007 From: cito at online.de (Christoph Zwerschke) Date: Thu, 05 Jul 2007 16:40:41 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: References: Message-ID: Thomas Heller wrote: > I have the impression that you do NOT want to change the exceptions, > instead you want to print the traceback in a customized way. But I may be wrong... No, I really want to modify the exception, supplementing its message with additional information about the state of the program. The use case are compiled Kid templates (http://kid-templating.org). If an error occurs, I want to add the corresponding line number of the XML file as information for the template developer. Since the final error handling may happen somewhere else (e.g. by TurboGears importing a Kid template), I do not want to modify trackeback handling or something. -- Chris From bignose+hates-spam at benfinney.id.au Thu Jul 12 08:00:41 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 12 Jul 2007 22:00:41 +1000 Subject: Tuple vs List: Whats the difference? References: <1184177195.569916.184770@22g2000hsm.googlegroups.com> Message-ID: <87y7hlkf12.fsf@benfinney.id.au> Dave Baum writes: > In article <1184177195.569916.184770 at 22g2000hsm.googlegroups.com>, > Shafik wrote: > > > what exactly is the difference between a tuple and a list? I'm > > sure there are some, but I can't seem to find a situation where I > > can use one but not the other. > > Lists and tuples are both sequences, and can be used interchangeably > in many situations. The big difference is that lists are mutable > (can be modified), and tuples are immutable (cannot be modified). > Lists also have a richer API (for example the index and count > methods). This common misconception falls foul of only considering the implementation details. The choice of when to use one or the other is more one of intent: A tuple is best for heterogeneous sequences, a list is best for homogeneous sequences. Here's a better explanation: -- \ "No matter how cynical I get, I can't seem to keep up." -- | `\ Lily Tomlin | _o__) | Ben Finney From wbrehaut at mcsnet.ca Sat Jul 14 15:58:06 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Sat, 14 Jul 2007 13:58:06 -0600 Subject: Can a low-level programmer learn OOP? References: Message-ID: On Sat, 14 Jul 2007 11:49:48 -0600, darren kirby wrote: >quoth the Wayne Brehaut: > >> (I started with Royal McBee LGP 30 machine language (hex input) in >> 1958, and their ACT IV assembler later! Then FORTRAN IV in 1965. By >> 1967 I too was using (Burroughs) Algol-60, and 10 years later upgraded >> to (DEC-10) Simula-67.) >> >> Going---going--- > >Mel? Is that you? > >http://www.pbm.com/~lindahl/mel.html > Ha-ha! Thanks for that! Although I'm not Mel, the first program I saw running on the LGP-30 was his Blackjack program! In 1958 I took a Numerical Methods course at the University of Saskatchewan, and we got to program Newton's forward difference method for the LGP-30. Our "computer centre tour" was to the attic of the Physics building, where their LGP-30 was networked to a similar one at the Univeristy of Toronto (the first educational computer network in Canada!), and the operator played a few hands of Blackjack with the operator there to illustrate how useful computers could be. A few years later, as a telecommunications officer in the RCAF, I helped design (but never got to teach :-( ) a course in LGP-30 architecture and programming using both ML and ACT IV AL, complete with paper tape input and Charactron Tube (http://en.wikipedia.org/wiki/Charactron) output--handy, since this display was also used in the SAGE system. We weren't encouraged to use card games as examples, so used navigational and tracking problems involving fairly simple trigonometry. wwwayne >-d From rcdailey at gmail.com Fri Jul 6 19:26:28 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 06 Jul 2007 23:26:28 -0000 Subject: C++ Modules for python: How to? In-Reply-To: <5f7llqF3bfvstU1@mid.uni-berlin.de> References: <1183750094.154566.248170@m36g2000hse.googlegroups.com> <5f7llqF3bfvstU1@mid.uni-berlin.de> Message-ID: <1183764388.576690.31740@n60g2000hse.googlegroups.com> On Jul 6, 3:06 pm, "Diez B. Roggisch" wrote: > Robert Dailey schrieb: > > > Hi, > > > I'm interested in making a C++ library of mine usable through python. > > Python does a similar thing with Expat (the non-validating XML > > parser). I notice that with Expat, python is importing a C++ header > > file into a PY file and the interface is available to python. I've > > read through the python documentation as well as done a little bit of > > google research and I've not been able to find a tutorial of some sort > > on how to do this. Perhaps I just don't know the right words to search > > for. > > > If anyone could lead me in the right direction (possibly an article, > > tutorial, etc) I would greatly appreciate it. > > The best thing to do is to offer your C++-lib with a C-style interface. > Then you can use python's ctypes (included since python2.5) to access > the shared library. > > If you insist on using C++, you can expose the lib using several > available wrapper generators. I know of three: SIP, Swig & > Boost::Python. The first I've got some very good first-hand experience. > The second is somewhat primitive IHMO. The third I never used. > > Use these to google in this group, you'll find plenty of stuff. > > Diez How do I install SIP? I can't seem to do this. I've downloaded the package and read the README file, but I don't see a way of installing it on windows. I ran the configure.py file but then it generates makefiles to run which can't be run on windows. I also attempted to download QT but it doesn't appear to be free (it's an evaluation and I don't feel like submitting my personal information to download it). Am I missing something? Thank you for your reply. From ratchetgrid at googlemail.com Thu Jul 19 16:17:38 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Thu, 19 Jul 2007 21:17:38 +0100 Subject: Converting between objects Message-ID: <676224240707191317i41e76ab7lceb39fcb981b0188@mail.gmail.com> Hi, I have being thinking about this and was wondering with built in types you can do things like float(1) or str(200) is there way I can define conversion functions like this: say i have a class A and a class B bobj = B() aobj = a(bobj) in a neater way than just defining a set of methods def a(object_to_convert) # if object_to_convert of type...... # do some stuff return A() def b(object_to_convert) # if object_to_convert of type...... # do some stuff return B() Cause this seems a little verbose and not very OO. Please correct me if I m wrong or offer me hints as to a better way to do it ? Many Thanks nathan From claird at lairds.us Mon Jul 2 13:27:31 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 2 Jul 2007 17:27:31 +0000 Subject: what is the PythonWin References: <1183330410.164963.151790@c77g2000hse.googlegroups.com> Message-ID: <35pnl4-748.ln1@lairds.us> In article , O.R.Senthil Kumaran wrote: >* steveandleyla at gmail.com [2007-07-01 15:53:30]: > >> In PythonWin, select Tools | COM MakePy utility | Microsoft Speech >> Object Library 5.1). >> >> I can't find PythonWin .. Does anybody know what this is. I have the >> Python shell gui but no "PythonWin". >> >PythonWin is a separate project by Mark Hammond providing win32 extensions for >python. > >http://sourceforge.net/projects/pywin32/ . . . I believe there's confusion afoot. Pythonwin is a Python-oriented editor for Windows. Mark bundles Pythonwin with a couple of other equally-intriguing pieces to make pywin32. When I read, "win32 extensions for python", I think of what Mark labels "win32api". I'm reasonably certain that, in this case, steve had in mind specifically the editor, and *not* all of win32all--although he'll surely want to know that the canonical way to retrieve it is as part of pywin32 as a whole. From nytrokiss at gmail.com Fri Jul 20 16:07:35 2007 From: nytrokiss at gmail.com (James Matthews) Date: Fri, 20 Jul 2007 13:07:35 -0700 Subject: Trying to choose between python and java In-Reply-To: <20070720180348.GA7658@dynamo.powerhouse.invalid> References: <1i1bcty.j0nnz4hkz078N%aleax@mac.com> <20070720180348.GA7658@dynamo.powerhouse.invalid> Message-ID: <8a6b8e350707201307r75ee6032gfeadf3857c15c8ef@mail.gmail.com> You can always use jython. ;) On 7/20/07, rvu44vs02 at sneakemail.com wrote: > > On Sun, 15 Jul 2007 at 22:28:08 -0700, Alex Martelli wrote: > > James T. Dennis wrote: > > ... > > > You can start writing all your code now as: print() --- calling > > > the statement as if it were a function. Then you're future Python > > > > ...except that your output format will thereby become disgusting...: > > > > >>> name = 'Alex' > > >>> print 'Hello', name, 'and welcome to my program!' > > Hello Alex and welcome to my program! > > >>> print('Hello', name, 'and welcome to my program!') > > ('Hello', 'Alex', 'and welcome to my program!') > > > > In Python 2.*, the parentheses will make a tuple, and so you'll get an > > output full of parentheses, quotes and commas. I think it's pretty bad > > advice to give a newbie, to make his output as ugly as this. > > > > > > Alex > > -- > > One possible kind of print function that might be used in the interim is > something like: > > > def print_fn(*args): > """print on sys.stdout""" > arg_str = " ".join([str(x) for x in args]) > print arg_str > > -Jim > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/watches.asp?Brand=14 http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jul 10 07:29:06 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 10 Jul 2007 13:29:06 +0200 Subject: Should I use Python for these programs? References: <1395v33mpci3p5c@corp.supernews.com> Message-ID: <5fh8s2F3crmfnU1@mid.individual.net> Grant Edwards wrote: > Most of the graphics I do with Python is with Gnuplot (not > really appropriate for what you want to do. > wxWidgets/Floatcanvas might be worth looking into. Agreed (I'm quite sure you mean wxPython though). Also, in "wxPython in Action" (the official book) a simple drawing app is constructed. It could help to start from there. Regards, Bj?rn -- BOFH excuse #211: Lightning strikes. From gal.diskin at gmail.com Tue Jul 10 17:32:50 2007 From: gal.diskin at gmail.com (Gal Diskin) Date: Wed, 11 Jul 2007 00:32:50 +0300 Subject: subprocess popen trouble In-Reply-To: <1184085837.104954.235230@n2g2000hse.googlegroups.com> References: <1184085837.104954.235230@n2g2000hse.googlegroups.com> Message-ID: <4693FB02.4010606@gmail.com> Your code seems correct to me. Just as a long shot - have you tried setting bufsize=0 ? nik wrote: > I am having trouble using subprocess popen and stdin/stdout > > I have the following simple test application written in C++, that just > echoes back the stdin. It works fine running from the command line: > > #include > #include > > int main (int argc, char * const argv[]) { > int currenttemp = 0; > int settemp = 0; > char* str; > > while(currenttemp < 500){ > gets(str); > sscanf(str, ">%d", &settemp); > currenttemp = settemp; > printf("<%d\n", currenttemp++); > } > return 0; > } > > ###################################################### > Then I have the following python code. A listener thread that waits > for the output of test and the main part that creates the subprocess > Popen object, passes it to the thread and then sends user input to the > subprocess test. > > > import subprocess > import os, sys > from threading import * > import time > > class TempXListen(Thread): > """ thread to listen for incomming > messages and put them onto a > shared queue, no time lost processing incoming lines > """ > def __init__(self, channel): > """ connect internal response queue > to external queue > """ > Thread.__init__(self) > self.setDaemon(True) > self._channel = channel > self.start() > > def run(self): > """ listening loop > reads line off of input source > puts the line into the response Q shared with parent > thread > sets event that parent is waiting for to indicate Q has at > least 1 element > """ > while 1: > try: > response = self._channel.stdout.readline() # > read input line > print response > except Exception, e: > print 'Listener Exception: ' + str(e) > > > print "Temp Monitor Test" > tempx = subprocess.Popen('/Users/engineeringadmin/Documents/test/build/ > Debug/test', \ > bufsize=1, stdin=subprocess.PIPE, > stdout=subprocess.PIPE, \ > stderr=subprocess.PIPE) > > print tempx.stderr.readline() > > listener = TempXListen(tempx) > while 1: > data = sys.stdin.readline() > if data != '': > data = '>' + data + '\n' > tempx.stdin.write(data) > print data > time.sleep(1) > > > ############################################################### > When I run it this is the output: > > Temp Monitor Test > warning: this program uses gets(), which is unsafe. > > 45 > >> 45 >> > > ################################################################ > The subprocess is opened, because the warning is coming off of the > test applications stderr, but nothing else seems to go in or out. I've > been looking at a lot of examples and a lot of different postings, and > can't see any mistakes in my use of subprocess. I would really > appreciate it if somebody could see where I am going wrong. > > Thank you, > Nik > > -- Gal Diskin -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Sat Jul 14 00:01:56 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 14 Jul 2007 06:01:56 +0200 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: <4697d9f0$0$7614$426a74cc@news.free.fr> Chris Carlen a ?crit : > Hi: > > From what I've read of OOP, I don't get it. I have also found some > articles profoundly critical of OOP. I tend to relate to these articles. > > However, those articles were no more objective than the descriptions of > OOP I've read in making a case. Ie., what objective > data/studies/research indicates that a particular problem can be solved > more quickly by the programmer, or that the solution is more efficient > in execution time/memory usage when implemented via OOP vs. procedural > programming? None. Definitively. wrt/ developper time and memory, it's mostly a matter of fit-your-brains. If it does, you'll find it easier, else choose another programming style. wrt/ cpu time and memory, and using 'low-level' languages (C/C++/Pascal etc) OO is usually worse than procedural for simple programs. For more complex ones, I'd say it tends to converge since these programs, when written procedurally, usually rely on many abstraction/indirection layers. > The problem for me is that I've programmed extensively in C and .asm on > PC DOS way back in 1988. Then didn't program for nearly 10 years during > which time OOP was popularized. Starting in 1999 I got back into > programming, but the high-level-ness of PC programming and the > completely foreign language of OOP repelled me. My work was in analog > and digital electronics hardware design, so naturally I started working > with microcontrollers in .asm and C. Most of my work involves low-level > signal conditioning and real-time control algorithms, so C is about as > high-level as one can go without seriously loosing efficiency. You may still want to have a look on some more functional languages like Haskell, OCaml or Erlang. But if you find OO alien, I doubt you'll have a strong feeling for functional programming. > The > close-to-the-machine-ness of C is ideal here. This is a realm that I > truly enjoy and am comfortable with. > > Hence, being a hardware designer rather than a computer scientist, I am > conditioned to think like a machine. I think this is the main reason > why OOP has always repelled me. OTOH, OO is about machines - at least as conceveid by Alan Key, who invented the term and most of the concept. According to him, each object is a (simulation of) a small machine. > Perhaps the only thing that may have clicked regarding OOP is that in > certain cases I might prefer a higher-level approach to tasks which > involve dynamic memory allocation. While OO without automatic memory management can quickly become a major PITA, OO and GC are two orthogonal concepts - some languages have builtin support for OO but nothing specific for memory management (ObjectPascal, C++, ObjectiveC), and some non-OO languages do have builtin memory management (mostly but not only in the functional camp). > If I don't need the execution > efficiency of C, then OOP might produce working results faster by not > having to worry about the details of memory management, pointers, etc. It's not of feature of OO per se. But it's clear that not having (too much) to worry about memory management greatly enhance productivity. > But I wonder if the OOP programmers spend as much time creating classes > and trying to organize everything into the OOP paradigm as the C > programmer spends just writing the code? Don't you design your programs ? AFAICT, correct design is not easier with procedural programming. Now to answer your question, I'd say it depends on your experience of OO, and of course of the kind of OO language you're using. With declaratively statically typed languages - like C++, Java etc - you are forced into a lot of upfront design (way too much IMHO). Dynamic languages like Smalltalk, Python or Ruby are much more lightweight in this area, and tend to favor a much more exploratory style - sketch a quick draft on a napkin, start coding, and evolve the design while you're coding. And FWIW, Python doesn't *force* you into OO - while you'll be *using* objects, you can write most of your code in a procedural way, and only "fall down" into OO for some very advanced stuff. > Ultimately I don't care what the *name* is for how I program. I just > need to produce results. Indeed !-) > So that leads back to objectivity. I have a > problem to solve, and I want to find a solution that is as quick as > possible to learn and implement. > > Problem: > > 1. How to most easily learn to write simple PC GUI programs GUI are one of the best (and more successfull) application of OO - and as a matter of fact, even GUI toolkits implemented in plain C tend to take an OO approach (GTK+ being a clear example, but even the old Pascal/C Mac GUI API does have a somewhat "object based" feeling). > that will > send data to remote embedded devices via serial comms, and perhaps > incorporate some basic (x,y) type graphics display and manipulation > (simple drawing program). Data may result from user GUI input, or from > parsing a text config file. Solution need not be efficient in machine > resource utilization. Emphasis is on quickness with which programmer > can learn and implement solution. So what you want is an hi-level, easy to learn language with a rich collection of libraries. The Goodnews(tm) is that Python is one of the possible answers. > 2. Must be cross-platform: Linux + Windows. Idem. You can even add most unices and MacOS X to the list. > This factor can have a big > impact on whether it is necessary to learn a new language, or stick with > C. If my platform was only Linux I could just learn GTK and be done > with it. I wouldn't be here in that case. > > Possible solutions: > > Form 1: Use C and choose a library that will enable cross-platform GUI > development. > > Pro: Don't have to learn new language. > Con: Probably will have difficulty with cross-platform implementation > of serial comms. This will probably need to be done twice. This will > waste time. Con: C is a low-level language (not a criticism - it has been designed so), which greatly impact productivity. Con: the only serious C (not++) cross-platform GUI toolkit I know is GTK+, which is less cross-platform than wxWidgets, and *is* OO. > Form 2: Use Python and PySerial and TkInter or wxWidgets. I'd probably go for wxWidgets. > Pro: Cross-platform goal will likely be achieved fully. Very likely. There are a couple of things to take care of, but nothing close to what you'd have to do in C. > Have a > programmer nearby with extensive experience who can help. > Con: Must learn new language and library. Yes, obviously. The (other) GoodNews(tm) is that, according to most estimations, an experimented programmer can become productive in Python in a matter of weeks at worst (some manage to become productive in a few days). This won't mean you'll master the language and use it at its best, but don't worry, you'll get things done, and perhaps in less time than with C. > Must possibly learn a > completely new way of thinking (OOP) Not necessarly. While Python is OO all the way down - meaning that everything you'll work with will be an object (functions included) -, it doesn't *force* you into OO (IOW : you don't have to define classes to write a Python program). You can as well use a procedural - or even somewhat functional - approach, and most Python programs I've seen so far are usually a mix of the three. > not just a new language syntax. You forgot one of the most important part of a language : idioms. And it's definitively *not* idiomatic in Python to use classes when a simpler solution (using plain functions and modules) is enough. > This might be difficult. Not necessarily that much. > Form 3: Use LabVIEW > > Pro: I think that the cross-platform goal can be met. > Con: Expensive. I would prefer to use an Open Source solution. But > that isn't as important as the $$$. I have also generally found the 2D > diagrammatical programming language of "G" as repelling as OOP. I > suspect that it may take as much time to learn LabVIEW as Python. I don't have much knowledge of LabVIEW so I can't comment on this. But I remember a thread here about G, and I guess you'll find Python much more familiar - even if you'll need some 'thinking adjustment' to grok it. > In > that case the time spent on Python might be better spent since I would > be learning something foundational as opposed to basically just learning > how to negotiate someone's proprietary environment and drivers. IMHO, the biggest gain (in learning Python vs LabVIEW) is that you'll add a very valuable tool to your toolbox - the missing link between C and shell scripts. > > Comments appreciated. > HTH From kimiraikkonen85 at gmail.com Sun Jul 1 15:37:17 2007 From: kimiraikkonen85 at gmail.com (kimiraikkonen) Date: Sun, 01 Jul 2007 12:37:17 -0700 Subject: The best platform and editor for Python In-Reply-To: References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> Message-ID: <1183318637.021496.185990@k29g2000hsd.googlegroups.com> On Jul 1, 10:30 pm, "S?nmez Kartal" wrote: > Hello, > > Emacs is the best for anything for me. Some people prefers Eclipse > with PyDev extension. > > Build some real world applications with Python. Pick what do you need > from SourceForge or similar one then write it. If it is something you > need then you probably will make it more special then you found and > this will take you to the more coding and more... > > By the way, thanks for winning Magny Cours grand prix Kimi... :-P > > On 7/1/07, kimiraikkonen wrote: > > > > > Hi, > > For experienced with Pyhton users, which developing software and > > enviroment would you suggest for Pyhton programming? Compiler+Editor > > +Debugger. > > > Also what are your suggestions for beginners of Pyhton programming? > > > Thank you. > > > -- > >http://mail.python.org/mailman/listinfo/python-list- Hide quoted text - > > - Show quoted text - Thank you for the suggestions. I'd prefer a GUI-based, helpful and easy-implemention skilled enviroment. Tesekkurler Sayin Kartal :-) From george.sakkis at gmail.com Thu Jul 26 17:20:18 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Thu, 26 Jul 2007 21:20:18 -0000 Subject: is_iterable function. In-Reply-To: References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> <5uNpi.36822$G23.3430@newsreading01.news.tds.net> <5gs35iF3gbvuoU1@mid.uni-berlin.de> Message-ID: <1185484818.900893.213420@l70g2000hse.googlegroups.com> On Jul 26, 2:56 pm, Neil Cerutti wrote: > On 2007-07-26, Marc 'BlackJack' Rintsch wrote: > > > > > On Thu, 26 Jul 2007 15:02:39 +0000, Neil Cerutti wrote: > > >> Based on the discussions in this thread (thanks all for your > >> thoughts), I'm settling for: > > >> def is_iterable(obj): > >> try: > >> iter(obj).next() > >> return True > >> except TypeError: > >> return False > >> except KeyError: > >> return False > > >> The call to iter will fail for objects that don't support the > >> iterator protocol, and the call to next will fail for a > >> (hopefully large) subset of the objects that don't support the > >> sequence protocol. > > > And the `next()` consumes an element if `obj` is not > > "re-iterable". > > Crap. > > So how best to imlement deeply_mapped? > > The following still breaks for objects that don't provide > __iter__, do provide __getitem__, but don't support the sequence > protocol. That's not the only problem; try a string element to see it break too. More importantly, do you *always* want to handle strings as iterables ? The best general way to do what you're trying to is pass is_iterable() as an optional argument with a sensible default, but allow the user to pass a different one that is more appropriate for the task at hand: def is_iterable(obj): try: iter(obj) except: return False else: return True def flatten(obj, is_iterable=is_iterable): if is_iterable(obj): for item in obj: for flattened in flatten(item, is_iterable): yield flattened else: yield obj from functools import partial flatten_nostr = partial(flatten, is_iterable=lambda obj: not isinstance(obj,basestring) and is_iterable(obj)) print list(flatten_nostr([1, [[[2, 'hello']], (4, u'world')]])) By the way, it's bad design to couple two distinct tasks: flattening a (possibly nested) iterable and applying a function to its elements. Once you have a flatten() function, deeply_mapped is reduced down to itertools.imap. HTH, George From p.c.j.kleiweg at rug.nl Sun Jul 22 11:15:26 2007 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Sun, 22 Jul 2007 17:15:26 +0200 Subject: split on NO-BREAK SPACE Message-ID: Is this a bug or a feature? Python 2.4.4 (#1, Oct 19 2006, 11:55:22) [GCC 2.95.3 20010315 (SuSE)] on linux2 >>> a = 'a b c\240d e' >>> a 'a b c\xa0d e' >>> a.split() ['a', 'b', 'c\xa0d', 'e'] >>> a = a.decode('latin-1') >>> a u'a b c\xa0d e' >>> a.split() [u'a', u'b', u'c', u'd', u'e'] -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/kleiweg/ls.html From http Sun Jul 1 00:05:21 2007 From: http (Paul Rubin) Date: 30 Jun 2007 21:05:21 -0700 Subject: object references/memory access References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> Message-ID: <7xps3c93b2.fsf@ruckus.brouhaha.com> dlomsak writes: > knowledge of the topic to help. If the above are not possible but you > have a really good idea for zipping large amounts of data from one > program to another, I'd like to hear it. One cheesy thing you might try is serializing with marshal rather than pickle. It won't handle as many object types, and it's not guaranteed interoperable from one Python version to another, but it's potentially faster than pickle. Of course for pickling I presume you're already using cPickle (written in C) instead of Pickle (written in Python). From orsenthil at users.sourceforge.net Wed Jul 4 23:02:56 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Thu, 5 Jul 2007 08:32:56 +0530 Subject: Tkinter toggle a Label Widget based on checkbutton value In-Reply-To: References: Message-ID: <20070705030256.GA3332@gmail.com> * Wojciech Mu?a [2007-07-04 20:13:06]: > O.R.Senthil Kumaran wrote: > > Any suggestions on how can i make this checkbutton effect. > > 1) Press Enable IP, the Label IP should be shown. > > 2) Toggle Enable IP (So that its unset). the Label IP should not be shown. > > > > #!/usr/bin/python > > from Tkinter import * > > root = Tk() > > root.title('something') > > x = StringVar() > > ip = Label(root,text="IP:") > > def display(): > global ip > > if x.get(): > > #ip = Label(root,text="IP:") > > ip.grid(row=3,column=0) > else: > ip.grid_forget() Thanks a lot, that perfectly does the trick. :-) Did not know about grid_forget() earlier. -- O.R.Senthil Kumaran http://uthcode.sarovar.org From http Sun Jul 1 11:33:38 2007 From: http (Paul Rubin) Date: 01 Jul 2007 08:33:38 -0700 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> Message-ID: <7xk5tk87fx.fsf@ruckus.brouhaha.com> Roedy Green writes: > >You cannot accurately compute > >the number of seconds between Nixon's resignation and 1800 UTC today, > >unless you take into account the leap seconds have been occurred > >between then and now. > > There are two valid answers to those questions. In a court of law, > say did some document arrive before deadline, you must use civil > time. Arguing leap seconds would not fly. I'd say if the deadline is "the document must arrive before noon on August 9, 2009", that is civil time, including any leap seconds. We don't know the exact number of seconds until then because there might be some leap seconds that haven't yet been announced. On the other hand if the deadline is "the document must arrive no more than 1 billion seconds after noon on January 20, 2001" that is an exact number of seconds. We don't yet know the exact civil time because we don't know about the leap seconds to come. From iladijas at gmail.com Tue Jul 10 13:47:15 2007 From: iladijas at gmail.com (fynali) Date: Tue, 10 Jul 2007 10:47:15 -0700 Subject: How do I remotely access Scheduled Tasks from Windows XP to Windows Server 2003? In-Reply-To: <1184028678.497589.268020@z28g2000prd.googlegroups.com> References: <1183152711.161151.285960@i13g2000prf.googlegroups.com> <1183226243_18235@sp12lax.superfeed.net> <1184028678.497589.268020@z28g2000prd.googlegroups.com> Message-ID: <1184089635.116203.151890@22g2000hsm.googlegroups.com> On Jul 10, 4:51 am, kj7ny wrote: > On Jun 30, 10:55 am, "Roger Upole" wrote: > > > > > > > "kj7ny" wrote: > > > How can I access and manipulateScheduledTasksin Windows using > > > Python? > > > > I have a Windows XP workstation running Python 2.4.4 using the > > > win32all modules to control the windows services on multiple Windows > > > 2003 servers. It works great. > > > > However, I also need to remotely collect the settings for the > > >scheduledtasks(on those same Windows 2003 servers) and then > > > manipulate those task settings. > > > > At the very least, I need to find out which ones are enabled and then > > > be able to disable and re-enable thosetasksat will. It would be > > > better to be able to also detect the account each task runs as so that > > > I could only disable selectedtasks, but I'll any help I can get. > > > > Thanks, > > > Pywin32 comes with a module that lets you do this, win32com.taskscheduler. > > You can use PyITaskScheduler.SetTargetComputer to accesstaskson remote > > machines. > > > Roger > > > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----http://www.newsfeeds.comThe#1 Newsgroup Service in the World! >100,000 Newsgroups > > ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- > > I FINALLY found taskscheduler (with the help of your post). I found > it under > > ...\Python243\Lib\site-packages\win32comext\taskscheduler > > ... and, there seems to be a /test/ directory with some examples. > Haven't tried them yet, but they should get me started. > > Thanks,- Hide quoted text - > > - Show quoted text - kj7ny, could you post back here to learn from? Thanks. s|a fynali From claird at lairds.us Tue Jul 3 14:12:28 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 3 Jul 2007 18:12:28 +0000 Subject: The best platform and editor for Python References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> Message-ID: In article <1183398645.511107.258700 at n2g2000hse.googlegroups.com>, kimiraikkonen wrote: >Thanks for the replies so far. Also i have to learn: > >What is the most reliable and easy way to start learning Ptyhon? >Books? Trusted code sammples(where?)? . . . Beside answering your direct questions (which others have already done well), I think it's important to alert you (as others have also done, though less directly) that learning and using Python is different from VC++. Python is simply easier than C++; you might well find that a debugger, for example, doesn't feel as essential as it is for you with C++. Books might not be as necessary as they were for C++. I recommend you at least scan the following: , , and . From rschroev_nospam_ml at fastmail.fm Thu Jul 26 10:26:11 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 26 Jul 2007 14:26:11 GMT Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185409845.466642.146410@e9g2000prf.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <82d28c40707251158ibae2f9u70889f01ac45a9f6@mail.gmail.com> <1185402705.421724.3680@x35g2000prf.googlegroups.com> <1185409845.466642.146410@e9g2000prf.googlegroups.com> Message-ID: <7a2qi.16837$o33.391425@phobos.telenet-ops.be> Jeff schreef: > No programming language can fix bad programmers. And if cost is an > issue, www.nearlyfreespeech.net has Python, clisp, and OCaml. But only via CGI, which means every request results in a new instance of the interpreter. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From chowroc.z+l at gmail.com Tue Jul 3 06:11:28 2007 From: chowroc.z+l at gmail.com (Roc Zhou) Date: Tue, 3 Jul 2007 18:11:28 +0800 Subject: A new data structrue in python: Tree Message-ID: <7847e5160707030311j4e590ecdi19d5d83495e3e060@mail.gmail.com> Recently I tried to create a new data structure in python: Tree, by operator overloading. I want it can act as a builtin type, such as list and dict. Luckily the basic definition has been finished now, the document is in the code and unittest. And I have put the HTML doc at: http://crablfs.sourceforge.net/tree.html The source code is in SVN: https://crablfs.svn.sourceforge.net/svnroot/crablfs/caxes/trunk/lib/ the files are tree.py and tree_ut.py. Now I want to get more advices and feedbacks, so I post this mail. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alberto.griggio at gmail.com Mon Jul 30 02:47:40 2007 From: alberto.griggio at gmail.com (Alberto Griggio) Date: Mon, 30 Jul 2007 08:47:40 +0200 Subject: wxGlade: Who knows how to drive this application? References: Message-ID: <200707300646.l6U6k03P029079@dit.unitn.it> > Here are some things I can think of, in no particular order: Thanks! I can't promise I'll take care of all of them (some are nontrivial to implement, and would probably take a lot of time), but this list is definitely valuable (e.g. I can circulate it through the other developers to see if there's any volunteer...) Alberto From steve at holdenweb.com Tue Jul 31 21:44:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 31 Jul 2007 21:44:28 -0400 Subject: Iteration over strings In-Reply-To: <46AFCB8C.9060800@jayloden.com> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> <46AF7A49.3040804@jayloden.com> <46AF8046.7090702@gmx.net> <496954360707311307y7d503b8eybd72795c8e699104@mail.gmail.com> <46AF9B2D.8040501@jayloden.com> <46AF9F55.20105@gmx.net> <46AFA1D9.1010707@gmx.net> <46AFCB8C.9060800@jayloden.com> Message-ID: Jay Loden 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. > In this particular case the documentation is quite explicit about the return value and the documentation for the function runs to almost 400 words. Do you expect *everything* to be in the source? That isn't practical, as documenting everything twice like that makes twice the work when the function changes and the documentation has to be rewritten. > One of the items on my very long TODO list is to submit bug reports for items like the above but it's a long list and I just haven't gotten there yet ;) > All such work will earn the gratitude of the developers. 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 Jul 27 01:24:36 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 27 Jul 2007 07:24:36 +0200 Subject: zip() function troubles References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> Message-ID: Istvan Albert wrote: > I've been debugging the reason for a major slowdown in a piece of > code ... and it turns out that it was the zip function. In the past > the lists that were zipped were reasonably short, but once the size > exceeded 10 million the zip function slowed to a crawl. Note that > there was memory available to store over 100 million items. > > Now I know that zip () wastes lots of memory because it copies the > content of the lists, I had used zip to try to trade memory for speed > (heh!) , and now that everything was replaced with izip it works just > fine. What was really surprising is that it works with no issues up > until 1 million items, but for say 10 million it pretty much goes > nuts. Does anyone know why? is there some limit that it reaches, or is > there something about the operating system (Vista in the case) that > makes it behave like so? > > I've noticed the same kinds of behavior when trying to create very > long lists that should easily fit into memory, yet above a given > threshold I get inexplicable slowdowns. Now that I think about is this > something about the way lists grow when expanding them? > > and here is the code: > > from itertools import izip > > BIGNUM = int(1E7) > > # let's make a large list > data = range(BIGNUM) > > # this works fine (uses about 200 MB and 4 seconds) > s = 0 > for x in data: > s += x > print s > > > # this works fine, 4 seconds as well > s = 0 > for x1, x2 in izip(data, data): > s += x1 > print s > > > # this takes over 2 minutes! and uses 600 MB of memory > # the memory usage slowly ticks upwards > s = 0 > for x1, x2 in zip(data, data): > s += x1 > print s When you are allocating a lot of objects without releasing them the garbage collector kicks in to look for cycles. Try switching it off: import gc gc.disable() try: # do the zipping finally: gc.enable() Peter From http Tue Jul 10 00:40:06 2007 From: http (Paul Rubin) Date: 09 Jul 2007 21:40:06 -0700 Subject: 2**2**2**2**2 wrong? Bug? References: Message-ID: <7xbqek7ty1.fsf@ruckus.brouhaha.com> "Jim Langston" writes: > In Python 2.5 on intel, the statement > 2**2**2**2**2 > evaluates to > >>> 2**2**2**2**2 I get the same number from hugs--why do you think it might be wrong? From markacy at gmail.com Tue Jul 31 03:38:47 2007 From: markacy at gmail.com (markacy) Date: Tue, 31 Jul 2007 07:38:47 -0000 Subject: Directory In-Reply-To: <1185831827.206641.163630@x40g2000prg.googlegroups.com> References: <1185831827.206641.163630@x40g2000prg.googlegroups.com> Message-ID: <1185867527.731345.111720@d55g2000hsg.googlegroups.com> On 30 Lip, 23:43, 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. Hi Rohan, http://diveintopython.org/file_handling/os_module.html Hope this helps, Cheers, Marek From steve at holdenweb.com Mon Jul 16 21:26:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 16 Jul 2007 21:26:37 -0400 Subject: Fetching a clean copy of a changing web page In-Reply-To: References: <1184566190.197725.296610@n60g2000hse.googlegroups.com> Message-ID: John Nagle wrote: > Miles wrote: >> On Jul 16, 1:00 am, John Nagle wrote: >> >>> I'm reading the PhishTank XML file of active phishing sites, >>> at "http://data.phishtank.com/data/online-valid/" This changes >>> frequently, and it's big (about 10MB right now) and on a busy server. >>> So once in a while I get a bogus copy of the file because the file >>> was rewritten while being sent by the server. >>> >>> Any good way to deal with this, short of reading it twice >>> and comparing? >>> >>> John Nagle >> >> Sounds like that's the host's problem--they should be using atomic >> writes, which is usally done be renaming the new file on top of the >> old one. How "bogus" are the bad files? If it's just incomplete, >> then since it's XML, it'll be missing the "" and you should >> get a parse error if you're using a suitable strict parser. If it's >> mixed old data and new data, but still manages to be well-formed XML, >> then yes, you'll probably have to read it twice. > > The files don't change much from update to update; typically they > contain about 10,000 entries, and about 5-10 change every hour. So > the odds of getting a seemingly valid XML file with incorrect data > are reasonably good. > I'm still left wondering what the hell kind of server process will start serving one copy of a file and complete the request from another. Oh, well. 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 Sat Jul 28 17:49:39 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 28 Jul 2007 21:49:39 GMT Subject: this must be a stupid question ... References: <849ad$46abb218$d443bb3a$21452@news.speedlinq.nl> Message-ID: On 2007-07-28, Stef Mientki wrote: > but I can;t find the answer ;-) > > As searching for the '$' sign doesn't work well in the help > files, I can not find out, where is the '$' sign used for. > > If I try to use it in names, I get a compiler error, so it > probably has some special meaning. It means something in regular expressions, namely, the end of the string/line. -- Neil Cerutti From js at js.com Tue Jul 31 13:19:39 2007 From: js at js.com (JS) Date: Tue, 31 Jul 2007 12:19:39 -0500 Subject: Encryption recommendation Message-ID: Can someone help me find the proper way to do AES encryption/decryption using Python? Thanks! From org.python.python-list at pooryorick.com Tue Jul 17 13:53:52 2007 From: org.python.python-list at pooryorick.com (=?utf-8?Q?Poor=20Yorick?=) Date: Tue, 17 Jul 2007 17:53:52 +0000 Subject: install python to custom prefix with custom library directories Message-ID: <20070717175352.9116.qmail@station198.com> Today I needed to install python from source on linux to a custom path. /usr/lib/libtk8.3.so existed, but I wanted python to link to /my/custom/path/lib/libtk8.4.so. I had LDFLAGS set: LDFLAGS="-L/my/custom/path/lib -Wl,-rpath,$base/lib -Wl,--enable-new-dtags" configure looked like this: ./configure --prefix=/my/custom/path/python-2.5.1 --enable-shared but python always linked against /usr/lib/libtk8.3.so instead of libtk8.4.so I ended up modifying setup.py (see below) but there must be a more user-friendly way to do this. Right? Thank you for your time! BTW, I don't have root access on this machine --- setup.py.original 2007-07-17 12:51:27 -04:00 +++ setup.py 2007-07-17 13:21:57 -04:00 @@ -293,10 +293,14 @@ # lib_dirs and inc_dirs are used to search for files; # if a file is found in one of those directories, it can # be assumed that no additional -I,-L directives are needed. + self.compiler.library_dirs.insert(0, + '/my/custom/path/lib') lib_dirs = self.compiler.library_dirs + [ '/lib64', '/usr/lib64', '/lib', '/usr/lib', ] + self.compiler.include_dirs.insert(0, + '/my/custom/path/include') inc_dirs = self.compiler.include_dirs + ['/usr/include'] exts = [] -- Poor Yorick From daniel at zelisko.net Sun Jul 1 13:28:39 2007 From: daniel at zelisko.net (Drex) Date: Sun, 01 Jul 2007 10:28:39 -0700 Subject: how to send files via bluetooth with python to a mobile In-Reply-To: <1183306850.712226.313800@m36g2000hse.googlegroups.com> References: <1183294323.556314.293860@m36g2000hse.googlegroups.com> <1183305873.736724.116680@c77g2000hse.googlegroups.com> <1183306850.712226.313800@m36g2000hse.googlegroups.com> Message-ID: <1183310919.771396.268760@q69g2000hsb.googlegroups.com> Hey, > > I'm not sure but try this: ( py_s60 ) > > >http://sourceforge.net/projects/pyed/ > and also try this: > > http://sourceforge.net/projects/pys60 thanks, but I am affraid this is not what I was looking for. I need to have some library on my pc (linux) that would allow me to transfer a file to a bluetooth mobile phone (the mine doesn't have symbian). I have some programs that allow to do that like for ex. obex_client but I would like to write something similar using python. thanks! regards dz From robert.rawlins at thinkbluemedia.co.uk Wed Jul 18 05:03:34 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 18 Jul 2007 10:03:34 +0100 Subject: Subprocess Poll() to sport Application Crash Message-ID: <029901c7c91a$85b9d6b0$912d8410$@rawlins@thinkbluemedia.co.uk> Hello Guys, I have an application which launches a sub-process using the sub process/Popen module, which seems to work great. However on occasion the launched process will crash, it doesn't appear to full terminate though as when I run a 'top' command from the Linux system the process is still displayed in the list, it just appears to be dormant and the TIME+ for the application stops incrementing. Can I use the poll() method from the sub-process object to test for this? I would love to test it however the crash is so rare it's very difficult to simulate, so thought I'd try and see if anyone has any experience of this. Thanks chaps, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Mon Jul 16 13:55:01 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 16 Jul 2007 10:55:01 -0700 Subject: Python and Tkinter Primer/Tutorial? In-Reply-To: References: <1184525138.178668.274570@22g2000hsm.googlegroups.com> Message-ID: W. Watson wrote: > Thanks for the tips to the posters above. Wow, the Grayson book is $98 > on Amazon. I think I'll see if I can get a library loan! Its an ebook for $25.00: http://www.manning.com/grayson/ James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bignose+hates-spam at benfinney.id.au Fri Jul 13 22:09:55 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 14 Jul 2007 12:09:55 +1000 Subject: Understanding python functions - Instant Python tutorial References: <878x9kkeif.fsf@benfinney.id.au> Message-ID: <87r6nbivm4.fsf@benfinney.id.au> Chris Carlen writes: > Excellent description. This understandable to me since I can > envision doing this with pointers. It would be better if you thought in terms of "refrences". Python names are unlike pointers in that they don't "store" anything. The *only* thing to do with them is refer to an object; don't think of them as a C pointer, because Python names don't need to be (and, indeed, can't) be "de-referenced". > But I have no idea how Python actually implements this. It also > appears that I am being guided away from thinking about it in terms > of internal implementation. Yes. This is a good thing, because Python has multiple implementations that are allowed to differ in their internals where it makes sense to do so. There are some guarantees at a lower level, that you can find in the language reference; but the main advantage of stopping at a certain level of abstraction is that the implementation programmers are free to *change* the implementation underneath that abstraction when it will improve the implementation. Meanwhile, the Python programmer is free to work at the abstraction level provided by the language, and isn't forced to be always mindful of the inner workings if the current implementation. -- \ "To me, boxing is like a ballet, except there's no music, no | `\ choreography, and the dancers hit each other." -- Jack Handey | _o__) | Ben Finney From pollastri at iriti.cnr.it Fri Jul 6 02:27:39 2007 From: pollastri at iriti.cnr.it (Fabrizio Pollastri) Date: Fri, 06 Jul 2007 08:27:39 +0200 Subject: Writing a read only attribute Message-ID: <468DE0DB.3030402@iriti.cnr.it> Hello, it is possible to force in some way a write to a read-only attribute of a python object? In which case? Thanks for any answer. F. Pollastri From kerny404 at gmail.com Mon Jul 2 13:15:42 2007 From: kerny404 at gmail.com (andrea) Date: Mon, 02 Jul 2007 10:15:42 -0700 Subject: Rappresenting infinite In-Reply-To: References: <1182940919.351011.267020@n2g2000hse.googlegroups.com> <1182945569.081290.40870@c77g2000hse.googlegroups.com> <20070628234618.2907b52d@localhost> <20070629004542.31bbc7ac@localhost> Message-ID: <1183396542.991662.230580@g4g2000hsf.googlegroups.com> Mm very interesting thread, for my needs from numpy import inf is more than enough :) From aleax at mac.com Mon Jul 2 22:11:45 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 2 Jul 2007 19:11:45 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> Message-ID: <1i0n0tr.ve0o791347ugyN%aleax@mac.com> Donn Cave wrote: > In article <1i0ikru.1uccqtm1efnzn3N%aleax at mac.com>, > aleax at mac.com (Alex Martelli) wrote: > > > "Dynamic typing is recommended", they conclude, "when programs must be > > as flexible as possible". I recommend reading the Agile Manifesto to > > understand why maximal flexibility is crucial in most real-world > > application programming -- and therefore why, in said real world rather > > than in the more academic circles Dr. Van Roy and Dr. Hadidi move in, > > dynamic typing is generally preferable, and not such a tiny issue as > > they make the difference to be. > > I guess there may be more than one kind of flexibility. The language > I fool around with sometimes that has strong static typing is Haskell. > Though a relatively elementary Haskell programmer (the learning curve > with this language is something you would have to experience to believe), I do have (some of:-) that experience, and am reasonably at ease in Haskell (except when it comes to coding monads, which I confess I still have trouble wrapping my head around). > I feel that the type checking actually helps me program faster. > The compiler's check for structural correctness is after all for my > benefit, and expedites development and maintenance of code, in my > limited experience. The more extensive my changes, the more useful > the type checking is - I'm much more casual about significant code > revision when writing in Haskell, somewhat more casual when writing > in C, and worried when writing Python. Eckel's and Martin's well-known essays on why good testing can replace strict static type checking: Me, I'm always worried about significant code revision _unless I have good tests in place_. Strict static typechecks catch only a small subset of frequent mistakes -- good tests catch a far higher quota. Typechecks do catch some mistakes "faster", but, in my experience on today's machines, that tiny difference is becoming insignificant, particularly when you consider that typechecks typically require whole-program analysis while, as Van Roy and Haridi point out, dynamic typing affords "totally open coding". Alex From bj_666 at gmx.net Wed Jul 11 13:01:03 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Jul 2007 17:01:03 GMT Subject: Simple search and Display system, no need for db? References: <1184119048.302574.141810@w3g2000hsg.googlegroups.com> <5fjab0F3d2eqeU1@mid.uni-berlin.de> <1184172752.996885.253340@m3g2000hsh.googlegroups.com> Message-ID: <5fkgmeF3cu82eU2@mid.uni-berlin.de> On Wed, 11 Jul 2007 16:52:32 +0000, flit wrote: > That seems to be a good idea, but I am afraid the web hosting does not > have the csv modules.. The `csv` module is part of the standard library. Ciao, Marc 'BlackJack' Rintsch From nospam.themindstorm at gmail.com Fri Jul 27 19:29:32 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Fri, 27 Jul 2007 23:29:32 +0000 (UTC) Subject: Relative-importing * References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> <871weth2gg.fsf@benfinney.id.au> Message-ID: Ben Finney wrote in news:871weth2gg.fsf at benfinney.id.au: > rbygscrsepda at gmail.com writes: > >> from . import * >> from .sibiling import * >> from .. import * >> from ..parent_sibling import * >> >> ...and so on. The same error occurs: >> SyntaxError: 'import *' not allowed with 'from .' > > Interesting. I know that 'from foo import *' is frowned on and is > generally worse than importing names explicitly, but I wasn't aware > that it was officialy deprecated. The PEP introducing absolute and > relative imports > doesn't mention it, except as a friendly "import * is *not* an option >:-)" aside. > Well, I may be looking it from the wrong perspective but what is the meaning of : from . import * from .. import ** Import all modules available at that relative path? I am not sure why the other 2 versions are not working, though. ./alex -- .w( the_mindstorm )p. From sjdevnull at yahoo.com Mon Jul 23 04:41:52 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Mon, 23 Jul 2007 01:41:52 -0700 Subject: decorators tutorials In-Reply-To: <1185178383.499234.299850@z24g2000prh.googlegroups.com> References: <1185178383.499234.299850@z24g2000prh.googlegroups.com> Message-ID: <1185180112.321457.73170@n2g2000hse.googlegroups.com> james_027 wrote: > Hi, > > I am learning python by learning django, and I stumble upon decorator > which is very cool, any beginners resources for python decorators, > although I can google it, I just want to get a good tutorial for this > topic. Decorators are just a more concise but less obvious way of calling a defined function on another function. e.g. @my_decorator def foo(): ... is the essentially the same as: def foo(): ... foo=my_decorator(foo) From deets at nospam.web.de Wed Jul 25 18:09:32 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 26 Jul 2007 00:09:32 +0200 Subject: Singleton in Python Cookbook In-Reply-To: References: Message-ID: <5gq00tF3fm71gU1@mid.uni-berlin.de> Alex Popescu schrieb: > Hi all! > > I was reading through Python Cookbook the Singleton recipe. At this moment > I am a bit puzzled as the example in the book is not working resulting in: > > TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of type > > (I haven't presented the original code as I am not sure about copyrights). AFAIK the cookbook is completely found online at ASPN. So no sweat publishing it here. And regarding the problem: is it possible that you forgot to subclass SingleSpam from object? Diez From musiccomposition at gmail.com Tue Jul 24 14:51:46 2007 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 24 Jul 2007 18:51:46 -0000 Subject: wxPython - How to add sorting to a ListCtrl? In-Reply-To: <1185294074.410142.214140@22g2000hsm.googlegroups.com> References: <1185294074.410142.214140@22g2000hsm.googlegroups.com> Message-ID: <1185303106.058223.271000@r34g2000hsd.googlegroups.com> On Jul 24, 11:21 am, Robert Dailey wrote: > Hi, > > I have 3 columns in my list control, each with a different "type" of > data (for example, one column has names, the other has dates, etc). > Can anyone reference a tutorial for solving this issue? I've done my > share of googling to no avail. I need the user to be able to click any > of the column headers and sort the rows of data by that column in > ascending or descending order. There is a mixin for this at wx.lib.mixins.listctrl.ColumnSorterMixin. To learn how to use it, take a look at the wxPython demo which comes with the doc distribution. There's a good example in the ListCtrl demo. > > Thanks for your time. From murali.dhanakoti at gmail.com Mon Jul 2 11:23:07 2007 From: murali.dhanakoti at gmail.com (Murali) Date: Mon, 02 Jul 2007 15:23:07 -0000 Subject: Reading stdout and stderr of an external program Message-ID: <1183389787.481605.111160@k29g2000hsd.googlegroups.com> Hi Python programmers, I need to be able to read the stdout and stderr streams of an external program that I launch from my python script. os.system( 'my_prog' + '>& err.log' ) and was planning on monitoring err.log and to display its contents. Is this the best way to do this? Thanks, Murali. From sbassi at clubdelarazon.org Sun Jul 15 00:15:39 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sun, 15 Jul 2007 01:15:39 -0300 Subject: Can a low-level programmer learn OOP? In-Reply-To: <1184349549.484402.214860@o61g2000hsh.googlegroups.com> References: <1184349549.484402.214860@o61g2000hsh.googlegroups.com> Message-ID: <9e2f512b0707142115i1ec18cedk877b7c142081c5a1@mail.gmail.com> On 7/13/07, Simon Hibbs wrote: > place. At the end of it you'll have a good idea how OOP works, and how > Python works. Learning OOp this way is easy and painless, and what you ... But this tutorial states "I assume you know how object-oriented programming works" -- Sebasti?n Bassi (???????) Diplomado en Ciencia y Tecnolog?a. GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D From info at thegrantinstitute.com Tue Jul 10 06:12:42 2007 From: info at thegrantinstitute.com (Anthony Jones) Date: 10 Jul 2007 03:12:42 -0700 Subject: Professional Grant Proposal Writing Workshop (September 2007: Simon Fraser University) Message-ID: <20070710031241.05E7F30B4FDC2BCD@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From deets at nospam.web.de Wed Jul 11 12:45:38 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 11 Jul 2007 18:45:38 +0200 Subject: stripping the first byte from a binary file References: <1184063032.195000.25880@i13g2000prf.googlegroups.com> <1184115964.912526.273780@e16g2000pri.googlegroups.com> <1184148168.639675.85900@a26g2000pre.googlegroups.com> <4694B01A.30107@web.de> <1184153416.798767.163740@d55g2000hsg.googlegroups.com> <5fk3geF3b8794U1@mid.uni-berlin.de> <1184164948.266014.178760@g4g2000hsf.googlegroups.com> Message-ID: <5fkfpjF37im5qU1@mid.uni-berlin.de> Alex Popescu wrote: > On Jul 11, 4:15 pm, "Diez B. Roggisch" wrote: >> > Forgive my newbie ignorance, but I am wondering why the other method >> > would not work? I mean it may not be very safe, >> > but I guess it may perform a lot better, than having to read the whole >> > file just to cut out the first byte. >> >> Because seeking is not moving? Shifting data bytewise isn't something >> that is supported by the underlying OS filesystems, and thus not >> supported. But replacing bytes with others is. Which seek is for. >> >> Diez > > As far as I know seek is just about positioning and nothing else. It is. > So, in fact the problem boils down to os support for deleting a bytes. Which there isn't, as I and several others pointed out. And "replacing" is not removing. Diez From jmoy.matecon at gmail.com Fri Jul 13 01:07:14 2007 From: jmoy.matecon at gmail.com (Jyotirmoy Bhattacharya) Date: Fri, 13 Jul 2007 05:07:14 -0000 Subject: diferent answers with isalpha() In-Reply-To: <1184285142.547758.57760@22g2000hsm.googlegroups.com> References: <1184285142.547758.57760@22g2000hsm.googlegroups.com> Message-ID: <1184303234.474610.186270@e9g2000prf.googlegroups.com> On Jul 13, 5:05 am, n... at salgado.ws wrote: > In Idle when I do print '?'.isalpha() I get True. When I make and > execute a script file with the same code I get False. > > Why do I have diferent answers ? Non-ASCII characters in ordinary (8-bit) strings have all kinds of strangeness. First, the answer of isalpha() and friends depends on the current locale. By default, Python uses the "C" locale where the alphabetic characters are a-zA-z only. To set the locale to whatever is the OS setting for the current user, put this near the beginning of your script: import locale locale.setlocale(locale.LC_ALL,'') Apparently IDLE does this for you. Hence the discrepancy you noted. Second, there is the matter of encoding. String literals like the one you used in your example are stored in whatever encoding your text editor chose to store your program in. If it doesn't match the encoding using by the current locale, once again the program fails. As I see it, the only way to properly handle characters outside the ASCII set is to use Unicode strings. From p.c.j.kleiweg at rug.nl Sun Jul 22 15:13:02 2007 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Sun, 22 Jul 2007 21:13:02 +0200 Subject: split on NO-BREAK SPACE In-Reply-To: References: Message-ID: Carsten Haese schreef op de 22e dag van de hooimaand van het jaar 2007: > On Sun, 2007-07-22 at 17:44 +0200, Peter Kleiweg wrote: > > > It's a feature. See help(str.split): "If sep is not specified or is > > > None, any whitespace string is a separator." > > > > Define "any whitespace". > > Any string for which isspace returns True. Define white space to isspace() > > Why is it different in and ? > > >>> '\xa0'.isspace() > False > >>> u'\xa0'.isspace() > True Here is another "space": >>> u'\uFEFF'.isspace() False isspace() is inconsistent > For byte strings, Python doesn't know whether 0xA0 is a whitespace > because it depends on the encoding whether the number 160 corresponds to > a whitespace character. For unicode strings, code point 160 is > unquestionably a whitespace, because it is a no-break SPACE. I question it. And so does the sre module: \s Matches any whitespace character; equivalent to [ \t\n\r\f\v] Where is the NO-BREAK SPACE in there? > > Why does split() split when it says NO-BREAK? > > Precisely. It says NO-BREAK. It doesn't say NO-SPLIT. That is a stupid answer. -- Peter Kleiweg L:NL,af,da,de,en,ia,nds,no,sv,(fr,it) S:NL,de,en,(da,ia) info: http://www.let.rug.nl/kleiweg/ls.html From bignose+hates-spam at benfinney.id.au Thu Jul 26 20:31:30 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 27 Jul 2007 10:31:30 +1000 Subject: code indentation References: <1185297657.186852.136950@k79g2000hse.googlegroups.com> <87lkd5jt83.fsf@benfinney.id.au> <1185357861.989194.117000@r34g2000hsd.googlegroups.com> <1185387723.155661.311510@b79g2000hse.googlegroups.com> <1185478366.910475.110490@19g2000hsx.googlegroups.com> Message-ID: <87ejiuhel9.fsf@benfinney.id.au> vedrandekovic at v-programs.com writes: > here is my failed example of try with string: > > kl="n=90;if n==90:print'kajmakimar'" > > for line in kl.split(";"): > li=[] > m=li.append(line) > if line.endswith(':'): > m.append("\n\t\t\t\t\t\t\t\t") > print m The list.append method returns None. It appends the item to the list. >>> lines = [] >>> result = lines.append("foo") >>> print result None So, there's no need to do anything with the result of append() -- just continue using the list object. >>> print lines ['foo'] >>> lines.append("bar") >>> print lines ['foo', 'bar'] -- \ "There are only two ways to live your life. One is as though | `\ nothing is a miracle. The other is as if everything is." -- | _o__) Albert Einstein | Ben Finney From skawanagi at gmail.com Tue Jul 17 08:40:38 2007 From: skawanagi at gmail.com (mosi) Date: Tue, 17 Jul 2007 12:40:38 -0000 Subject: a=0100; print a ; 64 how to reverse this? In-Reply-To: <1184673934.660465.228280@i13g2000prf.googlegroups.com> References: <1184670575.205759.115360@i13g2000prf.googlegroups.com> <1184673934.660465.228280@i13g2000prf.googlegroups.com> Message-ID: <1184676038.231330.115220@e16g2000pri.googlegroups.com> Thank you, this is great, I thought that this should be standard in python 2.4 or 2.5 or in some standard library (math ???) Didn`t find anything. On Jul 17, 2:05 pm, John Machin wrote: > On Jul 17, 9:09 pm, mosi wrote: > > > > > Problem: > > how to get binary from integer and vice versa? > > The simplest way I know is: > > a = 0100 > > a > > 64 > > > but: > > a = 100 (I want binary number) > > does not work that way. > > > a.__hex__ exists > > a.__oct__ exists > > > but where is a.__bin__ ??? > > > What`s the simplest way to do this? > > Thank you very much. > > Here's a sketch; I'll leave you to fill in the details -- you may wish > to guard against interesting input like b < 2. > > >>> def anybase(n, b, digits='0123456789abcdef'): > > ... tmp = [] > ... while n: > ... n, d = divmod(n, b) > ... tmp.append(digits[d]) > ... return ''.join(reversed(tmp)) > ...>>> anybase(1234, 10) > '1234' > >>> anybase(7, 2) > '111' > >>> [anybase(64, k) for k in range(2, 17)] > > ['1000000', '2101', '1000', '224', '144', '121', '100', '71', '64', > '59', '54', '4c', '48', '44', '40'] > > > > HTH, > John From sundol at sfc.keio.ac.jp Fri Jul 27 09:35:02 2007 From: sundol at sfc.keio.ac.jp (Hyunchul Kim) Date: Fri, 27 Jul 2007 22:35:02 +0900 Subject: [python-list] pdf read & write Message-ID: <1185543302.11085.12.camel@hckim-desktop> Dear all, How can I read a pdf file and add invisible comment? I want to make a script which read a pdf file and add tags inside the file invisibly. Then, I will make a script for managing tags of given pdf files. I know "referencer" can manage tags for pdf file but it seems store tag information to additional file outside pdf file. Any suggestion are welcome. Best, Hyunchul Kim From arkanes at gmail.com Fri Jul 6 08:36:04 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 6 Jul 2007 07:36:04 -0500 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <9uRhi.17027$xk5.14289@edtnps82> Message-ID: <4866bea60707060536m76c3040dm9867911ffba0725d@mail.gmail.com> On 7/5/07, Douglas Alan wrote: > "Chris Mellon" writes: > > >> Some people here have been arguing that all code should use "with" to > >> ensure that the files are closed. But this still wouldn't solve the > >> problem of the large data structures being left around for an > >> arbitrary amount of time. > > > I don't think anyone has suggested that. Let me be clear about *my* > > position: When you need to ensure that a file has been closed by a > > certain time, you need to be explicit about it. When you don't care, > > just that it will be closed "soonish" then relying on normal object > > lifetime calls is sufficient. This is true regardless of whether > > object lifetimes are handled via refcount or via "true" garbage > > collection. > > But it's *not* true at all when relying only on a "true GC"! Your > program could easily run out of file descriptors if you only have a > real garbage collector and code this way (and are opening lots of > files). This is why destructors are useless in Java -- you can't rely > on them *ever* being called. In Python, however, destructors are > quite useful due to the refcounter. > Sure, but thats part of the general refcounting vs GC argument - refcounting gives (a certain level of) timeliness in resource collection, GC often only runs under memory pressure. If you're saying that we should keep refcounting because it provides better handling of non-memory limited resources like file handles, I probably wouldn't argue. But saying we should keep refcounting because people like to and should write code that relies on implicit scope level object destruction I very strongly argue against. > > Relying on the specific semantics of refcounting to give > > certain lifetimes is a logic error. > > > > For example: > > > > f = some_file() #maybe it's the file store for a database implementation > > f.write('a bunch of stuff') > > del f > > #insert code that assumes f is closed. > > That's not a logic error if you are coding in CPython, though I agree > that in this particular case the explicit use of "with" would be > preferable due to its clarity. > I stand by my statement. I feel that writing code in this manner is like writing C code that assumes uninitialized pointers are 0 - regardless of whether it works, it's erroneous and bad practice at best, and actively harmful at worst. From aisaac at american.edu Tue Jul 3 10:35:50 2007 From: aisaac at american.edu (Alan Isaac) Date: Tue, 03 Jul 2007 14:35:50 GMT Subject: allow scripts to use .pth files? Message-ID: Suppose I have a directory `scripts`. I'd like the scripts to have access to a package that is not "installed", i.e., it is not on sys.path. On this list, various people have described a variety of tricks they use, but nobody has proposed a pretty way to allow this. I am therefore assuming there is not one. (?) How about allowing a `scripts.pth` file in such a `scripts` directory, to work like a path configuration file? (But to be used only when __name__=="__main__".) Drawbacks? Alan Isaac From ironfroggy at gmail.com Thu Jul 19 00:22:10 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Thu, 19 Jul 2007 00:22:10 -0400 Subject: Charlotte Python Group In-Reply-To: <469E1765.1010801@freakmail.de> References: <76fd5acf0707180544y497bfd42t6b699b8f62b6b4e5@mail.gmail.com> <469E1765.1010801@freakmail.de> Message-ID: <76fd5acf0707182122h769e0ffem6088bc6677d0addd@mail.gmail.com> Holy crap, did I forget to mention the state and country? I could be a moron, at times. This would be Charlotte, North Carolina, the United States of America. On 7/18/07, Wildemar Wildenburger wrote: > Calvin Spealman wrote: > > I am looking to start a meetup in or near Charlotte. I already have a > > couple people interested, and I see some folks subscribing to new > > python groups on meetup. If I can find a few more people, it could be > > worth it. > > > > Is anyone in the area and interested in a group? Anyone who might want > > to do a talk, about anything interesting? Does anyone have suggestions > > of a good place in Charlotte to meet, maybe at a cafe with enough > > room? I'm from up in the Kannapolis/Concord area myself, so I'm not > > familiar with many places in the city proper, but I see a few > > possibilities at Google Maps. > > > > > Hey, can you get a little less specific, please? I can just about make > out what place you're talking about. This one > , > right? > > /W (your personal know-nothing nitpicker) > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From dennis.varghese at wipro.com Fri Jul 20 11:35:59 2007 From: dennis.varghese at wipro.com (pycraze) Date: Fri, 20 Jul 2007 08:35:59 -0700 Subject: NTLM APS python version 0.98 Message-ID: <1184945759.346727.190650@j4g2000prf.googlegroups.com> Hi , I am working on NTLM (Windows NT Lan Manager )APS (Authentication Proxy Server ) , to port to C language . I am using ethereal to monitor the packets sent between client and server . NTLM is a MS proprietary protocol designed so that will allow authentication only from MS browsers . This proprietary was cracked and code was written in python by Rozmanov . The link to the source pool about NTLM is http://www.innovation.ch/personal/ronald/ntlm.html Have any one worked extensively with NTLM APS python package 0.98 ? NTLM APS have a 6 step process :- (C) - client (S)- server 1: C --> S GET ... 2: C <-- S 401 Unauthorized WWW-Authenticate: NTLM 3: C --> S GET ... Authorization: NTLM 4: C <-- S 401 Unauthorized WWW-Authenticate: NTLM 5: C --> S GET ... Authorization: NTLM 6: C <-- S 200 Ok After step 6 client must connect to server . But when i run NTLM APS and watch the packets sent b/w client and server in ethereal , i see that client does not recieve 200 Ok at Step 6 , but receives 401 Unauthorized . After this i get a dialog box which requests me to enter my user name and password . I enter the credentials and then the server authorizes the client . I am sorry that i cannot give more info on this . I can send the saved page log from ethereal . That will give a very good idea . As per theory , it is only a 6 step process . I am puzzled regarding this . thanks , dennis From zyzhu2000 at gmail.com Wed Jul 25 20:58:10 2007 From: zyzhu2000 at gmail.com (beginner) Date: Thu, 26 Jul 2007 00:58:10 -0000 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <7xzm1kqw89.fsf@ruckus.brouhaha.com> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <7xzm1kqw89.fsf@ruckus.brouhaha.com> Message-ID: <1185411490.250673.165570@z28g2000prd.googlegroups.com> On Jul 25, 11:33 am, Paul Rubin wrote: > beginner writes: > > I know the * operator. However, a 'partial unpack' does not seem to work. > > A few other posters have mentioned ways around this, but you might ask > yourself what coding situation makes you want to do this stuff in the > first place. I won't say there's never a reason for it, but a lot of > times, a list containing a mixture of scalars and lists/tuples is a > sign that your underlying data representation is contorted. Things > are logically single values or they are logically lists of values, and > that mixed representation is often a sign that the item logically > should be a list, and you're hairing up the program with special > treatment of the case where the list has exactly one element. > > I.e. instead of [[1,2,], 3, [5,6,]] maybe you really want > [[1,2,], [3,], [5,6]] without the special treatment and flattening. Very good question. It is well possible that the problem is my programming style. I am new to python and am still developing a style that works for me. A lot of things that work in perl does not seem to work. Unpacking and flattening are just two examples. I need nested lists to represent nested records in a script. Since the structure of the underlying data is nested, I think it is probably reasonable to represent them as nested lists. For example, if I have the below structure: Big Record Small Record Type A Many Small Record Type B Small Record Type C It is pretty natural to use lists, although after a while it is difficult to figure out the meaning of the fields in the lists. If only there were a way to 'attach' names to members of the list. For the unpacking question, I encountered it when working with list comprehensions. For example: [ f(*x,1,2) for x in list] is difficult to do if I don't want to expand *x to x[0]..x[n]. There are usually 7-10 items in the list and it is very tedious and error prone. The second problem is from a nested list comprehension. I just needed something to flatten the list at the moment. I am still forming my way to do things in python via trial and error. It is well possible that this is not the natural way to do things. From the.mindstorm.mailinglist at gmail.com Thu Jul 5 05:16:29 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Thu, 05 Jul 2007 02:16:29 -0700 Subject: MethodType/FunctionType and decorators In-Reply-To: <1183623479.913816.301230@g4g2000hsf.googlegroups.com> References: <1183589529.198694.109440@m36g2000hse.googlegroups.com> <1183591053.434640.119550@o61g2000hsh.googlegroups.com> <1i0qoq9.u1fu2g63fkmxN%aleax@mac.com> <1183623479.913816.301230@g4g2000hsf.googlegroups.com> Message-ID: <1183626989.983470.94950@o61g2000hsh.googlegroups.com> On Jul 5, 11:17 am, Michele Simionato wrote: > On Jul 5, 3:41 am, a... at mac.com (Alex Martelli) wrote: > > > > > Alex already explained everything beautifully. I will just add a link > to > the definite guide to descriptors:http://users.rcn.com/python/download/Descriptor.htm > > Michele Simionato > > (who spent lot of brain cycles studying descriptors *before* that > guide was written :-() Guys, I appreciate a lot your help and explanations. It looks like I have to read/play a bit more as some of the terms/ideas are pretty new to me (coming to Python with a 10 years Java bag, and only with a small dynlang bag - Ruby, Perl). Once again thanks, ./alex -- .w( the_mindstorm )p. From seerdecker at gmail.com Mon Jul 16 19:35:45 2007 From: seerdecker at gmail.com (seerdecker at gmail.com) Date: Mon, 16 Jul 2007 16:35:45 -0700 Subject: Semantics of file.close() Message-ID: <1184628945.314844.53300@k79g2000hse.googlegroups.com> Hello, I'm a Python beginner and I'm trying to open, write and close a file in a correct manner. I've RTFM, RTFS, and I've read this thread: http://groups.google.ca/group/comp.lang.python/browse_thread/thread/73bbda2c920521c/98c731229d86b01d?lnk=st&q=python+file+explicit+close&rnum=1&hl=en#98c731229d86b01d I still cannot figure out the semantic of file.close(). As far as I can tell it is undocumented. Explanations and example follow. There are two occasions where you have to close a file: 1) At the end of a series of writes to the file, to ensure that all data is written correctly to disk. In this case I want file.close() to throw an exception if the file cannot be written (e.g. when there is no more disk space). 2) To clean up after an error occurred during the processing. In that case I just want to close the file handle cleanly. I do NOT want an exception to be thrown (e.g. in my finally clause). Man page of fclose() -- in C: fclose - close a stream Upon successful completion 0 is returned. Otherwise, EOF is returned and the global variable errno is set to indicate the error. In either case any further access (including another call to fclose()) to the stream results in undefined behaviour. The man page of fclose() clearly indicates that fclose() may fail. I've already tested under Linux that fwrite() indicates success even if the disk is full; the error is ONLY reported when close() is called. Consider the following example: file1 = None; file2 = None; try: file1 = open("foo1.txt", "wb"); file2 = open("foo2.txt", "wb"); file1.close(); file2.close(); finally: if file1: file1.close(); if file2: file2.close(); How do I ensure that the close() methods in my finally clause do not throw an exception? Thanks a lot, Laurent Birtz From rbonvall at gmail.com Fri Jul 20 19:44:37 2007 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Fri, 20 Jul 2007 23:44:37 -0000 Subject: Sorting dict keys In-Reply-To: <1184974474.000773.15370@k79g2000hse.googlegroups.com> References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> <1184974474.000773.15370@k79g2000hse.googlegroups.com> Message-ID: <1184975077.756128.234390@m3g2000hsh.googlegroups.com> On 20 jul, 19:34, montyphy... at gmail.com wrote: > copy.copy returns a new object: > > >>> copy.copy(a.keys()) > > [1,2,3] > > Then why doesn't copy.copy(a.keys()).sort() work?? It works, but you don't notice it, because you don't save a reference to the new list. Try this: c = copy.copy(a.keys()) c.sort() -- Roberto Bonvallet From paddy3118 at googlemail.com Sat Jul 21 04:00:41 2007 From: paddy3118 at googlemail.com (Paddy) Date: Sat, 21 Jul 2007 08:00:41 -0000 Subject: dejagnu equivalent In-Reply-To: References: Message-ID: <1185004841.636298.12450@k79g2000hse.googlegroups.com> On Jul 18, 7:05 am, "Rustom Mody" wrote: > Does anyone know if a dejagnu equivalent exists for python? > [Dejagnu is in tcl] Maybe http://www.codesourcery.com/public/qmtest/whitepaper.pdf ? I have not used it though. From stesch at no-spoon.de Sat Jul 28 21:14:26 2007 From: stesch at no-spoon.de (Stefan Scholl) Date: Sun, 29 Jul 2007 03:14:26 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> <0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de> <0T49iehiIt1hNv8%stesch@parsec.no-spoon.de> <46AB8194.2060906@web.de> <0T49il77ItapNv8%stesch@parsec.no-spoon.de> <0T49ish0ItfaNv8%stesch@parsec.no-spoon.de> Message-ID: <1T49jcp3Iu8vNv8%stesch@parsec.no-spoon.de> Michael L Torrie wrote: > Stefan Scholl wrote: >> Don't let the subject line fool you. I'm OK with cStringIO. The >> thread is now about xml.sax's parseString(). > > Giving you the benefit of the doubt here, despite the fact that Stefan > Behnel has state this over and over again and you just haven't listened. Speaking of over and over again ... > xml.sax's use of parseString() is exactly correct. xml.sax should > *never* parse python unicode strings as by definition XML must be > encoded as a *byte stream*, which is what a python string is. I don't care about the definition of XML at this point of the program. http://docs.python.org/lib/module-xml.sax.html calls parseString() a convenience function. This is Python. Python has a class named unicode. Its literals look like strings. The base class is basestring. xml.sax belongs to Python. Batteries included. parseString() is in Python. It's not parseString() that tells me something is wrong with the parameter. It's cStringIO, which is used on platforms where it is available. On other platforms no exceptions are thrown, because then StringIO is used, which behaves in Python 2.4 and Python 2.5 the same, regarding unicode strings. Other libraries like LXML (not included) parse unicode strings. And these are two additional lines in my code now: if isinstance(string, unicode): string = string.encode("utf-8") > A python /unicode/ string could be held internally in any number of > ways, 2, 3, 4, or even 8 bytes per character if the implementation > demanded it (a bit contrived, I admit). Since the xml parser is only > ever intended to parse *XML*, why should it ever know what to do with > python unicode strings, which could be stored any number of ways, making > byte-parsing impossible. xml.sax is no external parser. The program doesn't have to communicate with the outside world at this point of execution. The Python programm calls a Python function of a Python class and passes a Python unicode string as parameter. XML parsers only have to support few encodings. But nobody has something against it when they support more than that. A Python convenience function isn't broken when it allows Python unicode strings. The behavior of cStringIO (the original topic of this thread) is correct and documented. parseString() uses the old idiom where cStringIO is imported as StringIO, when available. Despite the fact that they behave differently. In my personal opinion: If parseString() shouldn't support unicode strings, then it should check for it and throw a meaningful exception. At the moment the code just looks as if someone has overlooked the fact that unicode strings (with non-ascii characters in it) cause a problem. Missing test? > So your code is faulty in its assumptions, not xml.sax. As I said in the conclusion, a few messages before: Undocumented, implementation dependent behavior. Or maybe just a bug, considering the following on http://docs.python.org/lib/module-xml.sax.html A typical SAX application uses three kinds of objects: readers, handlers and input sources. ``Reader'' in this context is another term for parser, i.e. some piece of code that reads the bytes or characters from the input source, and produces a sequence of events. Bytes _or_ characters. -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From byte8bits at gmail.com Wed Jul 18 15:59:04 2007 From: byte8bits at gmail.com (brad) Date: Wed, 18 Jul 2007 15:59:04 -0400 Subject: Open HTML file in IE In-Reply-To: <1184739605.732844.321180@m37g2000prh.googlegroups.com> References: <1184739605.732844.321180@m37g2000prh.googlegroups.com> Message-ID: gravey wrote: > Hello. > > Apologies if this is a basic question, but I want to open a HTML > file from my local drive (is generated by another Python script) > in Internet Explorer. I've had a look at the webbrowser module and > this doesn't seem to be what I need. Any help much appreciated. You may try something like this example: import time import win32com.client wie = win32com.client.Dispatch('InternetExplorer.Application') # Make IE Window Visible. wie.Visible = 1 # Open this URL wie.Navigate('www.your_url.com') # Print 'Busy' while Busy. while wie.Busy: print 'Busy' # Sleep 2 secs, then go home. time.sleep(2) wie.GoHome() # Sleep 2 secs, then go back. time.sleep(2) wie.GoBack() # Refresh the page time.sleep(2) wie.Refresh() # Close IE Window time.sleep(2) wie.Quit() From zyzhu2000 at gmail.com Fri Jul 27 18:16:47 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 27 Jul 2007 22:16:47 -0000 Subject: Another C API Question In-Reply-To: References: <1185498383.333248.225360@19g2000hsx.googlegroups.com> <1185545488.751250.200270@z24g2000prh.googlegroups.com> <1185571136.628131.168260@z24g2000prh.googlegroups.com> Message-ID: <1185574607.620385.198680@x40g2000prg.googlegroups.com> On Jul 27, 4:50 pm, Farshid Lashkari wrote: > beginner wrote: > > I did and it did not seem to work. I ended up doing the following. > > Verbose, isn't it? > > If I do d=PyFloat_AsDouble(oDiscount); in the third "if", I get an > > error. Maybe I missed something obvious. > > That's strange. I just tried the following code: > > fprintf(stdout,"True = %lf\n",PyFloat_AsDouble(Py_True)); > fprintf(stdout,"False = %lf\n",PyFloat_AsDouble(Py_False)); > fprintf(stdout,"5 = %lf\n",PyFloat_AsDouble(PyInt_FromLong(5))); > > And it printed the following: > > True = 1.000000 > False = 0.000000 > 5 = 5.000000 > > What version of Python are you using? I am using 2.5.1 and Windows XP. Thanks for your help. From S.Mientki-nospam at mailbox.kun.nl Sun Jul 1 15:59:49 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sun, 01 Jul 2007 21:59:49 +0200 Subject: The best platform and editor for Python In-Reply-To: <1183318637.021496.185990@k29g2000hsd.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183318637.021496.185990@k29g2000hsd.googlegroups.com> Message-ID: <48881$46880677$d443bb3a$16222@news.speedlinq.nl> > Thank you for the suggestions. I'd prefer a GUI-based, helpful and > easy-implemention skilled enviroment. Tesekkurler Sayin Kartal :-) > then first decide which graphical package you want to use, because that limits your choice. cheers, Stef Mientki From frank at chagford.com Sun Jul 22 05:14:26 2007 From: frank at chagford.com (Frank Millman) Date: Sun, 22 Jul 2007 02:14:26 -0700 Subject: Advice on sending images to clients over network Message-ID: <1185095666.627415.108450@w3g2000hsg.googlegroups.com> Hi all This is not strictly a Python question, but as the system to which relates is written in Python, hopefully it is not too off-topic. I have an accounting/business application, written in client/server mode. The server makes a connection to a database, and then runs a continuous loop waiting for client connections, establishes a session with the client, and responds to messages received from the client until the client closes the connection. The client uses wxPython as the gui. All the business logic is on the server - there is none at all on the client side. It seems to be working quite well. I now want to add the capability of displaying images on the client. For example, if the application deals with properties, I want to display various photographs of the property on the client. wxPython is perfectly capable of displaying the image. My question is, what is the best way to get the image to the client? Assume that the images are stored in a directory on the server, or at least accessible from the server, and that the database has a table which stores the full path to each image, with the property id as a reference. My first thought was that the server would simply retrieve the path, read the image, and send it to the client over the network, along with all the other information. The problem with this is performance - I may set up a page with 20 images to be displayed on the client, which may take some time. I need the server to respond to client messages as quickly as possible, so that it is ready to handle the next request. The server is multi-threaded, so it will not block other threads, but it may still result in sluggish performance. My second thought was to send the path to the image down to the client, and get the client to read the image directly. The problem with this is that each client needs to be able to resolve the path to the image directory. At present, all that the client requires is a pointer to the client program directory, and a parameter giving it the ip address and port number required to make a connection to the server. It seems an extra administrative burden to ensure that each client can access the image directory, especially if at a later date it is decided to move the directory. My third thought was to set up a separate 'image server'. It would be another server program written in Python, listening on its own port number, waiting for a client request for a particular image. It would know where to find it, read it in, and send it to the client. Then all the client needs to know is the ip address and port number. It seems likely that a typical setup would start by storing the images on the same machine as the database and the server program. If so, there would be little difference between any of the above, as no matter with method is used, the same machine ultimately has to read the record from its own hard drive and send it down the network over its own nic. If at a later date it was decided that the volume of image handling was slowing down the server process, one might well decide to move the images to a separate server. In this case, I think that my third option would make it easiest to facilitate this. You would have to change all the client parameters to connect to a different server. Or maybe not - thinking aloud, I could pass the 'image server connection parameters' to the client from the main server once a connection has been established. A second implication is that you would have to change all the paths in the database table. Again, maybe not - just store the file names in the table, and the path to the directory as a separate parameter. Then you only have to change the parameter. I guess the point of all this rambling is that my thought process is leading me towards my third option, but this would be a bit of work to set up, so I would appreciate any comments from anyone who has been down this road before - do I make sense, or are there better ways to handle this? Any suggestions will be much appreciated. Thanks Frank Millman From the.mindstorm.mailinglist at gmail.com Tue Jul 17 10:05:17 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Tue, 17 Jul 2007 07:05:17 -0700 Subject: how to find available classes in a file ? In-Reply-To: References: <2e302$469bf38f$d443bb3a$30036@news.speedlinq.nl> <1184627599.597658.267380@g4g2000hsf.googlegroups.com> Message-ID: <1184681117.305570.311350@x35g2000prf.googlegroups.com> On Jul 17, 4:41 am, "Gabriel Genellina" wrote: > En Mon, 16 Jul 2007 20:13:19 -0300, Alex Popescu > escribi?: > > > On Jul 17, 1:44 am, Stef Mientki > > wrote: > >> I want to have a (dynamically) list of all classes defined in a py-file. > >> Is there a way of getting this list, without manually parsing the file ? > > > I have written something that does something like this, but I am not > > sure it is the pythonic way. > > Bascially I am loading the module and then using dir() on the module > > object I am looking for > > attribute of the type classobj (for old style classes) and type type > > (for new style classes). > > There is also the pyclbr standard module > that does not load the > module (just reparses enough of it to get the info needed). So a broken > import, or any other initialization error, won't hurt. > > > I also heard of the inspect module, but I haven't checked it yet. > > inspect.getmembers(the_module, inspect.isclass) would do. But this > requires the module to be importable. > > -- > Gabriel Genellina I may be wrong but I think I've found a difference between my dir(module) approach and the inspect.getmembers(module, inspect.isclass): the first one returns the classes defined in the module, while the later also lists the imported available classes. ./alex -- .w( the_mindstorm )p. From claird at lairds.us Tue Jul 17 17:15:13 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 17 Jul 2007 21:15:13 +0000 Subject: How to organize control access to source code ? References: <1184618776.798929.98960@57g2000hsv.googlegroups.com> <1184627782.951682.77870@n2g2000hse.googlegroups.com> <1184676647.068641.3500@d30g2000prg.googlegroups.com> Message-ID: <14ovm4-28m.ln1@lairds.us> In article <1184676647.068641.3500 at d30g2000prg.googlegroups.com>, Paul Boddie wrote: >On 17 Jul, 01:16, Succe... at gmail.com wrote: >> >> Thanks for your response, >> But I want to know if there is a process or best practices, to give >> not the access to all of the project. in other words, must every >> developer work on the entire copy of the project locally ? > >You probably want to split the project up into several individual >projects (as perceived from a technical perspective), which can then >be protected using whichever mechanisms are available. Not only will >it be easier to introduce various access controls - for example, you >might have a bunch of different CVS modules (or similar things) which >are then easier to administer and apply access controls to - but >you'll also reduce the undesirable side-effects that come with a >monolithic project with lots of people hacking on different stuff that >inadvertently breaks other stuff. > >> Or to work just on his module and manage a process of integration, and >> if there is any Agile practices for this problem. > >I'm not sure what the overlap is between "agile development" and >restrictive access controls, but another approach might be to use a >totally distributed version control system and then manage the >restrictions when merging changes. You'd probably remain "agile" >whilst exercising the control you require. > >Paul > I think the answers to this point are missing emphases I can't make the time now to articulate. The prospects are actually better than what we've been saying: individual developers *do* have access to everything (and they like that), but the authoritative version of the software is the one sequestered away in the version control system, and you gain all sorts of access control and auditability through *that* mechanism. So: I think what the original questioner needs to do is read up on version control and configuration manage- ment. , for example, is very light background reading that I suspect the original questioner does not yet have. From nyamatongwe+thunder at gmail.com Sat Jul 7 19:45:22 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 07 Jul 2007 23:45:22 GMT Subject: Getting the home directory in Python and a bug in os.path.expanduser In-Reply-To: <_MRji.11911$K9.9459@bignews6.bellsouth.net> References: <5aQji.1085$m%.196@newssvr17.news.prodigy.net> <_MRji.11911$K9.9459@bignews6.bellsouth.net> Message-ID: Edward Diener: > Probably most reliable on Windows is a Windows API function, if it > exists, for getting the home directory, as opposed to using environment > variables, but I can not find any Windows API for it at present. Look at SHGetFolderPath(CSIDL_PROFILE, ...) for Windows Me/2000 or later. CSIDL_APPDATA is probably a better idea than CSIDL_PROFILE (its equivalent to "%USERPROFILE%\Application Data" and roams) but %USERPROFILE% (CSIDL_PROFILE) is compatible with previous Python behaviour. http://msdn2.microsoft.com/en-us/library/ms647764.aspx Neil From david.bear at asu.edu Tue Jul 10 19:32:01 2007 From: david.bear at asu.edu (David Bear) Date: Tue, 10 Jul 2007 16:32:01 -0700 Subject: storing pickles in sql data base Message-ID: <592087469.jZQWuvoN0q@teancum> I need to store pickled objects in postgresql. I reading through the pickle docs it says to always open a file in binary mode because you can't be sure if the pickled data is binary or text. So I have 2 question. Can I set the pickle to be text -- and then store it in a 'text' type field in my sql table, or should what sql type should I save the pickle as? -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From hniksic at xemacs.org Fri Jul 13 05:32:15 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 13 Jul 2007 11:32:15 +0200 Subject: Question about PyDict_SetItemString References: <1184311267.876950.150040@e16g2000pri.googlegroups.com> Message-ID: <87ps2w4pk0.fsf@mulj.homelinux.net> lgx writes: >From Google results, I find some source code write like that. But >some code write like below: > > obj = PyString_FromString("value"); > PyDict_SetItemString(pDict,"key",obj); > Py_DECREF(obj); > > So, which one is correct? The latter is correct. While PyDict_GetItemString returns a borrowed reference, PyDict_SetItemString doesn't steal the reference. This makes sense because adding to the dictionary can fail for various reasons (insufficient memory, invalid key, hash or comparison functions failing), and that allows you to write code like this: obj = ; int err = PyDict_SetItemString(dict, "key", obj); Py_DECREF(obj); if (err) return NULL; /* or whatever is appropriate in your case */ That won't leak regardless of whether PyDict_SetItemString succeeded, and will correctly propagate an error if it occurs. Please note that there is a new mailing list for Python/C API questions, see http://mail.python.org/mailman/listinfo/capi-sig . From laurent.pointal at wanadoo.fr Mon Jul 2 16:20:34 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Mon, 02 Jul 2007 22:20:34 +0200 Subject: Pretty Scheme, ??? Python References: Message-ID: <46895e12$0$5078$ba4acef3@news.orange.fr> Neil Cerutti wrote: ... > How can I make the Python more idiomatic Python? Have you taken a look at pyparsing ? http://pyparsing.wikispaces.com/ From bdesth.quelquechose at free.quelquepart.fr Thu Jul 19 00:33:26 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 19 Jul 2007 06:33:26 +0200 Subject: Pythonic way for missing dict keys In-Reply-To: References: <1184961448.456134.153020@k79g2000hse.googlegroups.com> Message-ID: <46a20fda$0$27858$426a74cc@news.free.fr> Alex Popescu a ?crit : > Jakub Stolarski wrote in > news:1184961448.456134.153020 at k79g2000hse.googlegroups.com: > > >>Version 1 and 2 do different thing than version 3. The latter doesn't >>add value to dict. >> >>As it was mentioned before, use: >>1 - if you expect that there's no key in dict >>2 - if you expect that there is key in dict >> > > > I may be missing something You are. > but I think the 3 approaches are completely > equivalent in terms of functionality. d = dict() answer = d.get('answer', 42) answer in d => False From steve at holdenweb.com Fri Jul 6 19:31:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Jul 2007 19:31:21 -0400 Subject: Expandable 2D Dictionaries? In-Reply-To: <20070706160920.4947.2015818722.divmod.quotient.7938@ohm> References: <1183736635.415927.208450@57g2000hsv.googlegroups.com> <20070706160920.4947.2015818722.divmod.quotient.7938@ohm> Message-ID: Jean-Paul Calderone wrote: > On Fri, 06 Jul 2007 15:43:55 -0000, Robert Dailey wrote: >> Hi, >> >> I am interested in creating an expandable (dynamic) 2D dictionary. For >> example: >> >> myvar["cat"]["paw"] = "Some String" >> >> The above example assumes "myvar" is declared. In order for this to >> work, I have to know ahead of time the contents of the dictionary. For >> the above to work, my declaration must look like: >> >> myvar = {"cat": {"paw":""} } >> >> I would like to not have to declare my dictionary like this, as it >> does not allow it to be expandable. I'm very new to Python (I'm a >> professional C++ programmer. Any comparisons to C++ would help me >> understand concepts). >> >> Is there a way that when I index into my dictionary using an "unknown" >> index (string), that python will dynamically add that key/value pair? > > This gets much easier if you change your structure around a bit: > > d = {} > d["cat", "paw"] = "some string" > > Jean-Paul Unfortunately that makes it somewhat more difficult to retrieve the set of entries whose first index is "cat". I realise that we don't have much in the way of use cases here, but it would seem that the original motivation for a two-level dictionary might have been such a requirement. 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 rdm at rcblue.com Sat Jul 28 23:24:45 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 28 Jul 2007 20:24:45 -0700 Subject: OOP in Python book? In-Reply-To: References: <1185550866.950455.61240@g12g2000prg.googlegroups.com> Message-ID: <20070729032543.6F4781E400C@bag.python.org> At 01:27 PM 7/28/2007, Dennis Lee Bieber wrote: >On Fri, 27 Jul 2007 16:27:57 -0700, Dick Moores >declaimed the following in comp.lang.python: > > > > Well, the publisher is Prentice Hall, "The world's leading > > educational publisher". Textbooks are typically expensive. > > > > Yeah... But at that price it should have hard-covers! Should have, but look at this popular Cultural Anthropology text (paperback): . List price is $120.95 USD. (BTW I just bought the 6th edition online for about $10.) Then there's Calculus: Single Variable (Paperback) List price $123.95 USD. And so it goes. Dick From theller at ctypes.org Thu Jul 5 10:14:17 2007 From: theller at ctypes.org (Thomas Heller) Date: Thu, 05 Jul 2007 16:14:17 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: References: Message-ID: Christoph Zwerschke schrieb: > What is the best way to re-raise any exception with a message > supplemented with additional information (e.g. line number in a > template)? I have the impression that you do NOT want to change the exceptions, instead you want to print the traceback in a customized way. But I may be wrong... Thomas From mensanator at aol.com Sun Jul 8 14:26:31 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sun, 08 Jul 2007 11:26:31 -0700 Subject: python extra In-Reply-To: References: Message-ID: <1183919191.840576.204450@n60g2000hse.googlegroups.com> On Jul 8, 12:59?pm, Neal Becker wrote: > Just a little python humor: > > http://www.amazon.com/Vitamin-Shoppe-Python-Extra-tablets/dp/B00012NJ... Aren't there any female Python programmers? From bignose+hates-spam at benfinney.id.au Fri Jul 27 19:05:51 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 28 Jul 2007 09:05:51 +1000 Subject: Relative-importing * References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> Message-ID: <871weth2gg.fsf@benfinney.id.au> rbygscrsepda at gmail.com writes: > from . import * > from .sibiling import * > from .. import * > from ..parent_sibling import * > > ...and so on. The same error occurs: > SyntaxError: 'import *' not allowed with 'from .' Interesting. I know that 'from foo import *' is frowned on and is generally worse than importing names explicitly, but I wasn't aware that it was officialy deprecated. The PEP introducing absolute and relative imports doesn't mention it, except as a friendly "import * is *not* an option :-)" aside. > Why would it not let me import * from a relative module at all? I > read that they're planning to make absolute imports the default, so > I'd think that this sort of thing would become more common in the > future. I'd also like to know when this changed,and where it's documented. While waiting, you should take it as an opportunity to remove the blight of "from foo import *". All imports should explicitly import names, not implicitly clobber the current namespace with whatever pops out. Depending on the reason for the import, do one of the following: from foo import bar, baz, boris do_stuff_with(baz) import foo do_stuff_with(foo.baz) import uncomfortably_long_name as foo do_stuff_with(foo.baz) All of these preserve the valuable trait of being able to trace, by reading the program, the origin of every name in the current namespace. -- \ "I hope if dogs ever take over the world, and they chose a | `\ king, they don't just go by size, because I bet there are some | _o__) Chihuahuas with some good ideas." -- Jack Handey | Ben Finney From evan at yelp.com Tue Jul 17 13:50:11 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 17 Jul 2007 10:50:11 -0700 Subject: Semantics of file.close() In-Reply-To: <1184628945.314844.53300@k79g2000hse.googlegroups.com> References: <1184628945.314844.53300@k79g2000hse.googlegroups.com> Message-ID: On 7/16/07, seerdecker at gmail.com wrote: > Hello, > > I'm a Python beginner and I'm trying to open, write and close a file > in a > correct manner. I've RTFM, RTFS, and I've read this thread: > http://groups.google.ca/group/comp.lang.python/browse_thread/thread/73bbda2c920521c/98c731229d86b01d?lnk=st&q=python+file+explicit+close&rnum=1&hl=en#98c731229d86b01d > > I still cannot figure out the semantic of file.close(). As far as I > can > tell it is undocumented. Explanations and example follow. > > There are two occasions where you have to close a file: > > 1) At the end of a series of writes to the file, to ensure that all > data > is written correctly to disk. In this case I want file.close() to > throw an exception if the file cannot be written (e.g. when there > is > no more disk space). > > 2) To clean up after an error occurred during the processing. In that > case I just want to close the file handle cleanly. I do NOT want an > exception to be thrown (e.g. in my finally clause). > > Man page of fclose() -- in C: > > fclose - close a stream > > Upon successful completion 0 is returned. Otherwise, EOF is > returned > and the global variable errno is set to indicate the error. In > either > case any further access (including another call to fclose()) to > the stream results in undefined behaviour. > > The man page of fclose() clearly indicates that fclose() may fail. > I've > already tested under Linux that fwrite() indicates success even if the > disk is full; the error is ONLY reported when close() is called. > > Consider the following example: > > file1 = None; > file2 = None; > > try: > file1 = open("foo1.txt", "wb"); > file2 = open("foo2.txt", "wb"); > file1.close(); > file2.close(); > > finally: > if file1: file1.close(); > if file2: file2.close(); > > How do I ensure that the close() methods in my finally clause do not > throw an exception? > > Thanks a lot, > Laurent Birtz You should take a look at the man pages for close(2) and write(2) (not fclose). Generally you will only get an error in C if you try to close a file that isn't open. In Python you don't even have to worry about that -- if you close a regular file object more than once no exception will be thrown, _unless_ you are using os.close(), which mimics the C behavior. If you are out of space, in C you will get an error returned by the call to write (even if the data isn't actually flushed to disk yet by the kernel). I'm pretty sure Python mimics this behavior, so an exception would be called on the write, not on the close operation. -- Evan Klitzke From ndbecker2 at gmail.com Sun Jul 8 20:12:01 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Sun, 08 Jul 2007 20:12:01 -0400 Subject: python extra References: <1183919191.840576.204450@n60g2000hse.googlegroups.com> <59f9c5160707081533n39305cq3358d376e1f8aecb@mail.gmail.com> Message-ID: Danyelle Gragsone wrote: > Nope.. not a one.. > > > On 7/8/07, mensanator at aol.com wrote: >> On Jul 8, 12:59?pm, Neal Becker wrote: >> > Just a little python humor: >> > >> > http://www.amazon.com/Vitamin-Shoppe-Python-Extra-tablets/dp/B00012NJ... >> >> Aren't there any female Python programmers? >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> I really think we should take up a collection to send this to Guido. From S.Mientki-nospam at mailbox.kun.nl Tue Jul 31 10:11:39 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 31 Jul 2007 16:11:39 +0200 Subject: Plotting Images In-Reply-To: References: Message-ID: <6fdf6$46af419c$d443bb3a$8600@news.speedlinq.nl> Pei-Yu CHAO wrote: > Hi ALL: > > I have only been switched from matlab to python few > months ago. I having trouble of plotting images from a > matrix size of 8x10000 (unfortunately that is the size > of my data.....) > > for example, > x = rand(8,10000) > inshow(x) > > I have tried to use matplotlib function imshow(), but > all i get is a long thin line (unable to see the color > display and the my matrix information). > > i think imshow() has the same problem in matlab, but i > think there is a alternative in matlab, imagesc(). > > I did search on web about plt.imagesc().....but when i > try to run the example code, python just tell me > cannot find module plt. > >>> >from scipy import plt > ImportError: cannot import name plt > > I have installed scipy, wxpython2.6....and it still > seem not to work! > > is there some alternitive? or what have i done wrong? > Thank you > > Pei you might try wxPyPlot, this seems to be a very light weight and yet powerfull graph unit. cheers, Stef Mientki From byte8bits at gmail.com Mon Jul 23 16:22:48 2007 From: byte8bits at gmail.com (brad) Date: Mon, 23 Jul 2007 16:22:48 -0400 Subject: inet_addr() in Python In-Reply-To: References: Message-ID: Steve Holden wrote: > brad wrote: >> Does Python have an equivalent to C's inet_addr()? >> > socket.inet_aton() produces a four-byte string you can pass as a struct > in_addr, if that's what you are looking for. If you want a number then > use the struct module to manipulate it further. > > >>> s.inet_aton('127.0.0.1') > '\x7f\x00\x00\x01' > > regards > Steve Thanks! That works great for my needs. I should have read the socket documentation more thoroughly. From Green.Horn.000 at gmail.com Fri Jul 27 23:10:32 2007 From: Green.Horn.000 at gmail.com (GreenH) Date: Sat, 28 Jul 2007 03:10:32 -0000 Subject: pythonic parsing of URL Message-ID: <1185592232.110391.69630@i13g2000prf.googlegroups.com> I get some string as below from a library method (qt3 QDropEvent.data()) I use. file:///C:/Documents%20and%20Settings/Username/My%20Documents/45-61-Abc%20fold-%20den.vru I need file path on my system, for the above example: C:/Documents and Settings/Username/My Documents/45-61-Abc fold- den.vru I am doing the below, it doesn't look pythonic, can someone suggest any elegant solution, which is not too cryptic to understand? yep, I do care about readability of the code to average python user :) -------------------- tmpTuple = urlparse.urlparse(fileURLname) tmpString = tmpTuple[2].strip('/\\') fileName = urllib.unquote(tmpString) #For some reason the string contained in 'fileName' has some unprintable trailing characters, Any ideas on that? #thus I do below fileName = fileName.split('.vru')[0] + '.vru' -------------------- Thanks, Greene. From bignose+hates-spam at benfinney.id.au Thu Jul 26 01:23:18 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Jul 2007 15:23:18 +1000 Subject: I am giving up perl because of assholes on clpm -- switching to Python References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> Message-ID: <878x93ivqx.fsf@benfinney.id.au> Martha_Jones at tx.net writes: > Python is a better language, with php support, anyway, but I am fed > up with attitudes of comp.lang.perl.misc. Please, if you must fred the troll, drop comp.lang.python from the discussion (i.e. post trplies only to the newsgroup this message relates to). -- \ "I like to reminisce with people I don't know. Granted, it | `\ takes longer." -- Steven Wright | _o__) | Ben Finney From frank at chagford.com Mon Jul 9 00:53:17 2007 From: frank at chagford.com (Frank Millman) Date: Sun, 08 Jul 2007 21:53:17 -0700 Subject: How to override PyGridTableBase.SetColLabelValue()? In-Reply-To: <1183951644.304339.243210@z28g2000prd.googlegroups.com> References: <1183951644.304339.243210@z28g2000prd.googlegroups.com> Message-ID: <1183956797.395669.278680@g4g2000hsf.googlegroups.com> On Jul 9, 5:27 am, fck... at gmail.com wrote: > Dear all, > > the doc is missing, and > i failed to find the solution on google search. > anyone know how to override > the function SetColLabel() inside the class PyGridTableBase or the > class GridTableBase? > > my code, > #=========================================== > class MegaTable(wx.grid.PyGridTableBase): > def __init__(...) > ..... > wx.grid.PyGridTableBase.__init__(self) > > def SetColLabelValue(self, col, value): > value = self.coltags[col] > -->how to ??? > > class MegaGrid(wx.grid.Grid): > def __init__(...) > ..... > wx.grid.Grid.__init__(self, parent, id) > self._table = MegaTable(self, .....) > self.SetTable(self._table) > ..... > #=========================================== > > thanks! You are not supposed to override SetColLabel(), you are supposed to override GetColLabelValue(). When you use PyGridTableBase, there could potentially be thousands of columns, and wxPython does not want to keep track of thousands of column labels. Therefore, when wxPython needs to display a column label, it calls GetColLabelValue(self,col). It is up to you to return the value to use for that column. HTH Frank Millman From Eric_Dexter at msn.com Fri Jul 13 20:03:08 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Fri, 13 Jul 2007 17:03:08 -0700 Subject: Python Subprocess module In-Reply-To: References: Message-ID: <1184371388.515695.271360@22g2000hsm.googlegroups.com> On Jul 13, 4:15 pm, Dave Sampson wrote: > hey folks, > > A simple question hopefully. despite all my searching I have not found a > satisfactory response. > > The goal. Interact with a command line program. Simple enough, but the > key is INTERACT. > > I tried the shell and comand approaches but that initiates, it does not > allow interaction with the programs. > > So then I went with Popen and such... which then led to the subprocess > module. > > I can create the object and read a few lines of output. but if I go too > far then the program hangs. the number of lines will differ depandening > on many function including the format of an input file so I can;t > hardcode how many lines to read. > > I want to read all of STDOUT without failing because I went out of range. > > next I want to read the final line of the output because it tells me > what is required for the next line of input. > > I am supposed to be able to entre 'y' and return for the program to > continue if I agree with what I see in the stdout. > > A problem exists though that I have tried > 'y' > 'y\n' > 'y\r' > > and nothing seems to get the program going again for I still cant; read > past the same point in the standard output. then I have to kill and > start over. > > So the next approach included looking at Pexpect, which got realy > confusing realy fast and despite running fedora core and python 2.4.4 I > would like my application to be cross platform and there is no Pexpect > for Windows That I can see. > > I have checked out many mailing lists and posts and tutorials but they > all admit to not be samples of complex interactivity. I guess I am > having that special case. > > ASPN Python cookbok provided some code for a new Popen Class that allows > for interaction but I don't think I need to go that root.... > > I am essentialy trying to build and Python wrapper for a coomand line > program that i want to build a GUI around. > > Any links or suggestions would be great. Unfortunaetly I don't > understand that abstract concepts in the manual reference. I am fresh in > the python world and find examples better than technical abstracts. > > Cheers There is something called http://www.rutherfurd.net/python/sendkeys/ send keys for the p.c. you can use a try: except: concept and on the windows platform there is also a way to use autoit in python using pywin. At one time (2001) there was a module that allowed you to use gvim but it has dissapeared unless it is listed somewhere else (gvim doesn't seem to work with the sendkey method and it is a shame it has alot of cool text functions including command line support) http://sourceforge.net/projects/dex-tracker/ From kyosohma at gmail.com Thu Jul 5 11:09:26 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 05 Jul 2007 15:09:26 -0000 Subject: WXPYTHON push button call a frame In-Reply-To: <1183644253.916399.9350@w5g2000hsg.googlegroups.com> References: <1183626149.036739.281070@w5g2000hsg.googlegroups.com> <1183644253.916399.9350@w5g2000hsg.googlegroups.com> Message-ID: <1183648166.386213.139910@r34g2000hsd.googlegroups.com> On Jul 5, 9:04 am, Marcpp wrote: > On 5 jul, 14:51, Steve Holden wrote: > > > > > Marcpp wrote: > > > Hi I need to call a widget from a button in WXPYTHON. I've tried to > > > this from a function like this, but when push the button, the program > > > opens a window and do error. > > > Any idea? > > > Well, one *really* good idea would be to copy the error message and > > paste it into your message. The readers of this list have amazing > > psychic powers, but you can always help improve the answer quality by > > providing relevant information. > > > > ..... > > > def DialogRRHH(self,event): > > > prog = wx.PySimpleApp(0) > > > wx.InitAllImageHandlers() > > > DialogRRHH = MTRRHH(None, -1, "") > > > prog.SetTopWindow(DialogRRHH) > > > DialogRRHH.Show() > > > prog.MainLoop() > > > > class MTRRHH(wx.Frame): > > > ....... > > > if __name__ == "__main__": > > > app = wx.PySimpleApp(0) > > > wx.InitAllImageHandlers() > > > tasques = tasques(None, -1, "") > > > app.SetTopWindow(tasques) > > > tasques.Show() > > > app.MainLoop() > > > Unfortunately your code extracts don't tell us what's going wrong, only > > how the program is constructed. While that *is* useful information, by > > itself it only paints half the picture. > > > 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, the problem is No Error message, but the program continues running > after I closed it (by the X). When I open a custom frame from one of my applications, I do something like this:
    def BtnEventHandler(self, event): frame = myFrame() frame.Show()
    class myFrame(wx.Frame): def __init__(self, filename=None): wx.Frame.__init__(self, None, -1, 'Whatever', size=(570,295)) # you can set the OnTop style here # lots of other code... def OnClose(self, event): # Close the frame self.Close() If you have additional problems, try mailing the wxPython group, which you can find here: www.wxpython.org Mike From vsjni at cch.com Sun Jul 29 14:19:44 2007 From: vsjni at cch.com (Roddy) Date: Sun, 29 Jul 2007 12:19:44 -0600 Subject: No subject Message-ID: <46ACDA40.3030202@varanger-bredband.no> -------------- next part -------------- A non-text attachment was scrubbed... Name: mail.pdf Type: application/pdf Size: 24270 bytes Desc: not available URL: From mccredie at gmail.com Wed Jul 11 01:43:11 2007 From: mccredie at gmail.com (Matimus) Date: Wed, 11 Jul 2007 05:43:11 -0000 Subject: SafeConfigParser can set unsafe values In-Reply-To: References: <46940a3e$0$18464$afc38c87@news.optusnet.com.au> <1184111631.293350.106340@o11g2000prd.googlegroups.com> Message-ID: <1184132591.850915.293230@d30g2000prg.googlegroups.com> > This not only happens when get() after a set(), but with all the use cases > above. An intervening write()/read() does not change things. > But I'm not sure it is a bug really. If all % were escaped automatically, > there is no way to write a templatized value. Maybe SafeConfigParser.set > should grow an escape argument, controlling whether one wants the value > escaped or not. For compatibility reasons should default to False, for > usability reasons should default to True. The exception is only raised when get is called, the "raw" paremeter for get(...) is set to False (default) and the string value for that parameter contains a single "%". None of the cases I stated above call get() after calling set(). So, the exception will never be raised because of something the user set. It will be raised if the input file happens to have a single "%" character in one of the parameter values, but that content could have been user generated, and it is not reasonable to assume that fixing the set() method would have prevented it. Adding an escape parameter to set will not be used properly. Its purpose would be to escape lone "%" characters, but if users are wanting to use the substitution they would always keep escaping off. It wouldn't allow them catch situations like this: cp.set("sect","param","this is my value %(key)s and here is a lone % and here is another %(sub)s", escape=False) The solution I would propose is to raise an exception on set() if the value contains a single "%" not followed by a key name enclosed in parens followed by "s". That puts the burden of escaping on the user, before passing it to set. From gagsl-py2 at yahoo.com.ar Fri Jul 20 10:38:00 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Jul 2007 11:38:00 -0300 Subject: Compatibility of python2.5 with pytohn2.3 References: Message-ID: En Wed, 18 Jul 2007 08:36:24 -0300, Gerhard H?ring escribi?: > VISHAL KANAUJIA wrote: >> Hi all, >> I am new member of this post. I have a C application which uses >> Python(version 2.3) extensively with SWIG wrappers. I want to upgrade >> the Python to latest version2.5. >> >> Is there any compatibility issue between two versions? Does latest >> Python2.5 provide backward compatibility to previous Python (Version >> 2.3 in my case) constructs. > Short answer: yes. > > I've never had any issues here (compiling Python extension code in newer > Python versions). The other way around that's of course not the case. I > have to test my extension code against Python 2.4 and Python 2.3 > regularly, I would add this single point as the most relevant change in 2.5: "The obmalloc changes mean that you must be careful to not mix usage of the PyMem_*() and PyObject_*() families of functions. Memory allocated with one family's *_Malloc() must be freed with the corresponding family's *_Free() function." (On previous versions, mixing calls from different families could go mostly unnoticed, as nothing bad would happen). Regarding Python source files, their encoding declaration is now mandatory when they contains any non ascii string. (Reviewing the "What's new" documents would be a good idea anyway) -- Gabriel Genellina From semanticist at gmail.com Mon Jul 23 15:21:20 2007 From: semanticist at gmail.com (Miles) Date: Mon, 23 Jul 2007 15:21:20 -0400 Subject: Maintaining leading zeros with the lstrip string function? In-Reply-To: References: Message-ID: On 7/23/07, Randy Kreuziger wrote: > I need just the file name from a string containing the path to a file. The > name of the file starts with zeros. This is problematic because the lstrip > function strips them leaving this as the result: > 6128.jpg > > > How do I strip the path without losing the leading zeros in the file name? > > --------------------------------------------- > import sys, os, win32com.client, string > > teststring = 'C:\shoreline\dvd\prep area\800x\\006128.jpg' > print string.lstrip(teststring, 'C:\shoreline\dvd\prep area\800x\\') lstrip removes *any* of the set of characters in the argument, not the exact string[1]. Use of the string module for lstrip and other functions[2] has been deprecated for using the string methods directly, i.e. teststring.lstrip(...). You should probably be using split (or basename) in the os.path module. Also, use raw strings ( r'\path\to\file' ) to avoid problems with backslashes being interpreted in strings. -Miles [1] http://docs.python.org/lib/string-methods.html [2] http://docs.python.org/lib/node42.html From erfc at caballista.org Sun Jul 29 20:53:20 2007 From: erfc at caballista.org (Art Deco) Date: Sun, 29 Jul 2007 18:53:20 -0600 Subject: What does this thread have to do with classical music, References: <7nnh7350b5h25ghocra72b23mmsnnkj8bh@4ax.com> <468cf97b$0$97266$892e7fe2@authen.yellow.readfreenews.net> <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> Message-ID: <290720071853200863%erfc@caballista.org> 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! -- 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" From gh at ghaering.de Tue Jul 3 10:36:35 2007 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Tue, 03 Jul 2007 16:36:35 +0200 Subject: trouble with sqlite under debian etch In-Reply-To: References: Message-ID: <5ev57jF39kr3cU1@mid.uni-berlin.de> Rustom Mody wrote: > I was trying to follow the sqlalchemy tutorial on my debian etch box > and got stuck with installation. Any help/pointers will be welcome. > > First after installing sqlalchemy needed some sqlite package > synaptic showed me packages python-pysqlite, python-pysqlite1.1 and > python-pysqlite2. > [...] Or just use Python 2.5, which includes a "sqlite3" module that SQLAlchemy can use. > Theres some confusion regarding numbers: python-pysqlite2 is for > sqlite3 or some such thing the 2 in python-pysqlite2 is for > Tried python-pysqlite1.1 and got errors. Tried 2 and got version warnings. > > Downloaded the tgz and did a setup build followed by a setup install > > Now the >>>> db = create_engine('sqlite:///tutorial.db') > gives me no module _sqlite Did you execute that in the pysqlite root directory (i. e. the one that "setup.py" and friends are?). Unfortunately, any other working directory will be ok, but this one isn't. -- Gerhard From erik at myemma.com Mon Jul 16 12:25:49 2007 From: erik at myemma.com (Erik Jones) Date: Mon, 16 Jul 2007 11:25:49 -0500 Subject: How to determine which method was used in an inheritance heirarchy? In-Reply-To: <4866bea60707160835w5c64ec50pc8774592768b2b82@mail.gmail.com> References: <1184559788.712146.238190@q75g2000hsh.googlegroups.com> <1184565220.674041.270790@o61g2000hsh.googlegroups.com> <4BC3DC93-5F57-4B24-BE82-EB2D5FD679AF@myemma.com> <865D7C6C-F76B-46F0-9E4C-848E896A1627@myemma.com> <4866bea60707160835w5c64ec50pc8774592768b2b82@mail.gmail.com> Message-ID: <2BA8CFA1-D77B-45C9-8E22-01F765D5BC78@myemma.com> On Jul 16, 2007, at 10:35 AM, Chris Mellon wrote: > On 7/16/07, Erik Jones wrote: >> On Jul 16, 2007, at 3:37 AM, Gabriel Genellina wrote: >> >>> En Mon, 16 Jul 2007 03:56:18 -0300, Erik Jones >>> escribi?: >>> >>>> Perhaps an even better example of what I'm trying to do would be in >>>> order (this is minus any exception handling): >>>> >>>> import sys >>>> >>>> def mytrace(frame, event, arg): >>>> if event == 'call': >>>> func_name = frame.f_code.co_name >>>> >>>> if func_name in frame.f_locals['self'].__class__.__dict__: >>>> print frame.f_locals['self'].__class__.__name__ >>>> else: >>>> for base in frame.f_locals >>>> ['self'].__class__.__bases__: >>>> if func_name in base.__dict__: >>>> print base.__name__ >>>> break >>>> >>>> >>>> class A(object): >>>> def __init__(self): >>>> pass >>>> >>>> class B(A): >>>> def __init__(self): >>>> A.__init__(self) >>>> >>>> sys.settrace(mytrace) >>>> B() >>>> >>>> This will output: >>>> >>>> B >>>> B >>> >>> If you don't mind post-processing the results, you can log the >>> function >>> name and source module (from frame.f_code.co_name and >>> co_filename) and >>> current line number (frame.f_lineno). Later, obtaining the class >>> name from >>> those is a bit tricky (and not even the inspect module does it >>> right), but >>> perhaps using the tokenizer module, watching for lines that contain >>> "class" is enough. >> >> >> I was afraid of that. I used pretty much that tokenizer trick for a >> unit test generator I wrote in php a while back and felt like that >> was pretty clunky then. >> > > > Hacky, but maybe this will work: > > import sys > import inspect > > def mytrace(frame, event, arg): > if event == 'call': > func_name = frame.f_code.co_name > klassOb = frame.f_locals['self'].__class__ > for klass in inspect.getmro(klassOb): > cf = klass.__dict__.get(func_name) > if hasattr(cf, "func_code") and cf.func_code == > frame.f_code: > print klass.__name__ > > > class A(object): > def __init__(self): > pass > > class B(A): > def __init__(self): > A.__init__(self) > > sys.settrace(mytrace) > B() Chris, that is absolutely perfect. Also, I don't think there is such a thing as profiling code that isn't hacky ;) 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 p at ulmcnett.com Thu Jul 12 17:24:10 2007 From: p at ulmcnett.com (Paul McNett) Date: Thu, 12 Jul 2007 14:24:10 -0700 Subject: New guy help with setup In-Reply-To: <1184275051.504507.116080@57g2000hsv.googlegroups.com> References: <1184275051.504507.116080@57g2000hsv.googlegroups.com> Message-ID: <46969BFA.4080807@ulmcnett.com> meg99 wrote: > I just downloaded 2.5 and read the readme file. It says "Before you > can build Python, you must first confiigure it....Start by running the > script "./configure". > > I can't find "./configure" > > I am running Windows XP SP2 You downloaded the wrong file. You want the Windows Installer: http://python.org/ftp/python/2.5.1/python-2.5.1.msi HTH Paul -- pkm ~ http://paulmcnett.com From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jul 26 07:04:47 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 26 Jul 2007 13:04:47 +0200 Subject: Singleton in Python Cookbook In-Reply-To: References: <46a7c363$0$19625$426a34cc@news.free.fr> Message-ID: <46a87fbc$0$21340$426a74cc@news.free.fr> Alex Popescu a ?crit : > Bruno Desthuilliers wrote in > news:46a7c363$0$19625$426a34cc at news.free.fr: > >> Alex Popescu a ?crit : > >> [snip...] >> >> >> I don't have the book, so if you don't post the code, I just give up >> trying to guess what the problem can be. > > I've sent the original code and 2 different variants a long time ago. You had not sent anything when I answered. But it seems that the machine I answered with is a bit out of time !-) > ./alex > -- > .w( the_mindstorm )p. > > From mcshutterbug at dwx.com Tue Jul 3 20:41:32 2007 From: mcshutterbug at dwx.com (Marcus) Date: Tue, 03 Jul 2007 19:41:32 -0500 Subject: error return without exception set In-Reply-To: <468aa19c$0$27853$db0fefd9@news.zen.co.uk> References: <468a6d19$0$27861$db0fefd9@news.zen.co.uk> <468aa19c$0$27853$db0fefd9@news.zen.co.uk> Message-ID: <468aecc1$0$32299$c89e4b0f@news.dwx.com> Will McGugan wrote: > Thanks for the explanation. It happens when I'm debugging a wxWidgets > application with Komodo, but I can't trap it. I'm guessing it must be a > Komodo issue, because I dont get it if I run it without the debugger. The error happens in PyDev for Eclipse also -- only while debugging. It happens with or without wxWidgets; I've always assumed it's a pydev issue. From steven.bethard at gmail.com Tue Jul 10 19:47:47 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 10 Jul 2007 17:47:47 -0600 Subject: bool behavior in Python 3000? In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Tue, 10 Jul 2007 13:13:38 -0600, Steven Bethard wrote: > >> It's much easier to explain to newcomers that *, + and - work on True >> and False as if they were 1 and 0 than it is to introduce them to a two >> element boolean algebra. So making this kind of change needs a pretty >> strong motivation from real-world code. > > Pretending that False and True are just "magic names" for 0 and 1 might be > "easier" than real boolean algebra, but that puts the cart before the > horse. Functionality comes first: Python has lists and dicts and sets > despite them not being ints, and somehow newcomers cope. I'm sure they > will cope with False and True not being integers either. > > I mean, really, does anyone *expect* True+True to give 2, or that 2**True > even works, without having learnt that Python bools are ints? I doubt it. > > And the old Python idiom for an if...then...else expression: > > ["something", "or other"][True] > > tends to come as a great surprise to most newbies. So I would argue that > bools being ints is more surprising than the opposite would be. I disagree. I think you'd get just as many odd stares if: True + True == True But I think all you're really saying is that newbies don't expect things like +, -, *, etc. to work with bools at all. Which I agree is probably true. So it seems like you're really arguing for raising exceptions in all these situations. That would actually be fine with me since I never use bools as ints, but I suspect getting it past python-dev will be an uphill battle since it will break large chunks of code. STeVe From steve at holdenweb.com Thu Jul 26 09:06:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Jul 2007 09:06:22 -0400 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185453726.559470.122480@x40g2000prg.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> <46a7b908$0$32130$426a34cc@news.free.fr> <1185453726.559470.122480@x40g2000prg.googlegroups.com> Message-ID: walterbyrd wrote: > On Jul 22, 12:17 am, Bruno Desthuilliers > wrote: > >> Either you are a casual user with 101 web >> development skills trying to set up your personal home page > > But this, sort of, brings me back to my original point. Nobody starts > out being advanced. There are substantial differences in cost, and > deployment, between PHP and Python. It is much easier to get started > with PHP. And once somebody has started with PHP, that person is > likely to stay with PHP. Most PHP developers do not see a compelling > reason to start all over again with Python. > > BTW: I have a certain amount of respect for PHP, and PHP developers. > PHP5 is a big step forward over PHP4. And, there have been substantial > web projects completed with PHP - probably more so than with Python. > If PHP does everything they want, why should they change to Python? I am as keen as anyone else to see Python widely adopted, but not at the expense of forcing a tool down an unwilling population's throats. Python is a programming language first, PHP has become one almost incidentally. It's good at (some) things that Python isn't. It's horrible at others (for example OO in PHP is almost as horrible as OO in Perl). Learn to live with 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 http Wed Jul 11 23:25:55 2007 From: http (Paul Rubin) Date: 11 Jul 2007 20:25:55 -0700 Subject: bool behavior in Python 3000? References: <5ficp9F3cram2U2@mid.individual.net> <469472f4$0$1293$9b622d9e@news.freenet.de> <1184140795.974059.302830@22g2000hsm.googlegroups.com> <9v4li.8359$MV6.308@trnddc01> <1184210084.671732.123520@k79g2000hse.googlegroups.com> Message-ID: <7xtzsai9q4.fsf@ruckus.brouhaha.com> tah writes: > This doesn't leave you with anything equivalent to 'not' however. Or > nothing consistent. Currently '~a' will complement a boolean array,: > > >>> ~a > array([False, True, True], dtype=bool) Can you use operator.not_(a) ? From mail at microcorp.co.za Wed Jul 18 02:51:13 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 18 Jul 2007 08:51:13 +0200 Subject: Can a low-level programmer learn OOP? References: Message-ID: <013001c7c90b$99372620$03000080@hendrik> "Dennis Lee Bieber" wrote: > Don't confuse Python's "roaming names" with OOP, though. There are > OOP languages that still follow the variable=>memory address containing > object structure. "roaming names" is a brilliant description! Thanks Dennis! - Hendrik From stingo000 at yahoo.ca Sat Jul 21 18:57:28 2007 From: stingo000 at yahoo.ca (Andrey) Date: Sat, 21 Jul 2007 22:57:28 GMT Subject: UTF-8 Support of Curses in Python 2.5 References: <1183518492.937047.214130@z28g2000prd.googlegroups.com> Message-ID: Yes, it does solve the problem. Compile python with ncursesw library. Btw Ubuntu 7 has it "out of the box". > Hi All, > > Recently I ran into a problem with UTF-8 surrport when using curses > library in python 2.5 in Fedora 7. I found out that the program using > curses cannot print out unicode characters correctly on UTF-8 enabled > console. I googled around and got an impression that the reason for > this problem is that python is linked with libcurses library instead > of libcursesw. The latter one is said to be able to solve this > problem. Has anybody tried this? How to manually let python use > libcursesw? Thanks a lot! > > Here is a test program: > > #!/usr/bin/env python > # -*- coding: utf-8 -*- > import curses > def keyloop(stdscr): > # Clear the screen and display the menu of keys > stdscr_y, stdscr_x = stdscr.getmaxyx() > menu_y = (stdscr_y-3)-1 > str = u'This is my first curses python program. Press \'q\' to > exit. (???)' > stdscr.addstr(menu_y, 4, str.encode('utf-8')) > xpos = stdscr_x / 2 > ypos = stdscr_y / 2 > while (1): > stdscr.move(ypos, xpos) > c = stdscr.getch() > if 0 < c < 256: > c = chr(c) > if c in 'Qq': break > else: pass > elif c == curses.KEY_UP and ypos > 0: ypos -= 1 > elif c == curses.KEY_DOWN and ypos < stdscr_y - 1: ypos += 1 > elif c == curses.KEY_LEFT and xpos > 0: xpos -= 1 > elif c == curses.KEY_RIGHT and xpos < stdscr_x - 1: xpos += 1 > else: pass > def main(stdscr): > keyloop(stdscr) > if __name__ == '__main__': > curses.wrapper(main) From gagsl-py2 at yahoo.com.ar Fri Jul 13 23:16:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 14 Jul 2007 00:16:37 -0300 Subject: Function parameter type safety? References: <1184277163.803229.318660@g4g2000hsf.googlegroups.com> <1184338421.695360.227030@g4g2000hsf.googlegroups.com> Message-ID: En Fri, 13 Jul 2007 11:53:41 -0300, Robert Dailey escribi?: > However, I found it isn't possible since Python > mainly works with strings in file data instead of bytes. To write a > number 400000 to a file in python would take 6 bytes instead of 4, for > example. py> import struct py> f = open("output.bin","wb") py> f.write(struct.pack("l", 400000)) py> f.close() py> ^Z C:\TEMP>dir output.bin El volumen de la unidad C no tiene etiqueta. El n?mero de serie del volumen es: 3828-F1AF Directorio de C:\TEMP 14/07/2007 00:13 4 output.bin 1 archivos 4 bytes 0 dirs 18.806.763.520 bytes libres "strings" are "strings of bytes" in Python. (If you are mostly concerned with characters, use unicode objects). -- Gabriel Genellina From nis at superlativ.dk Mon Jul 2 05:30:15 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Mon, 02 Jul 2007 11:30:15 +0200 Subject: howto resend args and kwargs to other func? In-Reply-To: <4688a103$0$29642$426a34cc@news.free.fr> References: <1183279997.244378.105810@n60g2000hse.googlegroups.com> <1183280667.542964.175570@u2g2000hsc.googlegroups.com> <1183282733.179683.174350@c77g2000hse.googlegroups.com> <5er6doF31bulkU1@mid.individual.net> <4688a103$0$29642$426a34cc@news.free.fr> Message-ID: <4688c5b1$0$90268$14726298@news.sunsite.dk> Bruno Desthuilliers skrev: >> Why do people do this without posting what the actual solution is!!!! > > Probably because those people think usenet is a free help desk ? Usenet definitely isn't a help desk. You often get useful answers from usenet, from people who are not reading from a script. Nis From vedrandekovic at v-programs.com Tue Jul 17 14:26:46 2007 From: vedrandekovic at v-programs.com (...:::JA:::...) Date: Tue, 17 Jul 2007 20:26:46 +0200 Subject: directpython simple texture Message-ID: Hello, Is there any real easy example for loading an texture in your directpython window??? For example this is my code: # loading directpython modules import d3dx import d3d from d3dc import * import d3dgui import time #making a window fr=d3dx.Frame(u"Bok kaj ima") # trying to load an texture t1 = d3d.Texture(u"textures/skin.tiger.dds") d3d.setTexture(t1, 0) #starting the application fr.mainloop() ....after I run this example, all I got is blue,clear frame.Is there really any simple texture example??? Please don't tell me to I look into directpython samples becose it's not helpful!!!!! Thanks!!!!!! __________________________________________________________________ Vedran veki ICQ#: 264412055 Current ICQ status: + More ways to contact me Get ICQ! __________________________________________________________________ From jstroud at mbi.ucla.edu Mon Jul 30 21:11:47 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 30 Jul 2007 18:11:47 -0700 Subject: What is the "functional" way of doing this? In-Reply-To: <1185835690.530367.66600@m37g2000prh.googlegroups.com> References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> Message-ID: beginner wrote: > 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. > > Thanks, > beginner > Does it get any more functional than lambda? py> f = lambda n, r=None: f(n/26, (r if r else [])) + [n%26] if n/26 else [n%26] py> f(300000) [17, 1, 20, 12] py> f(30000) [1, 18, 9, 22] py> f(3000) [4, 11, 10] py> f(1000) [1, 12, 12] -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From spamtrap at dot-app.org Thu Jul 26 20:08:17 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Thu, 26 Jul 2007 20:08:17 -0400 Subject: SQLObject 0.9.1 References: <20070726143614.GI30176@phd.pp.ru> Message-ID: Steve Holden writes: > Sherm Pendley wrote: >> Gerardo Herzig writes: >> >>> So..at 11:23 we got version 0.7.8...at 11:30 was version 0.8.5...now >>> there is a 0.9.1 version?? Have a coffe dude >> >> Sounds more to me like he needs to lay off the coffee, or at least switch >> to decaffeinated for a while. :-) >> > Come on, give Oleg a break. He's maintaining three separate versions > in parallel. What part of ":-)" did you not understand? sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From arkanes at gmail.com Thu Jul 26 17:07:40 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 26 Jul 2007 16:07:40 -0500 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? In-Reply-To: <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> Message-ID: <4866bea60707261407k7ce2ac68lacfc893c4e7fc958@mail.gmail.com> On 7/26/07, Stefan Scholl wrote: > Stefan Behnel wrote: > > The XML is *not* well-formed if you pass Python unicode instead of a byte > > encoded string. Read the XML spec. > > Pointers, please. > > Last time I read that part of the spec was when a customer's > consulting company switched to ISO-8859-15 without saying > something beforehand. The old code (PHP) I have to maintain > couldn't deal with it. > > It was wrong to switch encoding without telling somebody about > it. And a XML processor isn't required to support ISO-8859-15. > But I thought it was too embarrassing not to support this > encoding. I fixed that part without making a fuss. > > > A Python XML processor that can't handle the own encoding is > embarrassing. It isn't required to support it. It would be OK if > it wouldn't support UTF-7. But a parseString() method that > doesn't want Python strings? No way! > Of course it can handle its own encoding. But you're passing incorrect values to it, the same way that passing '10' to a function expecting an int is going to fail. cStringIO in python 2.4 is buggy - when passed a unicode object, it silently uses the (platform and compilation dependent) internal buffer of the unicode object. In 2.5 this was corrected to be consistent with all other unicode/str conversions and encode it using the default encoding, failing when that's not possible (as in your example). It's not that your code worked on 2.4, and 2.5 broke it - the 2.4 code was subtly buggy and 2.5 is preventing you from having that bug. XML is not a string. It's a specific type of bytestream. If you want to work with XML, then generate well-formed XML in the correct encoding. There's no reason you should have an XML document (as opposed to values extracted from that document) in unicode objects at all. From carsten at uniqsys.com Sat Jul 21 00:26:19 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 21 Jul 2007 00:26:19 -0400 Subject: Pythonic way for missing dict keys In-Reply-To: References: Message-ID: <20070721041351.M63697@uniqsys.com> On Sat, 21 Jul 2007 09:22:32 +0530, Rustom Mody wrote > Can someone who knows about python internals throw some light on why > >>> x in dic > is cheaper than > >>> dic.has_key(x) > > ?? I won't claim to know Python internals, but compiling and disassembling the expressions in question reveals the reason: >>> from compiler import compile >>> from dis import dis >>> dis(compile("dic.has_key(x)","","eval")) 1 0 LOAD_NAME 0 (dic) 3 LOAD_ATTR 1 (has_key) 6 LOAD_NAME 2 (x) 9 CALL_FUNCTION 1 12 RETURN_VALUE >>> dis(compile("x in dic","","eval")) 1 0 LOAD_NAME 0 (x) 3 LOAD_NAME 1 (dic) 6 COMPARE_OP 6 (in) 9 RETURN_VALUE "dic.has_key(x)" goes through an attribute lookup to find the function that looks for the key. "x in dic" finds the function more directly. -- Carsten Haese http://informixdb.sourceforge.net From josiah.carlson at sbcglobal.net Tue Jul 10 02:11:13 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Tue, 10 Jul 2007 06:11:13 GMT Subject: trouble controlling vim with subprocess on windows machine In-Reply-To: <1184023825.646120.251060@d55g2000hsg.googlegroups.com> References: <1183970186.663847.4380@o61g2000hsh.googlegroups.com> <1184023825.646120.251060@d55g2000hsg.googlegroups.com> Message-ID: <5qFki.19733$2v1.4163@newssvr14.news.prodigy.net> Eric_Dexter at msn.com wrote: > On Jul 9, 11:06 am, Josiah Carlson > wrote: >> Eric_Dex... at msn.com wrote: >>> I am having trouble contolling vim with subprocess on a windows >>> machine. It appears that vim comes up on the machine all right and it >>> sometimes looks like it is doing the searchs what I am asking it to do >>> but when I am asking it to load a file it doesn't do anything. Is >>> there something I need to do to push the data through the pipe?? Here >>> is a couple different ways I am trying to do it. >> [snip] >> >> This recipe for asynchronous communication using subprocess could be >> used to write an expect-like tool: >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 >> >> It works on both Windows and *nix. >> >> - Josiah > > I had the original dir work but when I tried to trade it out with vim > it isn't clear > how I should call it.. vim filename and it doesn't find filename for > some reason. > I called it pipe and then > > > inport pipe > > def load_instrument3(instr_name, csd_name): > if sys.platform == 'win32': > shell, commands, tail = ('gvim' + csd_name, (csd_name, > csd_name), '\r\n') > else: > shell, commands, tail = ('sh', ('ls', 'echo HELLO WORLD'), > '\n') > > a = pipe.Popen(shell, stdin=pipe.PIPE, stdout=pipe.PIPE) > print pipe.recv_some(a), > for cmd in commands: > pipe.send_all(a, csd_name) > print pipe.recv_some(a), > pipe.send_all(a, csd_name) > print pipe.recv_some(a, e=0) > a.wait() The example uses a platform-specific shell in order to use the environment variable PATH to discover the executable to run. If you know the exact path to your binary ('gvim' for you), it should work. As-is, your program would require a binary with the name 'gvim'+csd_name in the same path as the script you are executing. - Josiah From sandravandale at yahoo.com Tue Jul 24 13:58:18 2007 From: sandravandale at yahoo.com (Sandra-24) Date: Tue, 24 Jul 2007 10:58:18 -0700 Subject: Hacking with __new__ In-Reply-To: <46a5d26b$0$18658$426a74cc@news.free.fr> References: <1185241394.990936.206360@k79g2000hse.googlegroups.com> <46a5d26b$0$18658$426a74cc@news.free.fr> Message-ID: <1185299898.927797.29520@g4g2000hsf.googlegroups.com> On Jul 24, 5:20 am, Bruno Desthuilliers wrote: > IIRC, __new__ is supposed to return the newly created object - which you > are not doing here. > > class Bar(Foo): > def __new__(cls, a, b, c, *args): > print 'Bar.__new__', len(args) > if not args: > cls = Zoo > obj = super(Bar, cls).__new__(cls, a, b, c, *args) > if not args: > obj.__init__(a, b, c, 7) > return obj Thanks guys, but you are right Bruno, you have to return the newly created object or you get: >>> b = Bar(1,2,3) Bar.__new__ 0 Foo.__new__ 3 Zoo.__init__ 4 Foo.__init__ 3 >>> b is None True However, if you return the object you get: >>> b = Bar(1, 2, 3) Bar.__new__ 0 Foo.__new__ 3 Zoo.__init__ 4 Foo.__init__ 3 Traceback (most recent call last): File "", line 1, in TypeError: __init__() takes exactly 5 arguments (4 given) Which is the same blasted error, because it seems to want to call init on the returned object and it's calling it with 4 args :( Is there any way around that? Thanks, -Sandra From gianmaria at hotmail.com Sat Jul 28 19:15:28 2007 From: gianmaria at hotmail.com (Gianmaria) Date: Sun, 29 Jul 2007 01:15:28 +0200 Subject: Events: The Python Way Message-ID: Hi, i'm a .net programmer and i'm learnig python, so this question can be very stupid or easy for python programmers. I've a doubt about events.... here is what: in c# for example i can write a delegate and an event in this way... public delegate SomethingChangedHandler(string message); public event SomethingChangedHandler SomethingChanged; and later in the code fire this event in this way... if(SomethingChanged != null) { SomethingChanged("Nothing important"); } and the subscription of this event of other objects can be easy as eventGeneratorObject.SomethingChanged += new SomethingChangedHandler(aFunctionto_takecareof_it); and even the handlig of the event is aesy... void aFunctionto_takecareof_it(string msg) { } ....now the question is.. how can i do the same using Python? Every help is appreciated Regards, Gianmaria From infocat at earthlink.net Tue Jul 3 22:42:17 2007 From: infocat at earthlink.net (Frank Swarbrick) Date: Tue, 03 Jul 2007 20:42:17 -0600 Subject: Python compilation ?? In-Reply-To: References: Message-ID: <5f0fo7F39tfbtU1@mid.individual.net> John Nagle wrote: > Evan Klitzke wrote: >> On 7/2/07, Cathy Murphy wrote: >> >>> Is python a compiler language or interpreted language. If it is >>> interpreter >>> , then why do we have to compile it? >> > Iron Python compiles to Microsoft's byte code as used by their > ".NET" common language runtime. This is then compiled to machine > code by a just-in-time compiler. Does Iron Python compile to free-standing executables, or is there an Iron Python interpreter that is always necessary? Frank From florent.cayre at snecma.fr Mon Jul 9 04:14:04 2007 From: florent.cayre at snecma.fr (florent.cayre at snecma.fr) Date: Mon, 9 Jul 2007 10:14:04 +0200 Subject: Florent CAYRE/SN09/SNECMA est absent. Message-ID: Je serai absent(e) du 19/02/2007 au 17/12/2007. Bonjour, je suis en cong=E9 sabbatique pour une dur=E9e de 10 mois. En mon absence, adressez-vous =E0 Christophe Baudoin pour tout ce qui concerne l'unit=E9 M=E9thodes et Outils du d=E9veloppement / A=E9rothermique= et Combustion. Florent Cayr=E9. #=0A= " This e-mail and any attached documents may contain confidential or proprie= tary information. If you are not the intended recipient, please advise the s= ender immediately and delete this e-mail and all attached documents from you= r computer system. Any unauthorised disclosure, distribution or copying here= of is prohibited."=0A= =0A= " Ce courriel et les documents qui y sont attaches peuvent contenir des inf= ormations confidentielles. Si vous n'etes pas le destinataire escompte, mer= ci d'en informer l'expediteur immediatement et de detruire ce courriel ains= i que tous les documents attaches de votre systeme informatique. Toute divul= gation, distribution ou copie du present courriel et des documents attaches= sans autorisation prealable de son emetteur est interdite."=0A= # From stargaming at gmail.com Tue Jul 24 10:15:08 2007 From: stargaming at gmail.com (Stargaming) Date: 24 Jul 2007 14:15:08 GMT Subject: Recursive lists References: <1185268478.433070.291370@q75g2000hsh.googlegroups.com> Message-ID: <46a6096c$0$8399$9b622d9e@news.freenet.de> On Tue, 24 Jul 2007 02:14:38 -0700, mizrandir wrote: > Can someone tell me why python doesn't crash when I do the following: > >>>> a=[] >>>> a.append(a) >>>> print a > [[...]] >>>> print a[0][0][0][0][0][0][0] > [[...]] > > How does python handle this internally? Will it crash or use up lot's of > memory in similar but more complicated cases? It should be like you pointing your finger at yourself and yelling I guess. Just a reference, no new object. From http Thu Jul 26 19:41:28 2007 From: http (Paul Rubin) Date: 26 Jul 2007 16:41:28 -0700 Subject: Learning Jython? References: <1185489708.437968.74890@57g2000hsv.googlegroups.com> Message-ID: <7xmyxiwx5j.fsf@ruckus.brouhaha.com> Matt Bitten writes: > It looks like Jython is for me. That said, I have two questions: > (1) Am I thinking straight here? Or is there some other solution that > a knows-Python-but-not-Java programmer might use? You are thinking of embedding Jython in a web applet? Probably not such a great idea, due to its size. From gagsl-py2 at yahoo.com.ar Thu Jul 12 22:23:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Jul 2007 23:23:05 -0300 Subject: diferent answers with isalpha() References: <1184285142.547758.57760@22g2000hsm.googlegroups.com> Message-ID: En Thu, 12 Jul 2007 21:05:42 -0300, escribi?: > Hi, > > I have python with sys.version_info = (2, 4, 4, 'final', 0) > > In Idle when I do print '?'.isalpha() I get True. When I make and > execute a script file with the same code I get False. > > Why do I have diferent answers ? Do you include an encoding directive at the top? (If you omit it you get a warning in 2.4 and an error in 2.5) Try this: import unicodedata print unicodedata.name(u'?') from IDLE and from inside a script. You should get "LATIN SMALL LETTER A WITH ACUTE"; if not, Python thinks your terminal uses a different encoding than the actual one. -- Gabriel Genellina From a.schmolck at gmail.com Thu Jul 12 17:19:37 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Thu, 12 Jul 2007 22:19:37 +0100 Subject: bool behavior in Python 3000? References: Message-ID: Steven D'Aprano writes: > Expressions like (i == j) used to return 0 and 1, and it was to avoid > breaking hacks like the above that bools were implemented as a subclass of > int, not because being able to write the above was a specific feature > requested. In the hypothetical bright new world of Python with bools that > are actually bools, the above are good cases for explicit being better than > implicit: > > int(x < b) * f(x) > -1 ** int(i == j) > > It makes more sense to explicitly cast bools to ints when you want to > do integer arithmetic on them, rather than explicitly casting bools to > bools to do boolean arithmetic! I feel strongly enough about this that I > believe that being able to write (x < b) * f(x) is a DISADVANTAGE -- it > gives me a real WTF moment to look at the code. Just because it looks funny to you doesn't mean it is a hack. It turns out that many mathemtical formulas can be written more clearly using this notation (see e.g. at knuth et al's "concrete mathematics"), and in mathematics limited and often ambiguous ad hoc notation that is neatly subsumed by this scheme is widely established. And I don't think adding int is an improvement: ``(x < b) * f(x)`` is plenty clear (not easily misread as something else and, I believe, not even particularly difficult to figure out even for mediocre python programmers) but adding padding just obscures formula structure. Of course it doesn't in the above examples with less than half a dozen terms, but IMO for something longer the int-litter, even it may be soothing the psyches of the anally retentive, is counterproductive. 'as From wildemar at freakmail.de Sun Jul 22 15:27:23 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Sun, 22 Jul 2007 21:27:23 +0200 Subject: split on NO-BREAK SPACE In-Reply-To: References: Message-ID: <46A3AF9B.4010909@freakmail.de> Peter Kleiweg wrote: > > Define white space to isspace() > > Explain that phrase. > > Here is another "space": > > >>> u'\uFEFF'.isspace() > False > > isspace() is inconsistent > I don't really know much about unicode, but google tells me that \uFEFF is a byte order mark. I thought we we're implicitly in unison that "whitespace" (whatever the formal definition) means "the stuff we put into text to visually separate words". So what is *your* definition of whitespace? >>> Why does split() split when it says NO-BREAK? >>> >> Precisely. It says NO-BREAK. It doesn't say NO-SPLIT. >> > > That is a stupid answer. > > I fail to see why you deem it a good idea to become insulting at this point. It is a very valid answer: NO-BREAK means "when wrapping characters into paragraphs do not break at this space". split() however does not wrap text, it /splits/ it (at whitespace characters, as it happens). The NO-BREAK semantic has no meaning here. /W From bthate at gmail.com Mon Jul 9 02:30:23 2007 From: bthate at gmail.com (bthate) Date: Mon, 09 Jul 2007 06:30:23 -0000 Subject: ANN: gozerbot 0.7 released In-Reply-To: <87lkdqm9mc.fsf@benfinney.id.au> References: <1183935992.848431.131890@r34g2000hsd.googlegroups.com> <87lkdqm9mc.fsf@benfinney.id.au> Message-ID: <1183962623.941986.109670@w3g2000hsg.googlegroups.com> On 9 jul, 07:25, Ben Finney wrote: > bthate writes: > > it time for a new gozerbot release ! we made a 0.7 release of > > gozerbot. > > When announcing a new release, please include a brief "What is > gozerbot?" explanation section so that readers can know whether the > announcement is of interest. > > -- > \ "Pinky, are you pondering what I'm pondering?" "Well, I think | > `\ so, Brain, but first you'd have to take that whole bridge | > _o__) apart, wouldn't you?" -- _Pinky and The Brain_ | > Ben Finney sorry forgot about it ;] will do so the next time. Bart From kelybrown at gmail.com Thu Jul 26 14:05:21 2007 From: kelybrown at gmail.com (K. Brown) Date: Thu, 26 Jul 2007 11:05:21 -0700 Subject: =?utf-8?B?4peY4pa6QWNjZXNzIEZSRUUgU2F0ZWxsaXRlIFRWIG9uIHlvdXIgUEMgb3IgTGFwdG9w4peE4peY?= Message-ID: <1185473121.189553.106580@o61g2000hsh.googlegroups.com> Legally Access 1000's of Television Channels From All Over The World Watch all your favorite shows on your Computer! Save 1000's of $$$ over many years on cable and satellite bills. INSTANT DOWNLOAD Learn More About it at Link below: http://tvonpc.cq.bz From len-l at telus.net Sun Jul 1 16:37:34 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Sun, 01 Jul 2007 20:37:34 GMT Subject: ctype and functions that return a pointer to a structure In-Reply-To: References: Message-ID: hg wrote: > Hi, > > I have the following code: > ****************************************** > from ctypes import * > g_lib = cdll.LoadLibrary("libc.so.6") > class Struct_Password(Structure): > """ > > """ > _fields_ = [ ('name', c_char_p), > ('code', c_char_p), > ('date', c_long), > ('min', c_long), > ('max', c_long), > ('warn', c_long), > ('inact', c_long), > ('expire', c_long), > ('flag', c_ulong) > ] > l_res = g_lib.getspnam('john') > l_struct = cast(l_res, POINTER( Struct_Password() ) ) l_struct = cast(l_res, POINTER( Struct_Password ) ) POINTER wants a ctypes type as an argument. Struct_Password() is a Structure instance. A better way to do it is define the return type for getspnam: g_lib.getspnam.restype = POINTER( Struct_Password ) Now the function returns a structure pointer so the cast is unnecessary. --- Lenard Lindstrom From gagsl-py2 at yahoo.com.ar Sun Jul 29 11:15:18 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 29 Jul 2007 12:15:18 -0300 Subject: interpreter in the background References: <51D13D69-EEA7-42B3-B05D-B18716F6F24D@tiscalinet.it> Message-ID: En Sat, 28 Jul 2007 08:29:38 -0300, Andrea Tomadin escribi?: > I need to use the Python interpreter as if it were a Matlab or > Mathematica "kernel", i.e. running in the background while I use an > interface program to send commands and get output. Try building something around the code module -- Gabriel Genellina From aahz at pythoncraft.com Sun Jul 15 19:07:43 2007 From: aahz at pythoncraft.com (Aahz) Date: 15 Jul 2007 16:07:43 -0700 Subject: Pass by reference or by value? References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> <1184385535.558451.306630@22g2000hsm.googlegroups.com> Message-ID: [posted and e-mailed] [top-posting because I want to make only a one-line response] Please stick this on a web-page somewhere -- it makes an excellent counterpoint to http://starship.python.net/crew/mwh/hacks/objectthink.html http://effbot.org/zone/python-objects.htm In article <1184385535.558451.306630 at 22g2000hsm.googlegroups.com>, sturlamolden wrote: >On Jul 13, 9:10 pm, Robert Dailey wrote: > >> I noticed in Python all function parameters seem to be passed by >> reference. This means that when I modify the value of a variable of a >> function, the value of the variable externally from the function is >> also modified. > > >Pass-by-value and pass-by-reference usually refer to the semantics >used in C and Fortran, respectively. > > >Here is an example showing the distinction between the 'pass-by-value' >semantics of C and the 'pass-by-reference' semantics of Fortran: > > >In C you can pass pointers, but it is still a pure 'pass-by-value' >semantics. The pointer itself is passed by value (which is an >address). What that means, is that the function receives a copy of the >argument used in the call: > >int a = 1; >foo(&a); >bar(&a); > >void foo(int *a) >{ > a = (int*) 0; /* no side effect */ >} > >void bar(int *a) >{ > *a = 0; /* side effect, but a is still passed by value */ >} > >Now take a look at how the functions foo and bar are called. They both >have the same signature, >void ()(* int). Thus they must be called equivalently. But still one >produces a side-effect and the other does not. Often in C litterature >you can see what happens in the function bar called 'pass-by- >reference'. But that is very incorrect, C never passes anything by >reference. > >'Pass-by-value' is thus equivalent to 'pass-a-copy'. > > >In Fortran you can only pass references. > >integer(4) :: a >a = 1 >call bar(a) > >subroutine bar(a) >integer(4) :: a >a = 0 ! side-effect >end subroutine > >That means, when a variable is used to call a function, the function >receives a pointer to the actual argument, not a local copy. That is >very different from C's copy-passing behaviour. > >C++ can pass-by-value and pass-by-reference: > >int a = 1; >foo(&a); // no side-effect >bar(&a); // side-effect >foo2(a); // no side-effect >bar2(a); // side-effect!!! > >void foo(int *a) // pass-by-value >{ > a = (int*) 0; // no side effect >} > >void bar(int *a) // pass-by-value >{ > *a = 0; // side effect, but a is still passed by value >} > > >void foo2(int a) // pass-by-value >{ > a = 0; // no side effect !!! >} > > >void bar2(int &a) // pass-by-reference >{ > a = 0; // side effect !!! >} > >The C++ example clearly shows what we mean by pass-by-reference. It >seems when we call the function bar2 that we give it the value of a, >when we in fact give it a reference to a. That is the same thing that >happens in Fortran. > >What it all boils down to is this: > > >Local copies are made in the 'pass-by-value' semantics. >Local copies are not made in the 'pass-by-reference' semantics. > > > >Now that we have defined 'pass-by-value' and 'pass-by-reference' >precisely, it is time to examine what Python does. > >It turns out that Python neither works like C nor like Fortran. >Rather, Python works like LISP. That is: > > >Python names are pointers bound to values. >Python always pass pointers to values. >Python never pass local copies. >Function arguments are referenced by names in the function's local >namespace. >Names referencing function arguments can be rebound in the local >scope. > > >>From this you might think that Python does pass-by-reference. Afterall >it does not create local copies. But as names can be rebound in the >local scope, function calls in Python and Fortran behave very >differently. > >That is: > >a = 1 # a points to an int(1) >foobar(a) ># a still points to an int(1) > >def foobar(a): > a = 0 # rebinds a locally, produces no side-effect > # in Fortran this would have produced a side-effect > > >Now, examine this code sniplet: > >a = 1 # a points to an int(1) >foobar(a) ># a still points to an int(1) as an int is immutable >a = [1, 2, 3] # rebinds a, a points to a mutable type >foobar(a) ># a points to [1,2,3,1,2,3] > >def foobar(a): > a *= 2 # rebinds a only if a points to an immutable type, > # otherwise the value pointed to by a is changed > > >If you take a careful look at these examples, you should be able to >figure out what Python does. > >Python does 'pass-by-reference' in the sense that it always pass >pointers. > >Python does 'pass-by-value' in the sense that names has a local scope >and can be rebound in the local scope. > >The correct statement would be to say that Python does neither pass-by- >reference nor pass-by-value in the conventional meaning of the terms. > >Rather Python does 'pass-as-lisp'. > > > >Sturla Molden > > > >P.S. You could think of Python as a Java only having reference types. >What makes the semantics of Java and C# 'pass-by-value' like C, is the >fact that they make copies of value-types when passed to a function. A >reference type is also passed by value, in this case the value of the >reference is passed. Python does not have value types. But Python does >have immutable types. An int is an immutable type in Python and a >value type in Java. What happens when Python and Java calls a function >with an int as argument is very different. Java makes a copy of the >int and passes that. Python passes a pointer to the int. But as an int >is immutable in Python, it may look like Python passes ints 'by value' >when in fact it never creates a local copy. > > > > > > -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I support the RKAB From chris at simplistix.co.uk Tue Jul 31 15:47:58 2007 From: chris at simplistix.co.uk (Chris Withers) Date: Tue, 31 Jul 2007 20:47:58 +0100 Subject: MailingLogger 3.2.0 Released! Message-ID: <46AF91EE.6020700@simplistix.co.uk> With help from Jens Vagelpohl, I'm pleased to announce a new release of Mailinglogger that now supports filtering of log entries... Mailinglogger enables log entries to be emailed either as the entries are logged or as a summary at the end of the running process. This pair of enhanced emailing handlers for the python logging framework is now available as a standard python package and as an egg. The handlers have the following features: - customisable and dynamic subject lines for emails sent - emails sent with an X-Mailer header for easy filtering - flood protection to ensure the number of emails sent is not excessive - support for SMTP servers that require authentication - fully documented and tested In addition, extra support is provided for configuring the handlers when using ZConfig, Zope 2 or Zope 3. Installation is as easy as: easy_install mailinglogger For more information, please see: http://www.simplistix.co.uk/software/python/mailinglogger cheers, Chris -- Simplistix - Content Management, Zope & Python Consulting - http://www.simplistix.co.uk From eopadoan at altavix.com Wed Jul 25 15:05:49 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Wed, 25 Jul 2007 16:05:49 -0300 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <1185379218.286977.124040@19g2000hsx.googlegroups.com> <1185384306.104549.287510@19g2000hsx.googlegroups.com> <1185384793.577650.256310@d55g2000hsg.googlegroups.com> Message-ID: def flatten(listOfLists): return list(chain(*listOfLists)) >From http://www.python.org/doc/2.4/lib/itertools-recipes.html -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From nagle at animats.com Thu Jul 12 23:58:32 2007 From: nagle at animats.com (John Nagle) Date: Thu, 12 Jul 2007 20:58:32 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <468565a0$0$3686$426a74cc@news.free.fr> <7xvecumrte.fsf@ruckus.brouhaha.com> <1i13w96.kyyobph71qxrN%aleax@mac.com> <7xwsx63we6.fsf@ruckus.brouhaha.com> <878x9llv5x.fsf@benfinney.id.au> Message-ID: Chris Mellon wrote: > You can't prove a program to be correct, in the sense that it's proven > to do what it's supposed to do and only what it's supposed to do. Actually, you can prove quite a bit about programs with the right tools. For example, proving that a program cannot subscript out of range is quite feasible. (Although not for C, where it's most needed; that language is just too ill-defined.) You can prove that certain assertions about an object always hold when control is outside the object. You can prove that certain entry conditions for a function are satisfied by all its callers. Take a look at what the "Spec#" group at Microsoft is doing. There's also some interesting USAF work on avionics at http://www.stsc.hill.af.mil/crossTalk/2006/09/0609SwardGerkenCasey.html But it's not a very active field right now. The basic problem is that C and C++ aren't well suited to proof of correctness, yet none of the other hard-compiled languages have any significant market share left. This is irrelevant to Python issues, though. John Nagle From sjmachin at lexicon.net Mon Jul 16 18:29:54 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 16 Jul 2007 15:29:54 -0700 Subject: zipfile 2GB problems? In-Reply-To: <1184621861.925437.64900@w3g2000hsg.googlegroups.com> References: <1184474112.081258.111490@n60g2000hse.googlegroups.com> <1184525970.082235.238200@q75g2000hsh.googlegroups.com> <1184528949.751377.5620@g4g2000hsf.googlegroups.com> <1184612398.359979.28900@d55g2000hsg.googlegroups.com> <1184621861.925437.64900@w3g2000hsg.googlegroups.com> Message-ID: <1184624994.008721.139080@e16g2000pri.googlegroups.com> On Jul 17, 7:37 am, xamdam wrote: > On Jul 16, 3:39 pm, Steve Holden wrote: > > > > > xamdam wrote: > > > On Jul 15, 5:39 pm, Steve Holden wrote: > > >> xamdam wrote: > > >>>>> Additional info: my file is from a data provider, do not know what > > >>>>> they used to compress it. Previous files worked ok, this one is the > > >>>>> 1st over 2GB. Winzip has no problem with it. > > >>>> It could be you are using a Python with an in-built limit of 2GB on file > > >>>> size. What happens if you open the file, seek past the 2GB point and > > >>>> then try and read data? > > >>> Steve, > > >>> I used is_zipfile function, which from does exactly that from a quick > > >>> read - goes to the end, reads expected string. It worked fine. Tried > > >>> regular Windows 2.4.4 and 2.5.1, same result. > > >> Fine, if it isn't file size limitations I suspect you need to post some > > >> code and a traceback so we can get better insight into exactly what the > > >> problem is. > > > > It's failing in the ZipFile constructor, which ends up throwing > > > > zipfile(2.4.3).py:291> raise BadZipfile, "Bad magic number for file > > > header" > > > Well, that one bald line by itself certainly doesn't give *me* any > > traction an what the problem might be. Getting information about this > > problem is like (i.e. as difficult as) pulling teeth! > > > regards > > Steve > > Well, Steve, I don't know what else to tell you "post some code and a traceback" > I certainly do not > want to cause you tooth ache! I suspect that you are inducing unwanted symptoms at the *other* end of Steve's alimentary canal. > I was sort of hoping for some ZIP expert > to go, 'oh, yeah'... Hope all you want, but supply the information you are asked for. From mccredie at gmail.com Thu Jul 19 17:56:32 2007 From: mccredie at gmail.com (Matt McCredie) Date: Thu, 19 Jul 2007 14:56:32 -0700 Subject: How to check if an item exist in a nested list In-Reply-To: <266557d0707191443h36eceddoca7bb626f0e0a022@mail.gmail.com> References: <266557d0707191443h36eceddoca7bb626f0e0a022@mail.gmail.com> Message-ID: <9e95df10707191456y36a05682m8549c5fad4f4e9c8@mail.gmail.com> > Is there any way to check if an item in specific location in a multiple > dimension nested exist? For example something like: > > if M_list[line][row][d] exist: > do_something_0 > else: > do_something_1 > Certainly: try: M_list[line][row][d] except IndexError: do_something_1 else: do_something_0 Assuming that you want to check because something in `do_someting_0' fails if the item isn't defined, it is very likely that this can be shortened to: try: do_something_0 except IndexError: do_something_1 The try/except should be wrapped as tightly as possible around the specific code that actually throws the exception. Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.rawlins at thinkbluemedia.co.uk Wed Jul 4 06:00:59 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 4 Jul 2007 11:00:59 +0100 Subject: Which Python Version Message-ID: <00b101c7be22$51649420$f42dbc60$@rawlins@thinkbluemedia.co.uk> Hello Chaps, Is there a command I can run to confirm which version of python I'm running? Another thing I've always wondered, should i be running my applications using './MyFile.py' or 'Python MyFile.Py' what are the benefits of each method? One thing I have noticed is that when I used 'Python MyFile.Py' my processor usage was a lot higher, is that normal? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From wildemar at freakmail.de Thu Jul 5 17:55:11 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Thu, 05 Jul 2007 23:55:11 +0200 Subject: list.append not working? In-Reply-To: <1183651889.219469.64950@n60g2000hse.googlegroups.com> References: <1183651138.209079.37620@q75g2000hsh.googlegroups.com> <1183651889.219469.64950@n60g2000hse.googlegroups.com> Message-ID: <468D68BF.2030109@freakmail.de> 7stud wrote: > Hardy wrote: > >> I experience a problem with append(). This is a part of my code: >> >> for entity in temp: >> md['module']= entity.addr.get('module') >> md['id']=entity.addr.get('id') >> md['type']=entity.addr.get('type') >> #print md >> mbusentities.append(md) >> #print mbusentities >> >> I want something like: [{'module': 'home', 'id': 123, 'type': 'core'}, >> {'module': 'work', 'id': 456, 'type': 'core'}] >> md is always correct, BUT:mbusentities is wrong. Length of >> mbusentities is same of temp, so it appended everything. BUT: >> mbusentities only shows the values of the last append: [{'module': >> 'work', 'id': 456, 'type': 'core'}, {'module': 'work', 'id': 456, >> 'type': 'core'}] >> >> What's wrong? >> > > Inside your loop, you assign md["module"], md["id"], and md["type"] > the same values over and over again. > > I may seem like a prick, but that is not the correct answer (infidel and Abhishek gave the correct explanation). I just thought I'd point this out to avoid confusion. /W From sjmachin at lexicon.net Tue Jul 31 09:00:31 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 31 Jul 2007 06:00:31 -0700 Subject: simple string backspace question In-Reply-To: <1185885183.303481.26120@19g2000hsx.googlegroups.com> References: <1185875052.153091.23300@19g2000hsx.googlegroups.com> <1185876068.755101.316320@b79g2000hse.googlegroups.com> <1185884227.491711.105160@x35g2000prf.googlegroups.com> <1185885183.303481.26120@19g2000hsx.googlegroups.com> Message-ID: <1185886831.296890.312060@e9g2000prf.googlegroups.com> On Jul 31, 10:33 pm, Dustan wrote: > On Jul 31, 7:17 am, John Machin wrote: > > > > > On Jul 31, 8:01 pm, vedrandeko... at v-programs.com wrote: > > > > On 31 srp, 11:44, vedrandeko... at v-programs.com wrote: > > > > > Hello, > > > > > I have one simple string, backspace character question.Here is my > > > > example: > > > > > >>> text="Hello\bworld" > > > > >>> print text > > > > > "HelloBSworld" > > > > > Should this character "\b" (backspace) in this text return this: > > > > "Helloworld"? > > > > > Regards, > > > > Vedran > > > > Hi, > > > > If you mean on operating system then unfortunately Windows XP. > > > Point (1) Works on Windows XP for me: > > > C:\junk>ver > > > Microsoft Windows XP [Version 5.1.2600] > > > C:\junk>\python25\python > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > > (Intel)] on win32 > > Type "help", "copyright", "credits" or "license" for more information. > > > >>> text = "Hello\bworld" > > >>> print text > > Hellworld > > > or, for mild amusement: > > > >>> import sys, time > > >>> for x in xrange(100): > > > ... sys.stdout.write("|/-\\"[x & 3] + "\b") > > ... time.sleep(0.1) > > ... > > Now try it on IDLE. So the OP should have been slagging off at PythonWin and IDLE, not at Windows. From bignose+hates-spam at benfinney.id.au Thu Jul 26 19:48:47 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 27 Jul 2007 09:48:47 +1000 Subject: code indentation References: <1185297657.186852.136950@k79g2000hse.googlegroups.com> <87lkd5jt83.fsf@benfinney.id.au> <1185357861.989194.117000@r34g2000hsd.googlegroups.com> <1185387723.155661.311510@b79g2000hse.googlegroups.com> Message-ID: <87myxihgkg.fsf@benfinney.id.au> Steve Holden writes: > We should be making allowances for this particular poster on account > of relative youth: I hadn't realised earlier, but we are dealing > with a fourteen-year-old. I don't believe that's true. One of the great advantages of discussion over the internet is that one's behaviour is what is judged, without necessary prejudice from one's age, skin tone, facial features, or the like. Set against the many disadvantages of internet discussion, I think "judge only on basis of behaviour" is a good default. -- \ "Pinky, are you pondering what I'm pondering?" "Well, I think | `\ so, Brain, but first you'd have to take that whole bridge | _o__) apart, wouldn't you?" -- _Pinky and The Brain_ | Ben Finney From jasondrew72 at gmail.com Thu Jul 12 13:22:36 2007 From: jasondrew72 at gmail.com (Jason Drew) Date: Thu, 12 Jul 2007 17:22:36 -0000 Subject: Lists in classes In-Reply-To: References: <1184253811.052346.220470@22g2000hsm.googlegroups.com> <1184254414.236260.108860@m3g2000hsh.googlegroups.com> Message-ID: <1184260956.212039.212960@57g2000hsv.googlegroups.com> Thanks for clearing up the other incorrect answers! In true Python fashion, I would also remind everyone of the *documentation* - in particular the Python tutorial. These are very elementary mistakes to be making - even worse as part of attempted answers. The Python tutorial is at http://docs.python.org/tut/tut.html In particular see the section on classes: http://docs.python.org/tut/node11.html Note however that the tutorial doesn't show the current best practice of subclassing your classes from "object", i.e. class MyClass(object): #...etc... -Jason On Jul 12, 11:51 am, Wildemar Wildenburger wrote: > Bart Ogryczak wrote: > > On 12 jul, 17:23, Jeremy Lynch wrote: > > >> Hello, > > >> Learning python from a c++ background. Very confused about this: > > >> ============ > >> class jeremy: > >> list=[] > > > You've defined list (very bad choice of a name, BTW), as a class > > variable. To declare is as instance variable you have to prepend it > > with "self." > > Ouch! > > 'self' is *not* a reserved ord in python, it doesn't do anything. So > just popping 'self' in front of something doesn't bind it to an instance. > Here is how it works: > > class Jeremy(object): # you better inherit from 'object' at all times > classlist = [] # class variable > def __init__(self): # "constructor" > self.instancelist = [] # instance variable > def add_item(self, item): > self.instancelist.append(item) > > 'self' is the customary name for the first argument of any instance > method, which is always implicitly passed when you call it. I think it > translates to C++'s 'this' keyword, but I may be wrong. Simply put: The > first argument in an instance-method definition (be it called 'self' or > otherwise) refers to the current instance. > Note however that you don't explicitly pass the instance to the method, > that is done automatically: > > j = Jeremy() # Jeremy.__init__ is called at this moment, btw > j.add_item("hi") # See? 'item' is the first arg you actually pass > > I found this a bit confusing at first, too, but it's actually very > clean, I think. > /W From musiccomposition at gmail.com Tue Jul 17 22:41:29 2007 From: musiccomposition at gmail.com (Benjamin) Date: Wed, 18 Jul 2007 02:41:29 -0000 Subject: wxPython and threads Message-ID: <1184726489.112138.96350@z28g2000prd.googlegroups.com> I'm writing a search engine in Python with wxPython as the GUI. I have the actual searching preformed on a different thread from Gui thread. It sends it's results through a Queue to the results ListCtrl which adds a new item. This works fine or small searches, but when the results number in the hundreds, the GUI is frozen for the duration of the search. I suspect that so many search results are coming in that the GUI thread is too busy updating lists to respond to events. I've tried buffer the results so there's 20 results before they're sent to the GUI thread and buffer them so the results are sent every .1 seconds. Nothing helps. Any advice would be great. From marduk at nbk.hopto.org Mon Jul 16 13:57:30 2007 From: marduk at nbk.hopto.org (marduk) Date: Mon, 16 Jul 2007 12:57:30 -0500 Subject: Best method for inter process communications In-Reply-To: <1184606522.541918.18870@22g2000hsm.googlegroups.com> References: <1184606522.541918.18870@22g2000hsm.googlegroups.com> Message-ID: <1184608650.15828.15.camel@blackwidow.nbk> On Mon, 2007-07-16 at 17:22 +0000, JamesHoward wrote: > I am looking for a way of performing inter process communication over > XML between a python program and something else creating XML data. > > What is the best way of performing this communication? I could bind a > socket to localhost and perform the data transfer that way, but that > seems inefficient due to the addition of TCP/IP or UDP/IP overhead. > Is there a way to stream data via a custom datastream (I.E. not STDIO, > STDERR, etc)? In *nix, you could also use a named pipe for cheap RPC (os.mkfifo()). -a From jjl at pobox.com Sat Jul 28 07:22:56 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 28 Jul 2007 11:22:56 GMT Subject: Pythonic way for missing dict keys References: <1185041243.323915.161230@x40g2000prg.googlegroups.com> Message-ID: <87lkd0eprj.fsf@pobox.com> Alex Popescu writes: > Zentrader wrote in news:1185041243.323915.161230 > @x40g2000prg.googlegroups.com: > >> On Jul 21, 7:48 am, Duncan Booth wrote: >> >> [snip...] >> >> >>>From the 2.6 PEP #361 (looks like dict.has_key is deprecated) >> Python 3.0 compatability: ['compatibility'-->someone should use a >> spell-checker for 'official' releases] >> - warnings were added for the following builtins which no >> longer exist in 3.0: >> apply, callable, coerce, dict.has_key, execfile, reduce, >> reload >> > > I see... what that document doesn't describe is the alternatives to be > used. And I see in that list a couple of functions that are probably used a > lot nowadays (callable, reduce, etc.). callable and reduce are rarely used, at least in code I've seen. I would agree there will be a large number of programs that contain one or two calls to these functions, though. Certainly has_key will be the most common of those listed above (but trivial to fix). apply will be common in old code from the time of Python 1.5.2. execfile is perhaps more common that callable (?) but again is really a "maybe 1 call in a big program" sort of thing. Anybody using coerce or reload deserves to lose ;-) John From greg at cosc.canterbury.ac.nz Wed Jul 11 04:09:31 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 11 Jul 2007 20:09:31 +1200 Subject: os.wait() losing child? In-Reply-To: References: Message-ID: <4694903B.8000105@cosc.canterbury.ac.nz> Jason Zheng wrote: > Hate to reply to my own thread, but this is the working program that can > demonstrate what I posted earlier: I've figured out what's going on. The Popen class has a __del__ method which does a non-blocking wait of its own. So you need to keep the Popen instance for each subprocess alive until your wait call has cleaned it up. The following version seems to work okay. import os from subprocess import Popen pids = {} counts = [0,0,0] p = [None, None, None] for i in xrange(3): p[i] = Popen('sleep 1', shell=True) pids[p[i].pid] = i print "Starting child process %d (%d)" % (i,p[i].pid) while (True): (pid,exitstat) = os.wait() i = pids[pid] del pids[pid] counts[i]=counts[i]+1 #terminate if count>10 if (counts[i]==10): print "Child Process %d terminated." % i if reduce(lambda x,y: x and (y>=10), counts): break continue print "Child Process %d (%d) terminated, restarting" % (i, pid), p[i] = Popen('sleep 1', shell=True) pids[p[i].pid] = i print "(%d)" % p[i].pid -- Greg From bdesth.quelquechose at free.quelquepart.fr Fri Jul 13 17:06:41 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 13 Jul 2007 23:06:41 +0200 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: <4697d9f0$0$7614$426a74cc@news.free.fr> Message-ID: <4697e976$0$26827$426a34cc@news.free.fr> Chris Carlen a ?crit : > Bruno Desthuilliers wrote: > >> Chris Carlen a ?crit : > > >[edit] > >>> Must possibly learn a completely new way of thinking (OOP) >> >> >> Not necessarly. While Python is OO all the way down - meaning that >> everything you'll work with will be an object (functions included) -, >> it doesn't *force* you into OO (IOW : you don't have to define classes >> to write a Python program). You can as well use a procedural - or even >> somewhat functional - approach, and most Python programs I've seen so >> far are usually a mix of the three. >> >>> not just a new language syntax. >> >> >> You forgot one of the most important part of a language : idioms. And >> it's definitively *not* idiomatic in Python to use classes when a >> simpler solution (using plain functions and modules) is enough. > > > I see. That's very promising. I guess some articles I read painted a > picture of religiousity among OOP programmers. That's alas a common disease - I'd say the best way to be definitively disgusted from OO is to read comp.lang.object :( > But that is not the > impression I am getting at all on the street. Heck. As you said, the important is to get things done. And I guess that's why we all (here) love Python. Last time I had to work on a Pascal program (actually Delphi's ObjectPascal, but the whole thing was almost caricaturally procedural), I found myself having to write tens of lines of code for thing that would have been no-brainer one-liners in Python, and define new types (records - Pascal's structs) where Python's builtin dict type would have do the trick. It's not a matter of procedural vs OO vs functional, it's a matter of using the appropriate tool for the job. From mail at microcorp.co.za Thu Jul 26 03:14:37 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 26 Jul 2007 09:14:37 +0200 Subject: I am giving up perl because of assholes on clpm -- switching toPython References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> <8a6b8e350707251620l6defd838gd26d003560e02f1f@mail.gmail.com> Message-ID: <01b801c7cf56$9ab2e1a0$03000080@hendrik> James Matthews wrote: >Wow! They might leave this newsgroup now also! Would be a pity, somehow - there seems to be a dearth of female posters here ;-) - Hendrik From steve at REMOVE.THIS.cybersource.com.au Sun Jul 8 18:17:04 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 09 Jul 2007 08:17:04 +1000 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <46824d8d$0$2324$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 08 Jul 2007 08:49:26 -0400, Steve Holden wrote: > Paul Rubin wrote: >> Steve Holden writes: >>>> Python even leaks the index variable of list comprehensions (I've >>>> mostly stopped using them because of this), though that's a >>>> recognized wart and is due to be fixed. >>>> >>> Wow, you really take non-pollution of the namespace seriously. I agree >>> it's a wart, but it's one I have happily worked around since day one. >> >> Well, the obvious workaround is just say "list()" >> instead of [] so that's what I do. > > I think I'll start calling you Captain Sensible. But you are right, it > does avoid that extra little potential for errors. I'd be thinking it should be Captain Paranoid. Why is list comp leakage a worse problem than, well, having local variables in the first place? def foo(x): y = something_or_other(x+1) z = do_something_else(y) + another_thing(y) # Oh noes!!! y still exists!!1!11!! What to do???? return ("foo", y) # OMG I meant to say z!!! If your function has got so many lines of code, and so many variables that this becomes a source of errors, your function should be refactored into smaller functions. As far as I can see, the only difference is that the list comp variable isn't explicitly created with a statement of the form "name = value". Why is that a problem? -- Steven. From westymatt at gmail.com Mon Jul 23 02:55:30 2007 From: westymatt at gmail.com (westymatt) Date: Mon, 23 Jul 2007 06:55:30 -0000 Subject: Catching a key press Message-ID: <1185173730.345615.284940@q75g2000hsh.googlegroups.com> How would I implement a trap for catching the "up arrow" from the keyboard? From cito at online.de Thu Jul 5 18:18:48 2007 From: cito at online.de (Christoph Zwerschke) Date: Fri, 06 Jul 2007 00:18:48 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: References: Message-ID: Sorry for the soliloquy, but what I am really using is the following so that the re-raised excpetion has the same type: def PoliteException(e): class PoliteException(e.__class__): def __init__(self, e): self._e = e def __getattr__(self, name): return getattr(self._e, name) def __str__(self): if isinstance(self._e, PoliteException): return str(self._e) else: return '\n%s: %s, I am sorry!' % ( self._e.__class__.__name__, str(self._e)) return PoliteException(e) try: unicode('\xe4') except Exception, e: raise PoliteException(e) From mensanator at aol.com Fri Jul 20 00:45:02 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Thu, 19 Jul 2007 21:45:02 -0700 Subject: really small values In-Reply-To: <1184882848.709077.168490@m37g2000prh.googlegroups.com> References: <1184882848.709077.168490@m37g2000prh.googlegroups.com> Message-ID: <1184906702.346437.148600@n60g2000hse.googlegroups.com> On Jul 19, 5:11?pm, Zentrader wrote: > On Jul 17, 2:13 pm, "Dee Asbury" wrote: > > > In multiplying a value of xe^-325 with ye^-4, Python is returning zero. How > > do I get it to give me back my tiny value? > > > Thanks! > > Dee > > Also, Python's decimal class allows theoretically unlimited > precision. I have extremely limited knowledge here. It gives the > following for 2**-325. I have no idea if the answer is correct. Looks ok, you should get about 0.3 as many decimal digits as bits. > You'll have to see if gmpy or decimal works better for this. One > piece of advice is to use whichever exclusively. If you use a float > and then covert to either one, the result will be corrupted. > import decimal > decimal.getcontext().prec = 375 ## set precision at 375 > print "2**-325 =", decimal.Decimal(str(2**-325)) > > 2**-325 = 1.46302386084E-98 Interestingly, using str() causes you to lose precision. >>> a = 2**-325 >>> a 1.463023860841312e-098 >>> b = str(a) >>> b '1.46302386084e-098' Setting the precision to 375 didn't help because you corrupted the value before you converted it to decimal. Although the 375 will allow you to do this: >>> a = decimal.Decimal('1e-325') >>> b = decimal.Decimal('1e-4') >>> a Decimal("1E-325") >>> b Decimal("0.0001") >>> a+b Decimal("0.0001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001") You can also do this in gmpy, although you set precision in bits, not decimal digits. From mattheww at chiark.greenend.org.uk Tue Jul 17 18:36:57 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 17 Jul 2007 23:36:57 +0100 (BST) Subject: Semantics of file.close() References: <1184628945.314844.53300@k79g2000hse.googlegroups.com> Message-ID: Donn Cave wrote: > I don't think there's any remedy for it, other than the obvious - > either always flush, or wrap an explicit close in its own exception > handler. Even if you have flushed, close() can give an error with some filesystems. -M- From simon at brunningonline.net Fri Jul 27 07:08:04 2007 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 27 Jul 2007 12:08:04 +0100 Subject: <> vs != In-Reply-To: <8a6b8e350707261228x234b7da0g17d43736e45e67ca@mail.gmail.com> References: <8a6b8e350707261228x234b7da0g17d43736e45e67ca@mail.gmail.com> Message-ID: <8c7f10c60707270408sdb320acua927ce016a90b20b@mail.gmail.com> On 7/26/07, James Matthews wrote: > What is the difference between <> and != <> is deprecated, != isn't. Other than that, nothing AFAIK. -- Cheers, Simon B. simon at brunningonline.net http://www.brunningonline.net/simon/blog/ GTalk: simon.brunning | MSN: small_values | Yahoo: smallvalues From horpner at yahoo.com Tue Jul 24 20:31:06 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 25 Jul 2007 00:31:06 GMT Subject: classmethod & staticmethod References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> <46a5b2ad$0$18903$426a74cc@news.free.fr> Message-ID: On 2007-07-25, Alex Popescu wrote: > As a matter of style, how do you figure out that class_list is > a class attribute and not an instance attribute? (I don't > remember seeing anything in the PEP describing the coding > style). Check out dir(MyClass) and dir(MyClass()) for some insight, if it turns out that it matters. Preferably, the user of a class doesn't have to really think about it much. -- Neil Cerutti From steve at REMOVE.THIS.cybersource.com.au Wed Jul 4 20:14:46 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 05 Jul 2007 10:14:46 +1000 Subject: Proposal: s1.intersects(s2) References: <5f1pldF3a62csU5@mid.uni-berlin.de> Message-ID: On Wed, 04 Jul 2007 14:37:34 +0000, Marc 'BlackJack' Rintsch wrote: > On Wed, 04 Jul 2007 09:59:24 -0400, David Abrahams wrote: > >> Here's an implementation of the functionality I propose, as a >> free-standing function: >> >> def intersects(s1,s2): >> if len(s1) < len(s2): >> for x in s1: >> if x in s2: return True >> else: >> for x in s2: >> if x in s1 return True >> return False > > In Python 2.5 this can be written a bit more concise: > > def intersects(set_a, set_b): > if len(set_a) < len(set_b): > set_a, set_b = set_b, set_a > return any(item in set_a for item in set_b) I'd rather see sets gain an method "isintersect()" with the functionality than the language to gain a built-in function. However, there's a very subtle flaw in the idea. While "the intersection" of two sets is well-defined, "these two sets intersect" is (surprisingly!) _not_ well-defined. If you only consider non-empty sets, you won't have a problem: two non-empty sets intersect if their intersection is not empty, and both implementations of intersects() given will do the right thing. The problem comes if we (perhaps naively) try to say that if a set A is a subset of set B, set A must intersect with B. (Not all intersecting sets are subsets, but all subsets are intersecting sets.) Unfortunately that is not the same as asking if the intersection between two sets is not empty: >>> A = set() >>> B = set([12, 21]) >>> A.issubset(B) True >>> B.issuperset(A) True >>> intersects(A, B) # both implementations do the same False >>> intersects(A, A) # does A intersect with itself? False PLEASE don't anybody try to argue that Python's behaviour here is "a bug" -- the meaning of subset and superset with the empty set is well-established and completely uncontroversial amongst mathematicians. (It is what they call a vacuous truth.) Rather than discuss the issues in detail, I'll just point those who care to Wikipedia: http://en.wikipedia.org/wiki/Empty_set#Common_problems and point out that the behaviour of any() and all() can sometimes be unintuitive or contradictory for the same reason. As a result, any proposed function or method that returns a True/False value for whether set A intersects with set B needs to define (and justify) what it means to say that two sets intersect when one or both are the empty set. -- Steven. From jarausch at igpm.rwth-aachen.de Tue Jul 3 06:12:04 2007 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 03 Jul 2007 12:12:04 +0200 Subject: restructuredtext latin1 encoding (FAQ?) Message-ID: <5eulnmF3ates7U1@mid.dfncis.de> Hi, I did try to find something on the net but I couldn't find anything useful. Is there a way to write documents with the reST tools using the Latin1 encoding? Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From Eric_Dexter at msn.com Mon Jul 16 19:45:33 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 16 Jul 2007 16:45:33 -0700 Subject: trouble controlling vim with subprocess on windows machine In-Reply-To: References: <1183970186.663847.4380@o61g2000hsh.googlegroups.com> Message-ID: <1184629533.518875.25410@r34g2000hsd.googlegroups.com> On Jul 16, 7:45 am, Yves Pouplard wrote: > On Mon, 09 Jul 2007 05:30:04 -0500, Nick Craig-Wood > > wrote: > >Eric_Dex... at msn.com wrote: > >> I am having trouble contolling vim with subprocess on a windows > >> machine. It appears that vim comes up on the machine all right and it > >> sometimes looks like it is doing the searchs what I am asking it to do > >> but when I am asking it to load a file it doesn't do anything. Is > >> there something I need to do to push the data through the pipe?? Here > >> is a couple different ways I am trying to do it. > > >For controlling an interactive program subprocess isn't the right > >tool. Subprocess only really does one way communication - it isn't > >good at conversations. I'd suggest pexpect but it doesn't work on > >windows. > > pexpect works with Cygwin's python :) > > > > >You appear to be doing stuff withcsound. There are several python > >modules out there which interface withcsound- did you investigate > >those?- Hide quoted text - > > - Show quoted text - I managed to get it as a com object (they have an example that isn't very good on the gvim site) and it is in csound routines as of 2pm today... Looks like it should be easy to do with sed also but I don't know that much about it. From wildemar at freakmail.de Mon Jul 16 08:16:06 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 16 Jul 2007 14:16:06 +0200 Subject: questions about functions inside a function In-Reply-To: <469B5B3B.8040901@gmail.com> References: <469B5B3B.8040901@gmail.com> Message-ID: <469B6186.3060709@freakmail.de> fdu.xiaojf at gmail.com wrote: > I want to create a list of function. > > Here is my code: > In [9]: a = [] > > In [10]: for i in range(4): > ....: b = lambda : i**2 > ....: a.append(b) > ....: > ....: > > In [11]: for f in a: > ....: f() > ....: > ....: > 9 > 9 > 9 > 9 > > What I want is, the value of i should be bounded to the anonymous function. > And the output should like this: > > for f in a: > print f() > 0 > 1 > 4 > 9 > > How to achieve this? > > Thanks a lot! > > I fail to see the point, sorry. Why would you want that? If you simply want a list of values you do: >>> a = [i**2 for i in range(4)] Can you elaborarate on what it is you really want. /W From steve at holdenweb.com Mon Jul 30 20:47:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Jul 2007 20:47:57 -0400 Subject: yield keyword usage In-Reply-To: <1185830034.713489.174640@r34g2000hsd.googlegroups.com> References: <1185830034.713489.174640@r34g2000hsd.googlegroups.com> Message-ID: Ehsan wrote: > hi > coulde any one show me the usage of "yield" keyword specially in this > example: > > > """Fibonacci sequences using generators > > This program is part of "Dive Into Python", a free Python book for > experienced programmers. Visit http://diveintopython.org/ for the > latest version. > """ > > __author__ = "Mark Pilgrim (mark at diveintopython.org)" > __version__ = "$Revision: 1.2 $" > __date__ = "$Date: 2004/05/05 21:57:19 $" > __copyright__ = "Copyright (c) 2004 Mark Pilgrim" > __license__ = "Python" > > def fibonacci(max): > a, b = 0, 1 > while a < max: > yield a > a, b = b, a+b > > for n in fibonacci(1000): > print n, > A function body with at least one yield expression (formerly a yield statement) in its body returns a generator when called: >>> def gen(i): ... for k in range(i): ... yield k*k ... >>> g = gen(3) >>> g >>> The same function can be called multiple times to create independent generators - the particular example I have given created a generator for a given number of squares. The generator can be used in an iterative context (such as a for loop), but in actual fact it observes the Python iterator protocol, so the generator has a .next() method, which can be used to extract the next value from it. Calling the .next() method runs the generator until a yield expression is encountered, and the value of the yield expression is the return value of the next method: >>> g.next() 0 >>> g.next() 1 >>> g.next() 4 When the generator function terminates (either with a return statement or by dropping off the end) it raises a StopIteration exception. This will terminate an iteration, but in other contexts it can be handled just like any other exception: >>> g.next() Traceback (most recent call last): File "", line 1, in StopIteration >>> So the fibonacci example you quote is a generator function that will yield a sequence of Fibonacci numbers up to but not including the value of its argument. 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 martin at v.loewis.de Sun Jul 29 00:46:09 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 29 Jul 2007 06:46:09 +0200 Subject: Compiling 2.5.1 on OpenBSD 4.1 In-Reply-To: References: Message-ID: <46AC1B91.3070706@v.loewis.de> > I'm stumped. Any suggestions? You will have to find the true declaration of lstat - reading man pages or checking that everything "looks right" won't help. So where is lstat declared? Is it declared at all, and if so, is that declaration conditional perhaps? Produce a preprocessor output (posixmodule.i), by adding -fsave-temps to the compiler line compiling posixmodule.c (copy the line from the make output into a shell, and add this command line); then inspect that output to see whether lstat has been declared. Regards, Martin From steve at holdenweb.com Thu Jul 26 00:35:23 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Jul 2007 00:35:23 -0400 Subject: Singleton in Python Cookbook In-Reply-To: References: <5gq00tF3fm71gU1@mid.uni-berlin.de> Message-ID: Alex Popescu wrote: > Alex Popescu wrote in > news:Xns9979172DC38F1themindstorm at 80.91.229.5: > >> "Diez B. Roggisch" wrote in >> news:5gq00tF3fm71gU1 at mid.uni-berlin.de: >> >>> Alex Popescu schrieb: >>>> Hi all! >>>> >>>> I was reading through Python Cookbook the Singleton recipe. At this >>>> moment I am a bit puzzled as the example in the book is not working >>>> resulting in: >>>> >>>> TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of >>>> type >>>> >>>> (I haven't presented the original code as I am not sure about >>>> copyrights). >>> AFAIK the cookbook is completely found online at ASPN. So no sweat >>> publishing it here. >>> >>> >>> And regarding the problem: is it possible that you forgot to subclass >>> SingleSpam from object? >>> >>> Diez >> The exact code: >> class Singleton(object): >> """ A Pythonic Singleton """ >> def _ _new_ _(cls, *args, **kwargs): >> if '_inst' not in vars(cls): >> cls._inst = type._ _new_ _(cls, *args, **kwargs) >> return cls._inst >> >> if _ _name_ _ == '_ _main_ _': >> class SingleSpam(Singleton): >> def _ _init_ _(self, s): self.s = s >> def _ _str_ _(self): return self.s >> s1 = SingleSpam('spam') >> print id(s1), s1.spam( ) >> s2 = SingleSpam('eggs') >> print id(s2), s2.spam( ) >> >> ./alex >> -- >> .w( the_mindstorm )p. >> > I got it working in 2 ways: > > class Singleton(object): > """ A Pythonic Singleton """ > def __new__(cls, *args, **kwargs): > if '_singletoninstance' not in vars(cls): > #variant 1: cls._singletoninstance = object.__new__(cls, *args, > **kwargs) > #variant 2: cls._singletoninstance = super(type, cls).__new__(cls, > *args, **kwargs) > return cls._singletoninstance > > Both of these seem to work. > If, that is, "work" means "Raise an AttributeError due to the missing spam() method". This appears to fix that problem: class Singleton(object): """ A Pythonic Singleton """ def __new__(cls, *args, **kwargs): if '_inst' not in vars(cls): cls._inst = object.__new__(cls, *args, **kwargs) return cls._inst if __name__ == '__main__': class SingleSpam(Singleton): def __init__(self, s): self.s = s def __str__(self): return self.s s1 = SingleSpam('spam') print id(s1), s1 s2 = SingleSpam('eggs') print id(s2), s2 print str(s1) 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 bronger at physik.rwth-aachen.de Mon Jul 16 09:53:02 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Mon, 16 Jul 2007 15:53:02 +0200 Subject: Trouble with email package References: <87r6n8foqd.fsf@wilson.homeunix.com> Message-ID: <87myxwfoap.fsf@wilson.homeunix.com> Hall?chen! Ingrid Bronger writes: > [...] > > The Content-Transfer-Encoding is wrong. Okay (well, not okay but) > then I added message["Content-Transfer-Encoding"] = "8bit" to my > code and got > > Content-Type: text/plain; charset="utf-8" > MIME-Version: 1.0 > Content-Transfer-Encoding: base64 > Content-Transfer-Encoding: 8bit > > Hall?chen! I found the cause of this part of my trouble. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From mcbooczech at gmail.com Tue Jul 24 17:24:22 2007 From: mcbooczech at gmail.com (Petr Jakes) Date: Tue, 24 Jul 2007 21:24:22 -0000 Subject: how to analyse music stream Message-ID: <1185312262.654685.270250@o61g2000hsh.googlegroups.com> On the local radio station here in the Czech they announced simple contest: If listeners will hear Elton John's Sacrifice followed immediately by Madonna's Frozen they have to call to the broadcasting. First caller will get some price. I am just thinking about the concept how to analyse music stream form the PC radio card to get the signal: "first tones of Frozen were played after Sacrifice, call to the studio" :-) Of course, the calling can be made by PC as well, but this is the easiest part of the task :) Thanks for your tips and comments Petr Jakes PS: both, Linux or Windows tips are welcome :-)) From no at no.no Tue Jul 17 08:17:38 2007 From: no at no.no (Daniel) Date: Tue, 17 Jul 2007 15:17:38 +0300 Subject: a=0100; print a ; 64 how to reverse this? References: <1184670575.205759.115360@i13g2000prf.googlegroups.com> Message-ID: On Tue, 17 Jul 2007 14:09:35 +0300, mosi wrote: > > Problem: > how to get binary from integer and vice versa? > The simplest way I know is: > a = 0100 > a > 64 > > but: > a = 100 (I want binary number) > does not work that way. > > a.__hex__ exists > a.__oct__ exists > > but where is a.__bin__ ??? > > > What`s the simplest way to do this? > Thank you very much. > Write your own? something like: def bin(x): from math import log bits = (8 if x == 0 else 8*(int(log(x)/log(2))/8+1)) return ''.join([str((x >> i) & 1) for i in range(bits)[::-1]]) though that's probably slow :/ -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From ahlongxp at gmail.com Sat Jul 7 12:58:34 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Sat, 07 Jul 2007 16:58:34 -0000 Subject: socket: connection reset by server before client gets response In-Reply-To: <1183819907.249945.239700@o11g2000prd.googlegroups.com> References: <1183819907.249945.239700@o11g2000prd.googlegroups.com> Message-ID: <1183827514.109496.252870@d30g2000prg.googlegroups.com> me again. "Connection reset by peer" happens about one in fifth. I'm using python 2.5.1 and ubuntu 7.04. -- ahlongxp Software College,Northeastern University,China ahlon... at gmail.comhttp://www.herofit.cn From martin at v.loewis.de Sat Jul 28 12:05:34 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 28 Jul 2007 18:05:34 +0200 Subject: Why no maintained wrapper to Win32? In-Reply-To: References: Message-ID: <46ab694e$0$17577$9b622d9e@news.freenet.de> > It looks like the development of the PyWin32 wrapper to the > Win32 API stopped years ago, which is too bad because it means that > writing GUI apps in Python even just for Windows means adding > megabytes when using eg. wxWidgets. Why does it mean that? The Win32 APIs for GUI are up-to-date; they don't need further development. Win32 itself stopped years ago. You can write GUI applications with PyWin32 just fine. Regards, Martin From nagle at animats.com Wed Jul 4 15:04:26 2007 From: nagle at animats.com (John Nagle) Date: Wed, 04 Jul 2007 12:04:26 -0700 Subject: object references/memory access In-Reply-To: <1183488824.131448.62720@x35g2000prf.googlegroups.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1183407411.397142.304790@e16g2000pri.googlegroups.com> <1183417108.245203.158830@x35g2000prf.googlegroups.com> <4689e535$0$23896$9b622d9e@news.freenet.de> <1183488824.131448.62720@x35g2000prf.googlegroups.com> Message-ID: Karthik Gurusamy wrote: > On Jul 2, 10:57 pm, "Martin v. L?wis" wrote: > >>>>>I have found the stop-and-go between two processes on the same machine >>>>>leads to very poor throughput. By stop-and-go, I mean the producer and >>>>>consumer are constantly getting on and off of the CPU since the pipe >>>>>gets full (or empty for consumer). Note that a producer can't run at >>>>>its top speed as the scheduler will pull it out since it's output pipe >>>>>got filled up. >>... > If the problem does not require two way communication, which is > typical of a producer-consumer, it is a lot faster to allow P to fully > run before C is started. > > If P and C are tied using a pipe, in most linux like OS (QNX may be > doing something really smart as noted by John Nagle), there is a big > cost of scheduler swapping P and C constantly to use the CPU. You may > ask why? because the data flowing between P and C, has a small finite > space (the buffer). Once P fills it; it will block -- the scheduler > sees C is runnable and puts C on the CPU. The killer case is where there's another thread or process other than C already ready to run when P blocks. The other thread, not C, usually gets control, because it was ready to run first, and not until the other thread runs out its time quantum does C get a turn. Then C gets to run briefly, drains out the pipe, and blocks. P gets to run, fills the pipe, and blocks. The compute-bound thread gets to run, runs for a full time quantum, and loses the CPU to C. Wash, rinse, repeat. The effect is that pipe-like producer-consumer systems may get only a small fraction of the available CPU time on a busy system. When testing a producer-consumer system, put a busy loop in the background and see if performance becomes terrible. It ought to drop by 50% against an equal-priority compute bound process; if it drops by far more than that, you have the problem described here. This problem is sometimes called "What you want is a subroutine call; what the OS gives you is an I/O operation." When you make a subroutine call on top of an I/O operation, you get these scheduling problems. John Nagle From ptmcg at austin.rr.com Mon Jul 9 09:54:45 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 09 Jul 2007 06:54:45 -0700 Subject: accessing an object instance by only having one of its attribute values In-Reply-To: <1183944576.702579.302150@g4g2000hsf.googlegroups.com> References: <1183918727.033724.213010@22g2000hsm.googlegroups.com> <1183921865.879071.172730@n2g2000hse.googlegroups.com> <1183940993.096789.148950@22g2000hsm.googlegroups.com> <1183944576.702579.302150@g4g2000hsf.googlegroups.com> Message-ID: <1183989285.084763.315940@r34g2000hsd.googlegroups.com> On Jul 8, 8:29 pm, mshiltonj wrote: > > Not sure why I slipped into the habit of testing for None, though. :-( > There is nothing wrong with testing for None. But the right ways to test for None are: if x is None: and if x is not None: Since None is a singleton, it is a waste to test using == or !=. The identity tests 'is' and 'is not' are sufficient. In fact, testing for None is a very common way to implement a default argument for an instance method (usually __init__ of a class) in which the default is a list (usually an empty list, but not always). The WRONG way: class BorkBorkBork(object): def __init__(self,words=[]): self.vocabulary = words Since the argument "words=[]" gets evaluated at class definition time, all instances of BorkBorkBork will end up using the same list, which is almost never the desired behavior, and a common surprise for new Pythoners. The ALMOST RIGHT way: class BorkBorkBork(object): def __init__(self,words=None): if words: self.vocabulary = words else: self.vocabulary = [] This is ALMOST RIGHT, now the default value of words is None, and the if test fails. Unfortunately, if this were called using: chef = BorkBorkBork([]) then the if test fails, not because the argument was omitted from the constructor, but BECAUSE THE PASSED VALUE EVALUATES TO FALSE! "So what?" you say, since in the else branch we just set the default value to an empty list anyway. But what about this? Why the ALMOST RIGHT way isn't ALWAYS RIGHT: class BorkBorkBork(object): def __init__(self,words=None): if words: self.vocabulary = words else: self.vocabulary = ['bork','hernie','fernie','bernie'] Our default starting vocabulary isn't empty now, but there is no way to initialize a BorkBorkBork'er to an empty list. The RIGHT way: class BorkBorkBork(object): def __init__(self,words=None): if words is not None: self.vocabulary = words else: self.vocabulary = ['bork','hernie','fernie','bernie'] Now the loophole is closed. If we want to initialize to an empty list, we can do so; or if we omit the argument, then the newly- constructed BorkBorkBork instance will have a minimally functional vocabulary. So testing for None is not inherently bad, and in many cases a healthy idiom. -- Paul From andre.roberge at gmail.com Tue Jul 31 10:33:35 2007 From: andre.roberge at gmail.com (Andr) Date: Tue, 31 Jul 2007 14:33:35 -0000 Subject: Plotting Images In-Reply-To: References: Message-ID: <1185892415.515577.211100@q75g2000hsh.googlegroups.com> On Jul 31, 8:41 am, Pei-Yu CHAO wrote: > Hi ALL: > > I have only been switched from matlab to python few > months ago. I having trouble of plotting images from a > matrix size of 8x10000 (unfortunately that is the size > of my data.....) > > for example, > x = rand(8,10000) > inshow(x) > > I have tried to use matplotlib function imshow(), but > all i get is a long thin line (unable to see the color > display and the my matrix information). > What is the screen size of your image? If it's scaled down so that the largest dimension is 1000px, then the smaller dimension will be reduced to 1px. Try breaking your image into various "strips". HTH, Andr > i think imshow() has the same problem in matlab, but i > think there is a alternative in matlab, imagesc(). > > I did search on web about plt.imagesc().....but when i > try to run the example code, python just tell me > cannot find module plt. > > >>>from scipy import plt > > ImportError: cannot import name plt > > I have installed scipy, wxpython2.6....and it still > seem not to work! > > is there some alternitive? or what have i done wrong? > Thank you > > Pei > > ____________________________________________________________________________________ > ?????????????????????? Yahoo!??????????http://tw.mobile.yahoo.com/texts/mail.php From gagsl-py2 at yahoo.com.ar Mon Jul 23 03:19:00 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Jul 2007 04:19:00 -0300 Subject: problem with exec References: <1185099810.772825.284620@m3g2000hsh.googlegroups.com> <1185111419.177524.131870@d55g2000hsg.googlegroups.com> Message-ID: En Sun, 22 Jul 2007 10:36:59 -0300, escribi?: >> Since the application is transforming >> its input, it could transform braces into indentation. Of course >> *Python* >> doesn't use braces, but the question was how to write "pseudo-Python" >> without using indentation to indicate grouping. >> > This previously is exactly what I need can you help me somehow about > this > code > indentation, on any way you know.Plese help I will really appreciate > this!!!!!!!!!!!!!! If you are using the tokenize module as suggested some time ago, try to analyze the token sequence you get using { } (or perhaps begin/end pairs in your own language, that are easier to distinguish from a dictionary display) and the sequence you get from the "real" python code. Then write a script to transform one into another: from tokenize import generate_tokens from token import tok_name from cStringIO import StringIO def analyze(source): g = generate_tokens(StringIO(source).readline) for toknum, tokval, _, _, _ in g: print tok_name[toknum], repr(tokval) I think you basically will have to ignore INDENT, DEDENT, and replace NAME+"begin" with INDENT, NAME+"end" with DEDENT. -- Gabriel Genellina From ptmcg at austin.rr.com Mon Jul 2 19:54:44 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 02 Jul 2007 16:54:44 -0700 Subject: Pretty Scheme, ??? Python In-Reply-To: <1183418938.911025.55340@w5g2000hsg.googlegroups.com> References: <46895e12$0$5078$ba4acef3@news.orange.fr> <_Ddii.36114$G23.10348@newsreading01.news.tds.net> <1183418938.911025.55340@w5g2000hsg.googlegroups.com> Message-ID: <1183420484.054730.139370@w5g2000hsg.googlegroups.com> On Jul 2, 6:28 pm, Paul McGuire wrote: > On Jul 2, 3:56 pm, Neil Cerutti wrote: > > > > > > > On 2007-07-02, Laurent Pointal wrote: > > > > Neil Cerutti wrote: > > >> How can I make the Python more idiomatic Python? > > > > Have you taken a look at pyparsing ? > > > Yes, I have it. PyParsing has, well, so many convenience features > > they seem to shout down whatever the core features are, and I > > don't know quite how to get started as a result. > > > Hardest of all was modifying a working PyParsing program. > > > As a result, I've found writing my own recursive descent parsers > > much easier. > > > I'm probably wrong, though. ;) > > > -- > > Neil Cerutti > > from pyparsing import * > > """ > Neil - > > Ok, here is the step-by-step, beginning with your posted BNF. (Based > on your test cases, I think the '{}'s are really supposed to be > '()'s.) > > ; ::= > ; > ; | { + } > ; | { - } > ; | {with { } } > ; | > > The most basic building blocks in pyparsing are Literal and Word. > With these, you compose "compound" elements using And and MatchFirst, > which are bound to the operators '+' and '|' (on occasion, Or is > required, bound to operator '^', but not for this simple parser). > Since you have a recursive grammar, you will also need Forward. > Whitespace is skipped implicitly. > > Only slightly more advanced is the Group class, which will impart > hierarchy and structure to the results - otherwise, everything just > comes out as one flat list of tokens. You may be able to remove these > in the final parser, depending on your results after steps 1 and 2 in > the "left for the student" part below, but they are here to help show > structure of the parsed tokens. > > As convenience functions go, I think the most common are oneOf and > delimitedList. oneOf might be useful here if you want to express id > as a single-char variable; otherwise, just use Word(alphas). > > At this point you should be able to write a parser for this WAE > grammar. Like the following 9-liner: > """ > > LPAR = Literal("(").suppress() > RPAR = Literal(")").suppress() > > wae = Forward() > num = Word(nums) > id = oneOf( list(alphas) ) > addwae = Group( LPAR + "+" + wae + wae + RPAR ) > subwae = Group( LPAR + "-" + wae + wae + RPAR ) > withwae = Group( LPAR + "with" + LPAR + id + wae + RPAR + wae + RPAR ) > > wae << (addwae | subwae | withwae | num | id) > > tests = """\ > 3 > (+ 3 4) > (with (x (+ 5 5)) (+ x x))""".splitlines() > > for t in tests: > print t > waeTree = wae.parseString(t) > print waeTree.asList() > print > > """ > If you extract and run this script, here are the results: > 3 > ['3'] > > (+ 3 4) > [['+', '3', '4']] > > (with (x (+ 5 5)) (+ x x)) > [['with', 'x', ['+', '5', '5'], ['+', 'x', 'x']]] > > Left as an exercise for the student: > 1. Define classes NumWAE, IdWAE, AddWAE, SubWAE, and WithWAE whose > __init__ methods take a ParseResults object named tokens (which you > can treat as a list of tokens), and each with a calc() method to > evaluate them accordingly. > 2. Hook each class to the appropriate WAE class using setParseAction. > Hint: here is one done for you: num.setParseAction(NumWAE) > 3. Modify the test loop to insert an evaluation of the parsed tree. > > Extra credit: why is id last in the set of alternatives defined for > the wae expression? > > -- Paul > """- Hide quoted text - > > - Show quoted text - Oops, that should be a 10-liner - I forgot the "from pyparsing import *" line. -- Paul From deets at nospam.web.de Mon Jul 23 18:09:46 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 24 Jul 2007 00:09:46 +0200 Subject: Reading data from an ISA port In-Reply-To: References: Message-ID: <5gkn9lF3g5b6vU1@mid.uni-berlin.de> Gabriel Dragffy schrieb: > Dear list members > > I must admit I am a new user of Python, but it is a language that I > enjoy using. > > For one of my university projects I need to write a program that can > read several bytes from an ISA port. It has been suggested to me that I > look at using C or Pyinline. If I can I would prefer to continue to use > Python, and Pyinline won't play ball. > > I am sure Python can do this for me, but the question is how? What > modules and code do I need to look? I'd be very grateful for any > suggestions and advice. Python as-is won't help. It has no concept of memory addresses and direct access to them. However, a trivial C-extension together with the struct and/or ctypes module will help. What you essentially need to code is a C-extension that will allow you to directly access memory. Wrap that either in an extension or using ctypes. Diez From steve at holdenweb.com Fri Jul 13 14:44:09 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Jul 2007 14:44:09 -0400 Subject: renaming an open file in nt like unix? In-Reply-To: References: <1184346880.093826.176350@n2g2000hse.googlegroups.com> Message-ID: Thomas Heller wrote: > aaron.watters at gmail.com schrieb: >> Hi. I'm writing an archival system which I'd like to be portable >> to Windows. >> >> The system relies on the property of Unix which allows a >> process to keep a file open even if another process renames >> it while it is open. Neither process sees any anomaly or >> error. >> >> Do the NT file systems support this feature (which I think is >> standard for POSIX systems)? > > Yes, you can do that. We implemented something like this to replace > dlls there are currently in use - rename the currently open file, create a new one > with the old name (newly started processes will use the new one then), > and delete the renamed one at the next possible occasion (usually at > the next reboot). I'm not so sure on which NT versions it works this > way, at least in w2000 and newer. > > Thomas > You do have to be careful though, because sometimes Windows refuses to let you rename a file because it's in use. 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 jan.m.danielsson at gmail.com Tue Jul 10 07:30:36 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Tue, 10 Jul 2007 13:30:36 +0200 Subject: "Empty" text In-Reply-To: <1184061101.493471.151310@22g2000hsm.googlegroups.com> References: <469147b8$1@griseus.its.uu.se> <1184061101.493471.151310@22g2000hsm.googlegroups.com> Message-ID: <46936ddc$1@griseus.its.uu.se> Andr? wrote: [---] >> I understand the opitmization ElementTree is performing; but it seems >> there are cases when it is not the proper thing to do. Is it possible to >> force ElementTree to output the XHTML code I need it to? > > I ran into the same problem and a workaround I found was to use either > ta.text = " " or ta.text = "\n" instead of ta.text = ''. > For my application, it did the right thing; your mileage may vary. The problem was actually as indicated by others, that the document was not being served as application/xml+xhtml. The _real_ problem was the fact that I know too little about http/html. I put a meta tag in the head, indicating that it had the content type "application/xml+xhtml", and thought that would do it. Which is obviously didn't. Once I added req.content_type = "application/xml+xhtml" to my mod_python application, it worked properly. In the future, I'll be sure to use the "View Page Info" feature in Firefox to actually check what type my documents are being served as. I was surprised to find that some pages render quite differently, just by changing content type from text/html to application/xml+xhtml. (Quite a positive surprise, to me) A big "Thank you!" goes to those who helped me find the source of the problem. -- Kind regards, Jan Danielsson From anessaclark at gmail.com Sat Jul 21 14:06:44 2007 From: anessaclark at gmail.com (Ana Clark) Date: Sat, 21 Jul 2007 11:06:44 -0700 Subject: =?utf-8?B?4pa64pa6WU9VUiBWQUxVQUJMRSBPUElOSU9OIENPVUxEIEVBUk4gWU9VICQzMDAwIOKXhOKXhA==?= Message-ID: <1185041204.857699.249490@d30g2000prg.googlegroups.com> Do You Know Your VALUABLE OPINION Can Earn You Upto $3000 Per Month >> Get Paid to Try New Products, Drive Car, Travel etc... Know more about these Opportunities, Just follow the link: http://shortlinks.co.uk/35x From http Thu Jul 26 17:13:18 2007 From: http (Paul Rubin) Date: 26 Jul 2007 14:13:18 -0700 Subject: I am giving up perl because of assholes on clpm -- switching to Python References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> Message-ID: <7x4pjqj2c1.fsf@ruckus.brouhaha.com> John K Masters writes: > As a complete amateur in the world of programming (barring 25 years > programming machine tools in the aerospace industry) I would like to > point out that the more arcane the ['language', 'operating system', > 'application'] the more unfriendly the community. I mentioned comp.lang.functional in another post but I'll add that except for a couple of semi-difficult personalities it's a very friendly place, and a lot of the subjects discussed are so arcane that even as a dedicated software geek I can barely comprehend what they're about. From ricaraoz at gmail.com Mon Jul 30 20:59:10 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Mon, 30 Jul 2007 21:59:10 -0300 Subject: What is the "functional" way of doing this? In-Reply-To: <1185839713.412656.242950@i13g2000prf.googlegroups.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> Message-ID: <46AE895E.2020405@bigfoot.com> > On Jul 30, 4:39 pm, Paul Rubin wrote: >> "attn.steven.... at gmail.com" writes: >>> Recursion is common in functional programming: >>> def f(n, l=None): >>> if l == None: >>> l = [] >>> if n > 0: >>> return f(n/26, l + [n%26]) >>> else: >>> return l >>> print f(1000) >> Right, this is functional style, but quite painful in Python (no tail >> recursion, and look at all that list copying). > It might actually be : def f(n): if n > 0: return ([n%26] + f(n/26)) else: return [] Wouldn't that be ok? From sajmikins at gmail.com Sun Jul 8 23:21:31 2007 From: sajmikins at gmail.com (Simon Forman) Date: Sun, 08 Jul 2007 20:21:31 -0700 Subject: What is the most efficient way to test for False in a list? In-Reply-To: <1183938194.761283.97950@57g2000hsv.googlegroups.com> References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> Message-ID: <1183951291.176559.12560@d55g2000hsg.googlegroups.com> On Jul 8, 7:43 pm, lex wrote: > Of course there is the always the iteration method: > > list = [1, True, True, False, False, True] > status = True > for each in list: > status = status and each > > but what is your best way to test for for False in a list? False in list i.e. for a list N if False in N: # do something with N.. From robert.rawlins at thinkbluemedia.co.uk Wed Jul 11 10:46:55 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 11 Jul 2007 15:46:55 +0100 Subject: Launch One Application From Another Message-ID: <005f01c7c3ca$562d7be0$028873a0$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm looking for the best method to launch one Python application from another? Is something like sub process going to be my best bet? Or is there something more specific for launching one python app from another? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten at uniqsys.com Fri Jul 20 16:41:46 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 20 Jul 2007 16:41:46 -0400 Subject: Pythonic way for missing dict keys In-Reply-To: References: Message-ID: <1184964106.3586.32.camel@dot.uniqsys.com> On Fri, 2007-07-20 at 19:39 +0000, Alex Popescu wrote: > Neil Cerutti wrote in > news:slrnfa2325.n4.horpner at FIAD06.norwich.edu: > > > On 2007-07-20, Alex Popescu wrote: > >> Hi all! > >> > >> I am pretty sure this has been asked a couple of times, but I > >> don't seem to find it on the archives (Google seems to have a > >> couple of problems lately). > >> > >> I am wondering what is the most pythonic way of dealing with missing > >> keys and default values. > >> > >> According to my readings one can take the following approaches: > > > > There's also the popular collections.defaultdict. > > > > Usually, the get method of normal dicts is what I want. I use a > > defaultdict only when the implicit addition to the dictionary of > > defaulted elements is what I really want. > > > > This looks like the closest to my needs, but in my case the default value > involves the creation of a custom object instance that is taking parameters > from the current execution context, so I am not very sure I can use it. If by "current execution context" you mean globally visible names, this should still be possible: >>> from collections import defaultdict >>> def make_default(): ... return x+y ... >>> dd = defaultdict(make_default) >>> x = 40 >>> y = 2 >>> print dd[0] 42 >>> x = "Dead" >>> y = " Parrot" >>> print dd[1] Dead Parrot >>> print dd defaultdict(, {0: 42, 1: 'Dead Parrot'}) HTH, -- Carsten Haese http://informixdb.sourceforge.net From James.w.Howard at gmail.com Mon Jul 16 15:46:07 2007 From: James.w.Howard at gmail.com (JamesHoward) Date: Mon, 16 Jul 2007 19:46:07 -0000 Subject: Best method for inter process communications In-Reply-To: References: <1184606522.541918.18870@22g2000hsm.googlegroups.com> Message-ID: <1184615167.403546.49380@q75g2000hsh.googlegroups.com> Thanks for the updates. I think I will try named processes first, but may just end up using local sockets in the end and not worry about the overhead. Jim Howard From bj_666 at gmx.net Tue Jul 24 04:10:36 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Jul 2007 08:10:36 GMT Subject: Parsing XML with ElementTree (unicode problem?) References: <1185200976.082516.105420@57g2000hsv.googlegroups.com> <1185256646.060652.199740@d55g2000hsg.googlegroups.com> Message-ID: <5glqfsF3gs3gfU2@mid.uni-berlin.de> On Tue, 24 Jul 2007 05:57:26 +0000, oren.tsur wrote: > but the thing is that the parser parses it all right from the web (the > amazon response) but fails to parse the locally saved file. I've just used wget to fetch that URL and `ElementTree` parses that local file without problems. Maybe you should stop searching the explanation within Python or `ElementTree` and accept having a broken XML file on your disk. :-) Have you checked the local XML file with something like `xmllint` or another XML parser already? Ciao, Marc 'BlackJack' Rintsch From news2 at mystrobl.de Sun Jul 22 10:20:09 2007 From: news2 at mystrobl.de (Wolfgang Strobl) Date: Sun, 22 Jul 2007 16:20:09 +0200 Subject: Can a low-level programmer learn OOP? References: <7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com> Message-ID: eddie at holyrood.ed.ac.uk (Eddie Corns): >I don't believe you can get the benefit of SNOBOL matching without direct >language support. That's my opinion, too. >There's only so much a library can do. However a valiant >and interesting effort: > >http://www.wilmott.ca/python/patternmatching.html This is newer than http://sourceforge.net/projects/snopy/ which adapts a ADA implemenation, which follows the SNOBOL model quite closely. Didn't knew that. Thanks for pointing it out! Well, unfortunately, it somehow demonstrates your point. This may be missing familiarity with the changed idiom, though. Perhaps rewriting a few of James Gimple's snippets from "Algorithms in SNOBOL4" (->http://www.snobol4.org/) as an exercise using that library might help to get a better appreciation. Perhaps I'll try, eventually ... -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From socialanxiety at gmail.com Sun Jul 8 20:19:17 2007 From: socialanxiety at gmail.com (socialanxiety at gmail.com) Date: Sun, 08 Jul 2007 17:19:17 -0700 Subject: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc) In-Reply-To: References: <1183939608.088756.178320@m37g2000prh.googlegroups.com> Message-ID: <1183940357.602565.192890@m37g2000prh.googlegroups.com> On Jul 8, 5:14 pm, John Nagle wrote: > socialanxi... at gmail.com wrote: > > i hope someone here can help me. > > > basically, me and my friend have a summer project. > > > in this project, we need something that would basically function as a > > blender. we know we'll need to buy a motor that spins, but what we're > > having trouble with is figuring out how to program it. we want to be > > able to control the speed of the motor. how would we accomplish this? > > > i'm new to all of this, so i'm having a hard time wrapping my mind > > around how it'd be possible to program one of those things :\ > > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then > > turn the other direction. > > > would you program it the same way you would on a personal computer > > (via c, python, etc)? > > Try "comp.robotics.misc" for the basics of robot motor control. > > John Nagle thank you. From ChrisEdgemon at gmail.com Wed Jul 11 19:21:22 2007 From: ChrisEdgemon at gmail.com (ChrisEdgemon at gmail.com) Date: Wed, 11 Jul 2007 23:21:22 -0000 Subject: Where does str class represent its data? Message-ID: <1184196082.903895.176020@n60g2000hse.googlegroups.com> I'd like to implement a subclass of string that works like this: >>>m = MyString('mail') >>>m == 'fail' True >>>m == 'mail' False >>>m in ['fail', hail'] True My best attempt for something like this is: class MyString(str): def __init__(self, seq): if self == self.clean(seq): pass else: self = MyString(self.clean(seq)) def clean(self, seq): seq = seq.replace("m", "f") but this doesn't work. Nothing gets changed. I understand that I could just remove the clean function from the class and call it every time, but I use this class in several locations, and I think it would be much safer to have it do the cleaning itself. From jakub.stolarski at gmail.com Fri Jul 20 15:57:28 2007 From: jakub.stolarski at gmail.com (Jakub Stolarski) Date: Fri, 20 Jul 2007 19:57:28 -0000 Subject: Pythonic way for missing dict keys In-Reply-To: References: Message-ID: <1184961448.456134.153020@k79g2000hse.googlegroups.com> Version 1 and 2 do different thing than version 3. The latter doesn't add value to dict. As it was mentioned before, use: 1 - if you expect that there's no key in dict 2 - if you expect that there is key in dict From raims at dot.com Mon Jul 16 17:33:40 2007 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 16 Jul 2007 23:33:40 +0200 Subject: Discover instance variables References: <1184606748.599294.293570@n60g2000hse.googlegroups.com> Message-ID: <1i1daq8.ahdqyat6mqy8N%raims@dot.com> Gabriel Genellina wrote: > The list keeps only the types explicitely enumerated. Other types are > excluded, as well as names starting with "_". Another criterion would be > `not attr.startswith('_') and not callable(getattr(obj,attr))` Why not: In [1]: class Foo(object): ...: a = 3 ...: ...: In [2]: import inspect In [4]: inspect.getmembers(Foo()) Out[4]: [('__class__', ), ('__delattr__', ), ('__dict__', {}), ('__doc__', None), ('__getattribute__', ), ('__hash__', ), ('__init__', ), ('__module__', '__main__'), ('__new__', ), ('__reduce__', ), ('__reduce_ex__', ), ('__repr__', ), ('__setattr__', ), ('__str__', ), ('__weakref__', None), ('a', 3)] and then filter out __xyz__ methods? -- 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 hexamorph at gmx.net Tue Jul 31 14:32:38 2007 From: hexamorph at gmx.net (Hexamorph) Date: Tue, 31 Jul 2007 20:32:38 +0200 Subject: Iteration over strings In-Reply-To: <46AF7A49.3040804@jayloden.com> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> <46AF7A49.3040804@jayloden.com> Message-ID: <46AF8046.7090702@gmx.net> Jay Loden schrieb: > Robert Dailey wrote: >> str = "C:/somepath/folder/file.txt" >> >> for char in str: >> if char == "\\": >> char = "/" > strings in Python are immutable - in other words, they cannot be updated in place as you're doing above. However, that doesn't mean you can't achieve what you're after. In Python, the way to approach this problem since you cannot modify the string in place, is to create a new string object with the desired content: Also note, that you are just extracting one char from the string into another variable (which you then change) and you are *not* getting any "reference" to the char in the string. As has been alreagy told, use the str.replace() function From timr at probo.com Tue Jul 24 02:47:23 2007 From: timr at probo.com (Tim Roberts) Date: Tue, 24 Jul 2007 06:47:23 GMT Subject: Need Help with base64 References: <1185193741.420611.302290@z28g2000prd.googlegroups.com> Message-ID: pycraze wrote: > >int base641_decodestring(char* pcstr,int size,char** ppcdest) >{ > unsigned char cin[4] = {""}; > unsigned char cout[3] = {""}; > unsigned char cv = 0; > int ni = 0; > int nlen = 0; > char* cptr = pcstr; > *ppcdest = malloc(sizeof(char)*160); > if (!*ppcdest) > { > return 1; > } > memset(*ppcdest,0,sizeof(char)*160); > > char* pcstring = malloc( sizeof(char) * SIZE); > if (!pcstring) > { > aps_log("APS_log.txt","\nbae64.c:base64encode:malloc failed >\n"); > return 1; > } > memset(pcstring,'\0',SIZE); Those last 7 lines must have been leftover; pcstring is not used in this routine. > for( nlen = 0, ni = 0; ni < 4; ni++ ) > { > cv = 0; > while( cv == 0 ) > { > cv = (unsigned char) *cptr; > cv = (unsigned char) ((cv < 43 || cv > 122) ? 0 : >cd64[ cv - 43 ]); > if( cv ) > { > cv = (unsigned char) ((cv == '$') ? 0 : cv - 61); > } > } > if( cptr++ ) > { > nlen++; > if( cv ) > { > cin[ ni ] = (unsigned char) (cv - 1); > } > } > else > { > cin[ni] = 0; > } > } > if( nlen ) > { > decodeblock( cin, cout ); > > } > memcpy(*ppcdest,cout,160); > return 0; "cout" is an array of 3 characters. Where do you think the memcpy is going to find 160 bytes? I suspect you intended to have this loop inside a SECOND loop, copying 3 characters at a time into *ppcdest. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From zellux at gmail.com Mon Jul 16 10:55:40 2007 From: zellux at gmail.com (ZelluX) Date: Mon, 16 Jul 2007 22:55:40 +0800 Subject: how to read python-doc in ubuntu? Message-ID: Hi all, I'm a new comer to Python. I've installed python-doc module, but just don't know how to open it. Could you help me? Many thanks ^_^ From bj_666 at gmx.net Wed Jul 4 10:37:34 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Jul 2007 14:37:34 GMT Subject: Proposal: s1.intersects(s2) References: Message-ID: <5f1pldF3a62csU5@mid.uni-berlin.de> On Wed, 04 Jul 2007 09:59:24 -0400, David Abrahams wrote: > Here's an implementation of the functionality I propose, as a > free-standing function: > > def intersects(s1,s2): > if len(s1) < len(s2): > for x in s1: > if x in s2: return True > else: > for x in s2: > if x in s1 return True > return False In Python 2.5 this can be written a bit more concise: def intersects(set_a, set_b): if len(set_a) < len(set_b): set_a, set_b = set_b, set_a return any(item in set_a for item in set_b) Ciao, Marc 'BlackJack' Rintsch From byte8bits at gmail.com Thu Jul 26 15:54:11 2007 From: byte8bits at gmail.com (brad) Date: Thu, 26 Jul 2007 15:54:11 -0400 Subject: question about math module notation Message-ID: How does one make the math module spit out actual values without using engineer or scientific notation? I get this from print math.pow(2,64): 1.84467440737e+19 I want this: 18,446,744,073,709,551,616 I'm lazy... I don't want to convert it manually :) From carsten at uniqsys.com Mon Jul 16 15:06:04 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 16 Jul 2007 15:06:04 -0400 Subject: Binary blobs to jpeg In-Reply-To: <1184612270.455699.254560@r34g2000hsd.googlegroups.com> References: <1184612270.455699.254560@r34g2000hsd.googlegroups.com> Message-ID: <1184612764.10154.11.camel@dot.uniqsys.com> On Mon, 2007-07-16 at 18:57 +0000, jayharvard1 at gmail.com wrote: > Hello All. > I'm trying to create jpegs out of data that is stored in a binary blob > format in an RDBMS (MS Access). I've tried writing the jpeg directly: > > while not rs.EOF: > op = file(imgdir + "\\" + pic,"w") > print >> op, rs.Fields[3].Value > ##where rs.Fields[3].Value is the data in the blob from Access. > > When I try to write out this file, the jpeg doesn't turn out. Have you tried to open the file in "wb" mode? HTH, -- Carsten Haese http://informixdb.sourceforge.net From tunuyan-house at hotmail.com Mon Jul 30 20:41:16 2007 From: tunuyan-house at hotmail.com (Natalia) Date: Mon, 30 Jul 2007 17:41:16 -0700 Subject: www.cerocom.com Message-ID: <1185842476.412684.188390@g4g2000hsf.googlegroups.com> ...................................... www.cerocom.com ...................................... You will be able to ask yourself: Is Internet a good investment for my company? So that an investment would have to do I of this type? Really is going to serve to me to have a Web site? So that to be in Internet? See some of the main advantages have a Web site: ? Increase the productivity and to generate more businesses with the implementation of collaboration rofe and integration maximizing the value of Internet and networks IP. ? Offer solutions of Internet, integration and collaboration in accordance with our clients, anyone is their size or trains, to rofesional r to integrate their applications, to fortify their present position in the market or to impel their growth, assuring trustworthiness, discharge rofesional qualification, and customized service. I invite it to cross the Web site and interiorice of the services available. www.cerocom.com Contact: Commercial direction: Viamonte 783 Piso 3? Capital Federal (C1053ABO) Bs. As. Argentina Tel/Fax: (54.11) 4322.1201 Celular: (54-9-11) (15) 5006.4384 Mail: cerocom at cerocom.com Web Site: www.cerocom.com From alia_khouri at yahoo.com Mon Jul 30 02:50:52 2007 From: alia_khouri at yahoo.com (Alia Khouri) Date: Sun, 29 Jul 2007 23:50:52 -0700 Subject: problems with logging module In-Reply-To: References: <1185744598.663382.126920@19g2000hsx.googlegroups.com> Message-ID: <1185778252.177411.286660@k79g2000hse.googlegroups.com> On Jul 30, 8:01 am, "Gabriel Genellina" wrote: > To see what's going on, try using this old-fashioned debug technique: a > few print statements. My bad, problem was solved, the shortcoming was one of my variables pointing to nothingness (-; But I'm not letting the logging module off, it's still not the easiest or most intuitive module to work with. For example: a basic Log class that can be programatically configured would be quicker to work with then messing around with three different classes types if you want to get beyond basicConfig functionality: (Logger, handlers, formatters) To be able to do this would be nice: from logging import Log class MyClass: def __init__(self, x): self.x = x self.log = Log( level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s", datefmt = '%H:%M:%S', filename='app.log', filemode='a' ) Thanks for your help and time. AK From bj_666 at gmx.net Tue Jul 24 06:10:24 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Jul 2007 10:10:24 GMT Subject: display image through cgi python html References: Message-ID: <5gm1ggF3gs3gfU3@mid.uni-berlin.de> On Tue, 24 Jul 2007 11:58:47 +0200, Ladislav Andel wrote: > Here is what I have in image.cgi but it is incorrect and i'm not able to > find it on the web. > > #!/usr/bin/python > print "Content-Type: image/png\n" > print 'image.png' You have to print the image, not the name. Read the binary file and print it. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Sat Jul 14 00:40:27 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 14 Jul 2007 01:40:27 -0300 Subject: Can I change one line in a file without rewriting the whole thing? References: <1184381184.772946.218220@w3g2000hsg.googlegroups.com> Message-ID: En Fri, 13 Jul 2007 23:46:24 -0300, J. J. Ramsey escribi?: > In Perl, there is a module called "Tie::File". What it does is tie a > list to each line of a file. Change the list, and the file is > automatically changed, and on top of this, only the bits of the file > that need to be changed are written to disk. At least, that's the > general idea. That usually means, rewriting from the first modified line to the end of the file. > I was wondering if something roughly similar could be done in Python, > or at the very least, if I can avoid doing what amounts to reading the > whole file into memory, changing the copy in memory, and writing it > all out again. Simplest aproach: lines = list(open("myfile.txt")) del lines[13] lines[42] = "Look ma! Replacing line 42!\n" open("myfile.txt","w").writelines(lines) This of course reads the whole file in memory, but it's a compact way if you require random line access. If you can serialize the file operations, try using the fileinput module with inplace=1. (Having a true Tie::File implementation for Python would be a nice addition to the available tools...) -- Gabriel Genellina From steve at holdenweb.com Sat Jul 28 08:23:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 28 Jul 2007 08:23:21 -0400 Subject: Pythonic way for missing dict keys In-Reply-To: References: <1185041243.323915.161230@x40g2000prg.googlegroups.com> <87lkd0eprj.fsf@pobox.com> Message-ID: Alex Popescu wrote: > jjl at pobox.com (John J. Lee) wrote in news:87lkd0eprj.fsf at pobox.com: > >> Alex Popescu writes: >> >>> Zentrader wrote in >>> news:1185041243.323915.161230 @x40g2000prg.googlegroups.com: >>> >>>> On Jul 21, 7:48 am, Duncan Booth >>>> wrote: >>>> >>>> [snip...] >>>> >>>> >>>> >From the 2.6 PEP #361 (looks like dict.has_key is deprecated) >>>> Python 3.0 compatability: ['compatibility'-->someone should use a >>>> spell-checker for 'official' releases] >>>> - warnings were added for the following builtins which no >>>> longer exist in 3.0: >>>> apply, callable, coerce, dict.has_key, execfile, >>>> reduce, >>>> reload >>>> >>> I see... what that document doesn't describe is the alternatives to >>> be used. And I see in that list a couple of functions that are >>> probably used a lot nowadays (callable, reduce, etc.). >> callable and reduce are rarely used, at least in code I've seen. > > I thought G would be using that function a lot. 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). > See his latest blog entry on artima.com, where he has started a Py3k FAQ. He suggests that uses if reduce are almost always more readable when written using a for loop and an accumulator variable. http://www.artima.com/weblogs/viewpost.jsp?thread=211200 >> Certainly has_key will be >> the most common of those listed above (but trivial to fix). > > dict.has_key(key) becomes key in dict (correct?) > >> apply >> will be common in old code from the time of Python 1.5.2. > > I think there were some advises to not use apply. > Yup. Anyway there's a trivial translation for uses of apply. apply(f, *args, **kw) => f(*args, **kw) The converter will almost certainly do this for you. >> execfile is >> perhaps more common that callable (?) but again is really a "maybe 1 >> call in a big program" sort of thing. > I don't ever remember using execfile. It has always been a blot on the landscape. > What is the replacement for this one? > I'd have to guess, and will refrain from doing so. 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 Tue Jul 24 14:25:13 2007 From: vasudevram at gmail.com (vasudevram) Date: Tue, 24 Jul 2007 18:25:13 -0000 Subject: Technology solutions for Ruby? In-Reply-To: <469be0e5$0$9556$426a74cc@news.free.fr> References: <469B059C.2050802@cesmail.net> <1184606739.054580.197740@g37g2000prf.googlegroups.com> <469be0e5$0$9556$426a74cc@news.free.fr> Message-ID: <1185301513.099804.202870@j4g2000prf.googlegroups.com> Bruno Desthuilliers wrote: >s/some/great/g >Both Ruby and Python are known for this. Thanks for the info. (I don't know much about metaprogramming etc. in either languages - just started exploring those topics recently.) >I'd say that - wrt/ "advanced" programming tricks - *most* of what you can do with one can be done with the other - but usually in a *very* different way. While Ruby and Python have similar features and may look very similar at first sight, their respective object models are totally different. Can you briefly explain what you mean by "their respective object models are totally different"? Do you refer to how the object- orientation (classes, objects, etc.) is implemented in the two languages? Thanks Vasudev From the.mindstorm.mailinglist at gmail.com Thu Jul 5 18:06:50 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Thu, 05 Jul 2007 15:06:50 -0700 Subject: Re-raising exceptions with modified message In-Reply-To: References: <1183668029.470160.218230@q69g2000hsb.googlegroups.com> Message-ID: <1183673210.409169.51830@n2g2000hse.googlegroups.com> On Jul 6, 12:21 am, Christoph Zwerschke wrote: > Kay Schluehr wrote: > > If you are sure that the exception isn't caught on another level just > > use the following showtraceback() function, manipulate it's output > > slightly and terminate your program with sys.exit() > > That's what I want to avoid. In my case the error is displayed and > evaluated in a completly different piece of software. > > -- Chris Probably the simplest solution would be to create a new exception and wrapping the old one and the additional info. Unfortunately, this may have a huge impact on 3rd party code that was catching the original exception. So, I think you should create an utility factory-like function that is either creating a new exception instance as the one caught and with the additional information, or an utility that knows how to modify the caught exception according to its type. In the first case you will need somehow to tell to the new instance exception the real stack trace, because by simply raising a new one the original stack trace may get lost. bests, ./alex -- .w( the_mindstorm )p. From gh at ghaering.de Mon Jul 9 06:53:02 2007 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 09 Jul 2007 12:53:02 +0200 Subject: Tests for Python Database API In-Reply-To: <1183847323.892963.32310@57g2000hsv.googlegroups.com> References: <1183847323.892963.32310@57g2000hsv.googlegroups.com> Message-ID: <5feiceF3ctuk1U1@mid.uni-berlin.de> MD wrote: > Are there any tests that will help me ensure that my Python database > driver conforms to the Database API v2.0 specification? There's this: http://www.initd.org/tracker/psycopg/browser/psycopg2/trunk/tests/dbapi20.py -- Gerhard From manlio_perilloNO at SPAMlibero.it Sat Jul 7 14:26:15 2007 From: manlio_perilloNO at SPAMlibero.it (Manlio Perillo) Date: Sat, 07 Jul 2007 18:26:15 GMT Subject: __unicode__ method for exception object Message-ID: Hi all. I have just noticed that exception objects does not handle well Unicode arguments. >>> e = RuntimeError(u'?????') >>> str(e) Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) >>> unicode(e) Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128) C object struct does not have a tp_unicode slot (maybe it will be added in Python 3000?), however I think that the Base Exception class should implement the __unicode__ method. Any problems in doing so? I have not yet required this feature in the Python tracker. Thanks Manlio Perillo From prx at marketinghispanics.com Sun Jul 8 11:35:57 2007 From: prx at marketinghispanics.com (Boyer Jim) Date: Sun, 8 Jul 2007 11:35:57 -0400 Subject: Article.PEGQXRVBDEGTNC.pdf Message-ID: <4691045D.5000305@provida.com> -------------- next part -------------- A non-text attachment was scrubbed... Name: Article.PEGQXRVBDEGTNC.pdf Type: application/pdf Size: 20123 bytes Desc: not available URL: From robert.kern at gmail.com Fri Jul 13 18:00:42 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 13 Jul 2007 17:00:42 -0500 Subject: Numpy array index handling In-Reply-To: <1184359937.326180.107370@g4g2000hsf.googlegroups.com> References: <1184352981.493615.18040@k79g2000hse.googlegroups.com> <1184359937.326180.107370@g4g2000hsf.googlegroups.com> Message-ID: phishboh at gmail.com wrote: > Thanks a lot for your reply. > I'll have a look at the numpy-discussion for future issues. > > FYI, I'm using Python 2.4.3 for Windows (Enthought Edition) and the > included IPython shell. I found my mistake; importing of pylab. > E.g., this works > from pylab import * ; from scipy import * ; y = arange(3) ; y[y>1] = 0 > but not > from scipy import * ; from pylab import * ; z = arange(3) ; z[z>1] = 0 > > Using the 'whos' command, I can see that y is an ndarray type, whereas > z is an array type. Ah, this means that matplotlib is configured to use Numeric, numpy's predecessor, which does not have the capability to index with boolean masks. You need to change matplotlib's "numerix" setting to "numpy". See its documentation on how to do that. Also, the Enthought Edition that you downloaded is quite old. I recommend getting newer versions of the packages. > (I also see a lot of functions, etc. How can I list just the > variables?) Functions are first-class objects in Python, so you are seeing "just the variables". However, you are probably only interested in a few types. You can look at the help for %who, which will show you how to restrict the types of objects that are displayed by that command. Unfortunately, it doesn't have a way to specifically exclude types. Most likely, you can get by with the following: In [15]: %who ndarray float int complex str ALLOW_THREADS BUFSIZE CLIP ERR_CALL ERR_DEFAULT ERR_DEFAULT2 ERR_IGNORE ERR_LOG ERR_PRINT ERR_RAISE ERR_WARN FLOATING_POINT_SUPPORT FPE_DIVIDEBYZERO FPE_INVALID FPE_OVERFLOW FPE_UNDERFLOW Inf Infinity MAXDIMS NAN NINF NZERO NaN PINF PZERO RAISE SHIFT_DIVIDEBYZERO SHIFT_INVALID SHIFT_OVERFLOW SHIFT_UNDERFLOW UFUNC_BUFSIZE_DEFAULT UFUNC_PYVALS_NAME WRAP e inf infty nan pi z You can assign that to a macro to make it easier to type: In [16]: %macro mywho 15 Macro `mywho` created. To execute, type its name (without quotes). Macro contents: _ip.magic("who ndarray float int complex str") In [17]: mywho -------> mywho() ALLOW_THREADS BUFSIZE CLIP ERR_CALL ERR_DEFAULT ERR_DEFAULT2 ERR_IGNORE ERR_LOG ERR_PRINT ERR_RAISE ERR_WARN FLOATING_POINT_SUPPORT FPE_DIVIDEBYZERO FPE_INVALID FPE_OVERFLOW FPE_UNDERFLOW Inf Infinity MAXDIMS NAN NINF NZERO NaN PINF PZERO RAISE SHIFT_DIVIDEBYZERO SHIFT_INVALID SHIFT_OVERFLOW SHIFT_UNDERFLOW UFUNC_BUFSIZE_DEFAULT UFUNC_PYVALS_NAME WRAP e inf infty nan pi z > It seems a bit risky to use 'from scipy import *'. Maybe it's better > to use 'import scipy' and then scipy.arange, to be sure what is > actually being used? Would there be any disadvanages with that > approach, other than more use of the keyboard? There really aren't any besides the extra verbosity. Using "from foo import *" is often fine for interactive use, but for code that you write in a file, it is *highly* recommended that you import modules and use them explicitly for the reasons you mention. You can reduce the typing burden somewhat like so: import numpy as N a = N.arange(10) That's a fairly common idiom in the numpy community. You can also import specific symbols if you know what you are going to use. If you're doing a lot of trig, for example: from numpy import sin, cos, tan, pi -- 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 nagle at animats.com Mon Jul 16 15:24:55 2007 From: nagle at animats.com (John Nagle) Date: Mon, 16 Jul 2007 12:24:55 -0700 Subject: Best method for inter process communications In-Reply-To: References: <1184606522.541918.18870@22g2000hsm.googlegroups.com> Message-ID: Steve Holden wrote: > JamesHoward wrote: > Given the radically inefficient representations that XML typically > requires, however, I think that worrying about localhost socket overhead > is unnecessary: if your application was *that* critical you wouldn't be > using XML in the first place. Agreed. UNIX/Linux/Python interprocess communication is inefficient compared to, say, QNX or Minix 3. But where Python and XML are involved, you've already lost 2-3 orders of magnitude in performance over something like MsgSend in QNX, or even OpenRPC. So don't worry about the socket overhead. John Nagle From deets at nospam.web.de Tue Jul 17 18:44:15 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 18 Jul 2007 00:44:15 +0200 Subject: Single-stepping through a python script In-Reply-To: References: Message-ID: <5g4v26F3f70llU2@mid.uni-berlin.de> Craig Howard schrieb: > Hello All: > > Is is possible to compile a code object and single-step through its > execution? import pdb; pdb.set_trace() Look up the pdb module documentation. Diez From byte8bits at gmail.com Thu Jul 26 17:35:11 2007 From: byte8bits at gmail.com (brad) Date: Thu, 26 Jul 2007 17:35:11 -0400 Subject: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> Message-ID: James Stroud wrote: > Midway through a semester in college, after a few days (or was it a few > weeks?) of...well...lets just say I was studying real hard...I got lost > on my way to o-chem and wandered into the interior design department by > accident and found what I like to call "the motherload". No, the girls > definitely weren't doing the sciency stuff back then. But that has been > a few years already, so maybe things have changed. > > James In my experience, things have not changed at most PolySci Universities (Georgia Tech, NC State, Virginia Tech, etc). The Comp Engineering/CS/Math classes are still full of boys. Although there are some girls, but not a lot. If a girl is in the class (and that's a big if) no boy in the classs can focus. She distorts the atmosphere of the entire room (in a good way). She's like a giant, shiny, spherical magnet close to a lot of little, ordinary metal shards. Even when the girl isn't a perfect 10 super model, the guys are still distracted because bathes daily and thus smells good. From martin at v.loewis.de Sat Jul 7 12:55:58 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sat, 07 Jul 2007 18:55:58 +0200 Subject: Unicode problem In-Reply-To: References: <5f9t3tF3c8qopU2@mid.uni-berlin.de> Message-ID: <468FC59E.7010609@v.loewis.de> > I agree, but the problem is much subtle. I have coverted a text from > iso-8859-1 to utf-8 and the codecs have translated \x27 ( the iso > apostrophe ) to \xe28099 in utf-8 ( or u'2019' in unicode code point > notation ) What software did you use to make that so? The Python codec certainly never would do such a thing. Are you sure it was latin-1 and \x27, and not windows-1252 and \x92? Regards, Martin From kimiraikkonen85 at gmail.com Thu Jul 5 13:18:53 2007 From: kimiraikkonen85 at gmail.com (kimiraikkonen) Date: Thu, 05 Jul 2007 10:18:53 -0700 Subject: The best platform and editor for Python In-Reply-To: <1183646799.400176.144570@k79g2000hse.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183646799.400176.144570@k79g2000hse.googlegroups.com> Message-ID: <1183655933.475488.157270@m36g2000hse.googlegroups.com> I just wanted a simple answer to my simple question, however topic has messed up. Think questioner as a beginner and use more understandable terms to help :) Thanks. From cousinstanley at hotmail.com Fri Jul 13 15:24:26 2007 From: cousinstanley at hotmail.com (Cousin Stanley) Date: Fri, 13 Jul 2007 14:24:26 -0500 Subject: Can a low-level programmer learn OOP? References: Message-ID: <1184354666_5947@sp12lax.superfeed.net> > .... > 2. Must be cross-platform: Linux + Windows. > > This factor can have a big impact on whether it is necessary > to learn a new language, or stick with C. > > If my platform was only Linux I could just learn GTK > and be done with it. > .... Chris .... The Python bindings for GTK in the form of a mechanism deemed PyGTK are also available for Windows and provide a diverse set of widgets for building GUI applications .... http://www.pygtk.org The Applications page lists a rather large and wide variety of the types of programs that have been built using PyGTK .... http://www.pygtk.org/applications.html There is plenty of decent documentation available and a dedicated newsgroup for assistance if needed .... -- 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 bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jul 16 03:46:36 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 16 Jul 2007 09:46:36 +0200 Subject: getting text inside the HTML tag In-Reply-To: <1184436087.239958.228710@r34g2000hsd.googlegroups.com> References: <1184436087.239958.228710@r34g2000hsd.googlegroups.com> Message-ID: <469b225c$0$2315$426a74cc@news.free.fr> kyosohma at gmail.com a ?crit : > On Jul 14, 12:47 pm, Nikola Skoric wrote: >> I'm using sgmllib.SGMLParser to parse HTML. I have successfuly parsed start >> tags by implementing start_something method. But, now I have to fetch the >> string inside the start tag and end tag too. I have been reading through >> SGMLParser documentation, but just can't figure that out... can somebody >> help? :-) >> >> -- >> "Now the storm has passed over me >> I'm left to drift on a dead calm sea >> And watch her forever through the cracks in the beams >> Nailed across the doorways of the bedrooms of my dreams" > > Oi! Try Beautiful Soup instead. That seems to be the defacto HTML > parser for Python: Nope. It's the defacto parser for HTML-like tag soup !-) From roy at panix.com Sun Jul 1 15:42:16 2007 From: roy at panix.com (Roy Smith) Date: Sun, 01 Jul 2007 15:42:16 -0400 Subject: The best platform and editor for Python References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> Message-ID: In article <1183317054.513102.127950 at q69g2000hsb.googlegroups.com>, kimiraikkonen wrote: > Hi, > For experienced with Pyhton users, which developing software and > enviroment would you suggest for Pyhton programming? Compiler+Editor > +Debugger. > > Also what are your suggestions for beginners of Pyhton programming? > > > Thank you. I'm very happy with emacs using python mode (http://www.python.org/emacs/). It's a love it or hate it kind of thing. If you're an emacs fan, you'll probably not want to use anything else. If you're not an emacs fan, this is probably not for you. There really is no separate compiler. It's part and parcel of the interpreter. Your .py files do get compiled into .pyc files, but it happens automatically the first time you run a module. No need to run a separate compilation phase like you would with C or Java. As for a debugger, I've honestly never found the need for one. I invest a lot of time in unit tests, which smoke out most of the bugs. For what's left, it's easy enough to stick print statements in strategic places to see what's going on. From nospam.themindstorm at gmail.com Thu Jul 26 07:22:00 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Thu, 26 Jul 2007 11:22:00 +0000 (UTC) Subject: os.path.walk usage on WinXP Message-ID: Hi all! I am trying to use the os.path.walk function, but I am getting a weird error: def _walk(dir_name): def selector(arg, dirname, fnames): print "selector" os.path.walk(dir_name, selector, None) File "C:\zengarden\python\python25\lib\ntpath.py", line 325, in walk names = os.listdir(top) TypeError: coercing to Unicode: need string or buffer, list found After searching through the documentation the only thing that I've found is the comment on os.listdir(path): [quote] Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a Unicode object, the result will be a list of Unicode objects. [/quote] Unfortunately, I have no idea what to do next. TIA, ./alex -- .w( the_mindstorm )p. From aahz at pythoncraft.com Thu Jul 19 13:38:26 2007 From: aahz at pythoncraft.com (Aahz) Date: 19 Jul 2007 10:38:26 -0700 Subject: class C: vs class C(object): References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> <469f1557$0$26759$426a74cc@news.free.fr> Message-ID: In article <469f1557$0$26759$426a74cc at news.free.fr>, Bruno Desthuilliers wrote: > >To make a long story short: Python 2.2 introduced a new object model >which is more coherent and more powerful than the original one. The old >one was kept so far for compatibility reasons, but there's absolutely no >reason to use it no more since "new-style" classes can do anything >"Classic" classes did and much more. IOW, don't even bother with >old-style classes. And I'll make my usual knee-jerk response disagreeing with this. For more info, search groups.google.com. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I support the RKAB From stefan.behnel-n05pAM at web.de Tue Jul 10 07:42:20 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 10 Jul 2007 13:42:20 +0200 Subject: Error when trying to write unicode xml to zipfile In-Reply-To: <46933987.6010703@v.loewis.de> References: <1184022684.557693.111890@n60g2000hse.googlegroups.com> <4693346A.4030707@web.de> <46933987.6010703@v.loewis.de> Message-ID: <4693709C.1050101@web.de> Martin v. L?wis wrote: >> Unless, obviously, you were serialising to a non-utf8 encoding. But since the >> "toxml()" method seems to return unicode here (which sounds surprising), I >> expect it a) to provide no XML declaration at all or b) to be broken anyway. > > Or c) the user forgot to specify the encoding= parameter in toxml(). Then I would expect it a) to serialise to a UTF-8 compatible encoding that does not require a declaration (which excludes Python unicode) or b) to be broken. :) Stefan From robert.rawlins at thinkbluemedia.co.uk Wed Jul 4 08:17:04 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 4 Jul 2007 13:17:04 +0100 Subject: GObject and Python 2.5 Message-ID: <001601c7be35$543322d0$fc996870$@rawlins@thinkbluemedia.co.uk> Hello Guys, Firstly I should apologise for all the mails that keep landing on the list, my SMTP server (supplied by my ISP) seems to be playing silly buggers and sending multiples. I've just installed Python 2.5 on my Debian system and I'm trying to run my application and I get 'ImportError: No module named gobject' thrown back at me. I think I've successfully install the glib library using apt-get but the problem still persists. There is obviously a module I'm missing, any ideas what it might be? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From michele.simionato at gmail.com Thu Jul 5 08:58:36 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Thu, 05 Jul 2007 12:58:36 -0000 Subject: MethodType/FunctionType and decorators In-Reply-To: <1183626989.983470.94950@o61g2000hsh.googlegroups.com> References: <1183589529.198694.109440@m36g2000hse.googlegroups.com> <1183591053.434640.119550@o61g2000hsh.googlegroups.com> <1i0qoq9.u1fu2g63fkmxN%aleax@mac.com> <1183623479.913816.301230@g4g2000hsf.googlegroups.com> <1183626989.983470.94950@o61g2000hsh.googlegroups.com> Message-ID: <1183640316.483018.227520@m36g2000hse.googlegroups.com> On Jul 5, 11:16 am, Alex Popescu wrote: > Guys, I appreciate a lot your help and explanations. It looks like I > have to read/play a bit more as some of the terms/ideas are pretty new > to me (coming to Python with a 10 years Java bag, and only with a > small dynlang bag - Ruby, Perl). > > Once again thanks, > > ./alex > -- > .w( the_mindstorm )p. BTW, if you are interested in decorators I should mention my own module, which I upgraded just yesterday to version 2.1: http://www.phyast.pitt.edu/~micheles/python/documentation.html HTH, M.S. From mal at egenix.com Sun Jul 1 10:06:58 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Sun, 01 Jul 2007 16:06:58 +0200 Subject: eGenix Partner Network (Pre-Announcement) Message-ID: <4687B502.5060405@egenix.com> Hello, we are currently looking into setting up a partner network of companies interested and able to sell and support our products with a more regional focus than we can deliver. The idea is to provide customers with a closer and more direct contact for first level support. Network partners should be able to do projects using or based on eGenix products and maintain a proper customer relationship in their native language. If you are interested in joining the network, please contact us or, even better, arrange a meeting at EuroPython or PyCon UK with us to discuss the details. We will be making an official announcement of the eGenix Partner Network sometime after EuroPython: http://www.egenix.com/company/partners/ Thanks, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 01 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/ ________________________________________________________________________ 2007-07-09: EuroPython 2007, Vilnius, Lithuania 7 days to go :::: 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 gagsl-py2 at yahoo.com.ar Fri Jul 13 23:27:12 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 14 Jul 2007 00:27:12 -0300 Subject: Circular import problem References: <1184294176.550267.119980@n60g2000hse.googlegroups.com> <1184343897.111992.107880@g4g2000hsf.googlegroups.com> Message-ID: En Fri, 13 Jul 2007 13:24:57 -0300, bvdp escribi?: > >> Seehttp://effbot.org/zone/import-confusion.htm >> Try to move the circular references later in the code (maybe inside a >> function, when it is required), or much better, refactor it so there is >> no >> circularity. >> >> -- >> Gabriel Genellina > > Yes, thanks. I'd read that page before posting. Helpful. > > But, I still don't understand how python can access a function in a > file I have NOT included. In this case, to get things to work, I DO > NOT "import MMA.grooves" but later in the module I access a function > with "xx=MMA.grooves.somefunc()" and it finds the function, and works > just fine. It shouldn't work. That depends a bit on what is "MMA" and what is "grooves". MMA.grooves means "look for an attribute named grooves inside MMA". If MMA is a module, and MMA.grooves is a class/function defined inside the module, you don't need to import it before using it. But if MMA is a package, and MMA.grooves is a module inside that package, you need to import it first (unless MMA/__init__.py does that already) > I have tried to delay the import, and that does work. But, from a > stylistic view I really to like to have all my imports at the top of > the module. Maybe some old assembler/C habits on my part. Sure, it's considered good style. -- Gabriel Genellina From openopt at ukr.net Sun Jul 1 04:53:17 2007 From: openopt at ukr.net (dmitrey) Date: Sun, 01 Jul 2007 01:53:17 -0700 Subject: howto resend args and kwargs to other func? Message-ID: <1183279997.244378.105810@n60g2000hse.googlegroups.com> I need something like this: def func1(*args, **kwargs): if some_cond: return func2(*args, **kwargs) else: return func3(some_other_args, **kwargs) Thank you in advance, D. From http Fri Jul 27 02:35:44 2007 From: http (Paul Rubin) Date: 26 Jul 2007 23:35:44 -0700 Subject: zip() function troubles References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> Message-ID: <7xfy3ae4lb.fsf@ruckus.brouhaha.com> Peter Otten <__peter__ at web.de> writes: > When you are allocating a lot of objects without releasing them the garbage > collector kicks in to look for cycles. Try switching it off: I think that is the answer. The zip took almost 2 minutes without turning gc off, but takes 1.25 seconds with gc off. It turned a linear-time algorithm into a quadratic one. I think something is broken about a design where that can happen. Maybe Pypy will have a generational GC someday. From pcapoyotecnico at gmail.com Sun Jul 15 17:27:10 2007 From: pcapoyotecnico at gmail.com (playrambo.blogspot.com) Date: Sun, 15 Jul 2007 14:27:10 -0700 Subject: get a free 150$ sign up bonus without deposit!!! tinyurl.com/ysmfw8 Message-ID: <1184534830.682852.72970@r34g2000hsd.googlegroups.com> (and also free licenses of pokertracker and pokeracehud after 500partypoints) tinyurl.com/ysmfw8 free 150$ NO deposit!!! (\__/) (='.'=) (")_(") From johnmfisher at comcast.net Sat Jul 21 20:34:31 2007 From: johnmfisher at comcast.net (John Fisher) Date: Sat, 21 Jul 2007 17:34:31 -0700 Subject: converting 64-bit fixed-point to float References: <1i1k9cc.1hyy4zm1ybovgwN%johnmfisher@comcast.net> <1185040832.243875.48420@e16g2000pri.googlegroups.com> Message-ID: <1i1m3fr.1xtv09p19whv9uN%johnmfisher@comcast.net> attn.steven.kuo at gmail.com wrote: > On Jul 20, 5:59 pm, johnmfis... at comcast.net (John Fisher) wrote: > > Hi Group, > > > > troubles with converting signed 32.32, little-endian, 2's complement > > back to floating point. I have been trying to brew it myself. I am > > running Python 2.5 on a Mac. Here is the C-code I have been trying to > > leverage: > > > > double FPuint8ArrayToFPDouble(uint8 *buffer, int startIndex) > > { > > uint32 resultDec = 0; > > uint32 resultWh = 0; > > int i; > > > > for(i = 0; i < 4; i++) > > { > > resultDec += (uint32)buffer[startIndex + i] * pow(2, (i*8)); > > resultWh += (uint32)buffer[startIndex + i + 4] * pow(2, (i*8)); > > } > > > > return ( (double)((int)resultWh) + (double)(resultDec)/4294967296.0 ); > > > > } > > > There are a few problem spots in that C code. I tend to > think that it "works" because you're on a system that has > 4-byte int and CHAR_BIT == 8. When the most-significant-bit (MSB) > of resultWh is 1, then casting to int makes that a negative > value (i.e., MSB == the sign bit). > > I presume that somewhere you include (from C99) > and that uint32 is really uint32_t, etc. For that to be > portable, you should probably cast to int32_t? > > #include > #include > #include > > double arr2dbl (uint8_t *buffer, int startIndex) > { > uint32_t decimal = 0; > uint32_t whole = 0; > size_t i; > for (i = 0; i < 4; ++i) > { > decimal += (buffer[startIndex + i] << (i*8)); > whole += (buffer[startIndex + i + 4] << (i*8)); > } > return (int32_t)whole + (decimal/(UINT32_MAX+1.0)); > } > > int main (void) > { > uint8_t arr[7][8] = { > {0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff}, > {0, 0, 0, 0, 0, 0, 0, 0}, > {51, 51, 51, 51, 0, 0, 0, 0}, > {0, 0, 0, 0, 1, 0, 0, 0}, > {0, 0, 0, 0, 2, 0, 0, 0}, > {102, 102, 102, 38, 42, 1, 0, 0 }, > {205, 204, 204, 204, 0xff, 0xff, 0xff, 0xff}}; > size_t i; > double result; > for (i = 0; i < sizeof arr/sizeof arr[0]; ++i) > { > result = arr2dbl(arr[i], 0); > printf("%f\n", result); > } > return 0; > } > > > > > > > > > Here is my version in Python, with some test code built in: > > > > from ctypes import * > > > > def conv64(input): > > input1=[0]*8 > > input1[0]=c_ushort(input[0]) > > input1[1]=c_ushort(input[1]) > > input1[2]=c_ushort(input[2]) > > input1[3]=c_ushort(input[3]) > > input1[4]=c_ushort(input[4]) > > input1[5]=c_ushort(input[5]) > > input1[6]=c_ushort(input[6]) > > input1[7]=c_ushort(input[7]) > > #print input1[0].value, > > input1[1].value,input1[2].value,input1[3].value > > #print > > input1[4].value,input1[5].value,input1[6].value,input1[7].value > > #print > > resultDec=c_ulong(0) > > resultWh=c_ulong(0) > > for i in range(4): > > dec_c=c_ulong(input1[i].value) > > Wh_c=c_ulong(input1[i+4].value) > > resultDec.value=resultDec.value+dec_c.value*2**(i*8) > > resultWh.value=resultWh.value+Wh_c.value*2**(i*8) > > conval=float(int(resultWh.value))+float(resultDec.value)/4294967296.0 > > #print conval > > return conval > > #tabs got messed up bringing this into MacSoup > > > (snipped) > > > > > > Finally, here is the output I get from my code: > > > > > > > > output should be -1 is 4294967296.0 > > output should be 0 is 0.0 > > output should be 0.2 is 0.199999999953 > > output should be 1 is 1.0 > > output should be 2 is 2.0 > > output should be 298.15 is 298.15 > > output should be -0.2 is 4294967295.8 > > > > Thanks for any light you can shed on my ignorance. > > > > wave_man > > > This is my translation: > > from ctypes import * > > def conv64(input): > input1 = [c_uint8(item) for item in input] > dec = c_uint32(0) > whl = c_uint32(0) > for i in xrange(4): > dec.value += (input1[i].value << (i*8)) > whl.value += (input1[i+4].value << (i*8)) > cast_whl_to_int = c_int32(whl.value) > return float(cast_whl_to_int.value + dec.value/4294967296.0) > > > for arr in [[0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff], > [0, 0, 0, 0, 0, 0, 0, 0], > [51, 51, 51, 51, 0, 0, 0, 0], > [0, 0, 0, 0, 1, 0, 0, 0], > [0, 0, 0, 0, 2, 0, 0, 0], > [102, 102, 102, 38, 42, 1, 0, 0], > [205,204,204,204,255,255,255,255]]: > print "%f" % conv64(arr) > > > > However, I've not looked deeply into ctypes so I > don't know if c_int32 is really C's int, or int32_t, or ??? > > -- > Hope this helps, > Steven Actually this was very helpful, thanks. Rgds, wave_man From wbrehaut at mcsnet.ca Mon Jul 16 13:36:43 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Mon, 16 Jul 2007 11:36:43 -0600 Subject: Can a low-level programmer learn OOP? References: <4697d9f0$0$7614$426a74cc@news.free.fr> <469b2477$0$11769$426a74cc@news.free.fr> Message-ID: On Mon, 16 Jul 2007 09:55:35 +0200, Bruno Desthuilliers wrote: >Wayne Brehaut a ?crit : >> On Sat, 14 Jul 2007 06:01:56 +0200, Bruno Desthuilliers >> wrote: >> >>> Chris Carlen a ?crit : >>>> Hi: >>>> >>>> From what I've read of OOP, I don't get it. I have also found some >>>> articles profoundly critical of OOP. I tend to relate to these articles. >>>> >> >> === 8< === >> >>>> Hence, being a hardware designer rather than a computer scientist, I am >>>> conditioned to think like a machine. I think this is the main reason >>>> why OOP has always repelled me. >>> OTOH, OO is about machines - at least as conceveid by Alan Key, who >>> invented the term and most of the concept. According to him, each object >>> is a (simulation of) a small machine. >> >> Oh you young'uns, not versed in The Ancient Lore, but filled with >> self-serving propaganda from Xerox PARC, Alan Kay, and Smalltalk >> adherents everywhere! > >Not feeling concerned. > >(snip pro-simula/anti-Xerox propaganda). Or, more accurately, pro: 1. Nygaard & Dahl as the inventors of most of the concept of OOP 2. Simula as the first OOP 3. Kay as the originator of the term OOP 4. Kay, Xerox PARC, and Smalltalk as making significant useful advances in implementation of OOP and "popularizing" it and anti: 1. attributing credit for any accomplishment to someone who doesn't himself claim it and even denies it wwwayne o/o From kirby.urner at gmail.com Tue Jul 31 16:38:55 2007 From: kirby.urner at gmail.com (kirby.urner at gmail.com) Date: Tue, 31 Jul 2007 20:38:55 -0000 Subject: Live editing... Message-ID: <1185914335.472511.172040@m37g2000prh.googlegroups.com> There's been some chatter on edu-sig (python.org) of late regarding Python's capabilities in the "edit/continue" tradition, meaning debugging tools, and/or IDE tools, that give the developer real time write access to running programs. I think a good design would be something like the ZODB, or the ZODB itself, to save the entire working environment, like a Smalltalk image, at which point a "supervisor Python" (a whole different instance, perhaps on another chip), could do "brain surgery" on the "hibernating Python" (like a patient undergoing surgery). You basically simulate or emulate the "operating table" version, without putting yourself at its mercy. If you break it completely, while doing your brain surgery, just abort the instance and roll back to the previously saved version. It's like sitting on top of a version control system, while never getting to directly edit the currently operating version (the supervisor). The alternative, allowing a developer to undermine his/her own running platform, seems to unnecessarily conflate a runtime and design time mode, which isn't just some stupid prejudice. We need that separation, just as we keep distance between production and development copies of things. Don't fix a running engine if you can fix an emulated running engine. Once you're happy with your changes, commit, and set it running for real. It still might crash, which is why you're glad for rollback capabilities. Smalltalk images meet CVS? Python atop Mercurial? Kirby From malaclypse2 at gmail.com Wed Jul 4 11:23:33 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 4 Jul 2007 11:23:33 -0400 Subject: using subprocess for non-terminating command In-Reply-To: <20070704143641.GA3434@gmail.com> References: <1183549118.773813.132940@r34g2000hsd.googlegroups.com> <1183550943.531211.306410@n60g2000hse.googlegroups.com> <20070704143641.GA3434@gmail.com> Message-ID: <16651e80707040823y7d8103bbl34da35a776b147f@mail.gmail.com> On 7/4/07, O.R.Senthil Kumaran wrote: > Yes, I am aware of the ping -c option. But again even that does not help. > try > process = subprocess.Popen('ping -c 10 127.0.0.1', stdin=subprocess.PIPE, > shell=True) > process.stdout.read() # This will hang again. When I try that, it doesn't hang. Instead, I get the output of the ping command pruinted to the screen, then the following exception: Traceback (most recent call last): File "", line 1, in AttributeError: 'NoneType' object has no attribute 'read' That's because you tied stdin to a pipe in your Popen call, but then tried to read from stdout. Try this instead: >>> process = subprocess.Popen("ping -c 10 127.0.0.1", stdout=subprocess.PIPE, shell=True) >>> process.stdout.readlines() ['PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.\n', '64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.049 ms\n', '64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.033 ms\n', '64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.040 ms\n', '64 bytes from 127.0.0.1: icmp_seq=4 ttl=64 time=0.033 ms\n', '64 bytes from 127.0.0.1: icmp_seq=5 ttl=64 time=0.033 ms\n', '64 bytes from 127.0.0.1: icmp_seq=6 ttl=64 time=0.030 ms\n', '64 bytes from 127.0.0.1: icmp_seq=7 ttl=64 time=0.032 ms\n', '64 bytes from 127.0.0.1: icmp_seq=8 ttl=64 time=0.028 ms\n', '64 bytes from 127.0.0.1: icmp_seq=9 ttl=64 time=0.030 ms\n', '64 bytes from 127.0.0.1: icmp_seq=10 ttl=64 time=0.039 ms\n', '\n', '--- 127.0.0.1 ping statistics ---\n', '10 packets transmitted, 10 received, 0% packet loss, time 8991ms\n', 'rtt min/avg/max/mdev = 0.028/0.034/0.049/0.009 ms\n'] -- Jerry From steve at holdenweb.com Fri Jul 6 06:42:08 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Jul 2007 06:42:08 -0400 Subject: SMTP server w/o using Twisted framework In-Reply-To: <5f68a6F3adj19U1@mid.uni-berlin.de> References: <1183661809.613856.312100@57g2000hsv.googlegroups.com> <1183664445.020890.226520@c77g2000hse.googlegroups.com> <5f68a6F3adj19U1@mid.uni-berlin.de> Message-ID: <468E1C80.7030308@holdenweb.com> Gerhard H?ring wrote: > _spitFIRE wrote: >> [looking up DNS MX records] >> Thanks for the pointer. However, as I said currently, I can't use >> anything other than the standard libraries. > > Sure you can. You just need to get rid of the "only standard library" > requirement rule. > > That works best by showing the alternatives to whoever set that requirement: > > - use pyDNS > - use an existing (probably non-Python) SMTP daemon > - reimplement some parts of pyDNS yourself and develop a basic (crappy) > SMTP daemon yourself > > For doing the latter, you should budget at least one week. > > FWIW another reason why SMTP servers should retry on temporary failure > is that increasing use of Greylisting (*), which was precisely designed > to filter out mail from "crappy" servers, like botnets, and - well - > cheap custom written ones ;-) > I'd actually use dnspython in preference to pyDNS, it's very easy to use. I have some MX-server lookup code somewhere in the vault, if you can use an external library. 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 samwyse at gmail.com Sat Jul 28 10:47:48 2007 From: samwyse at gmail.com (samwyse) Date: Sat, 28 Jul 2007 14:47:48 -0000 Subject: Python 2.5.1 can't find win32file? In-Reply-To: <1185628601.992750.55990@e16g2000pri.googlegroups.com> References: <1185628601.992750.55990@e16g2000pri.googlegroups.com> Message-ID: <1185634068.634813.187350@e16g2000pri.googlegroups.com> On Jul 28, 8:16 am, samwyse wrote: > I just upgraded from 2.4.something to 2.5.1. I get the stuff below. > I tried easy-installing pywin32; same results. Anyone know what's > going on? > Interestingly enough, this works: C:\Python25>path=%path%;C:\Python25\Lib\site-packages\pywin32-210- py2.5-win32.eg g\pywin32_system32 C:\Python25>python Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import win32file >>> It looks like the system search path isn't getting updated so that PYWINTYPES25.DLL can be found when win32file.pyd is loaded. Anyone have any ideas? From phd at phd.pp.ru Thu Jul 26 10:23:05 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 26 Jul 2007 18:23:05 +0400 Subject: SQLObject 0.7.8 Message-ID: <20070726142305.GC30176@phd.pp.ru> Hello! I'm pleased to announce the 0.7.8 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.7.8 News and changes: http://sqlobject.org/docs/News.html What's New ========== News since 0.7.7 ---------------- Bug Fixes ~~~~~~~~~ * Replaced calls to style.dbColumnToPythonAttr() in joins.py by name/dbName lookup in case the user named columns differently using dbName. * Minor correction in the tests: we fully support EnumCol in Postgres. * MySQLConnection now recognizes Enum, Double and Time columns when drawing the database scheme from DB. * Minor fix in FirebirdConnection.fromDatabase. * Fixed a bug with default field values for columns for firebird connection. * Prevent a deadlock in declarative.threadSafeMethod() by not reacquiring the class lock. * Fixed a bug in col.createSQL(). * Fixed a bug in converting date/time for years < 1000 (time.strptime() requires exactly 4 digits for %Y, hence a year < 1000 must be 0-padded). Other Changes ~~~~~~~~~~~~~ * Changed string quoting style for PostgreSQL and MySQL from \' to ''. For a more complete list, please see the news: http://sqlobject.org/docs/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From sjmachin at lexicon.net Tue Jul 24 18:46:17 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 24 Jul 2007 15:46:17 -0700 Subject: printing unicode strings In-Reply-To: <1185310571.173514.240940@r34g2000hsd.googlegroups.com> References: <1185310571.173514.240940@r34g2000hsd.googlegroups.com> Message-ID: <1185317177.315543.187160@x40g2000prg.googlegroups.com> On Jul 25, 6:56 am, 7stud wrote: > Can anyone tell me why I can print out the individual variables in the > following code, but when I print them out combined into a single > string, I get an error? > > symbol = u'ibm' > price = u'4 \xbd' # 4 1/2 > > print "%s" % symbol > print "%s" % price.encode("utf-8") > print "%s %s" % (symbol, price.encode("utf-8") ) > > --output:-- > ibm > 4 1/2 > File "pythontest.py", line 6, in ? > print "%s %s" % (symbol, price.encode("utf-8") ) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position > 2: ordinal not in range(128) Because the first part is Unicode and the second part (after encoding in utf8) is str. It is trying to convert the second part to Unicode, using the default codec (ascii), which of course must fail: >>> price = u"4 \xbd" >>> price.encode("utf8") '4 \xc2\xbd' >>>>>> price.encode("utf8").decode("ascii") Traceback (most recent call last): File "", line 1, in UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 2: ordinal not in range(128) >>> From wildemar at freakmail.de Thu Jul 5 18:08:11 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 06 Jul 2007 00:08:11 +0200 Subject: Where is the syntax for the dict() constructor ?! In-Reply-To: <468d49ff$0$90264$14726298@news.sunsite.dk> References: <468D1D9D.6060002@gmail.com> <468D3445.2060408@gmail.com> <468d49ff$0$90264$14726298@news.sunsite.dk> Message-ID: <468D6BCB.6010104@freakmail.de> Nis J?rgensen wrote: > Neil Cerutti skrev: > > >> Mostly you can use the default 'excel' dialect and be quite >> happy, since Excel is the main reason anybody still cares about >> this unecessarily hard to parse (it requires more than one >> character of lookahead for no reason except bad design) data >> format. >> > > I knew there had to be a reason why everyone is using xml these days ... > > Nis > Are you serious? You want to cram tabular data in some tree-oriented data format? Now THAT is evangelism. Why is it a bad desing choice to seperate values by a specific delimiter, thus emulating a tabular arrangement? I really don't get it. Thats the natural format for tabular data. Period. /W From steve at holdenweb.com Mon Jul 2 21:32:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Jul 2007 21:32:43 -0400 Subject: object references/memory access In-Reply-To: <1183417108.245203.158830@x35g2000prf.googlegroups.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1183407411.397142.304790@e16g2000pri.googlegroups.com> <1183417108.245203.158830@x35g2000prf.googlegroups.com> Message-ID: Karthik Gurusamy wrote: > On Jul 2, 3:01 pm, Steve Holden wrote: >> Karthik Gurusamy wrote: >>> On Jul 1, 12:38 pm, dlomsak wrote: >> [...] >> >>> I have found the stop-and-go between two processes on the same machine >>> leads to very poor throughput. By stop-and-go, I mean the producer and >>> consumer are constantly getting on and off of the CPU since the pipe >>> gets full (or empty for consumer). Note that a producer can't run at >>> its top speed as the scheduler will pull it out since it's output pipe >>> got filled up. >> But when both processes are in the memory of the same machine and they >> communicate through an in-memory buffer, what's to stop them from >> keeping the CPU fully-loaded (assuming they are themselves compute-bound)? > > If you are a producer and if your output goes thru' a pipe, when the > pipe gets full, you can no longer run. Someone must start draining the > pipe. > On a single core CPU when only one process can be running, the > producer must get off the CPU so that the consumer may start the > draining process. > Wrong. The process doesn't "get off" the CPU, it remains loaded, and will become runnable again once the buffer has been depleted by the other process (which is also already loaded into memory and will become runnable as soon as a filled buffer becomes available). >>> When you increased the underlying buffer, you mitigated a bit this >>> shuffling. And hence saw a slight increase in performance. >>> My guess that you can transfer across machines at real high speed, is >>> because there are no process swapping as producer and consumer run on >>> different CPUs (machines, actually). >> As a concept that's attractive, but it's easy to demonstrate that (for >> example) two machines will get much better throughput using the >> TCP-based FTP to transfer a large file than they do with the UDP-based >> TFTP. This is because the latter protocol requires the sending unit to >> stop and wait for an acknowledgment for each block transferred. With >> FTP, if you use a large enough TCP sliding window and have enough >> content, you can saturate a link as ling as its bandwidth isn't greater >> than your output rate. >> >> This isn't a guess ... > > What you say about a stop-n-wait protocol versus TCP's sliding window > is correct. > But I think it's totally orthogonal to the discussion here. The issue > I'm talking about is how to keep the end nodes chugging along, if they > are able to run simultaneously. They can't if they aren't on a multi- > core CPU or one different machines. > If you only have one CPU then sure, you can only run one process at a time. But your understanding of how multiple processes on the same CPU interact is lacking. > >>> Since the two processes are on the same machine, try using a temporary >>> file for IPC. This is not as efficient as real shared memory -- but it >>> does avoid the IPC stop-n-go. The producer can generate the multi-mega >>> byte file at one go and inform the consumer. The file-systems have >>> gone thru' decades of performance tuning that this job is done really >>> efficiently. >> I'm afraid this comes across a bit like superstition. Do you have any >> evidence this would give superior performance? >> > > I did some testing before when I worked on boosting a shell pipeline > performance and found using file-based IPC was very good. > (some details at http://kar1107.blogspot.com/2006/09/unix-shell-pipeline-part-2-using.html > ) > > Thanks, > Karthik > >>>> Thanks for the replies so far, I really appreciate you guys >>>> considering my situation and helping out. If you get better performance by writing files and reading them instead of using pipes to communicate then something is wrong. 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 martin at see.sig.for.address Sun Jul 1 18:36:00 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Sun, 01 Jul 2007 23:36:00 +0100 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <3vuf835e6m0dccrhipolnebpuugpni75fp@4ax.com> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <3vuf835e6m0dccrhipolnebpuugpni75fp@4ax.com> Message-ID: Roedy Green wrote: > On Sun, 01 Jul 2007 17:47:36 +0100, Martin Gregorie > wrote, quoted or indirectly quoted > someone who said : > >> GPS time is UTC time and I'd assume the same is true for Loran. > > not according to this site that has clocks running on all three. > They are out slightly. > > http://www.leapsecond.com/java/gpsclock.htm > A useful reference: thanks. Interesting that GPS and Loran are slightly out from Zulu. I'll ask round and see if this is something that ATP pilots are aware of: as a glider pilot and GPS user I'd never heard of it. So far the deviations from UTC are probably not enough to affect navigation significantly, but I wonder if banks using networks that timestamp transactions with GPS time know about it. Of course the deviation can't affect disputes where the timestamps are being used to decide event sequences within a single network. However, there could be legal implications if absolute time is important or if the timestamps are being compared across different networks, e.g SWIFT vs CHAPS or Fedwire. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From gagsl-py2 at yahoo.com.ar Mon Jul 9 07:42:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Jul 2007 08:42:22 -0300 Subject: The file executing References: <1183426846.550981.11910@m36g2000hse.googlegroups.com> <1183430828.997331.84340@e9g2000prf.googlegroups.com> <1183470421.012591.243300@k79g2000hse.googlegroups.com> <1183752922.290253.8600@q75g2000hsh.googlegroups.com> Message-ID: En Fri, 06 Jul 2007 17:15:22 -0300, Benjamin escribi?: >> > > > How does one get the path to the file currently executing (not the >> > > > cwd). Thank you > So: > if __name__ == "main": > currentDir = os.path.dirname(sys.argv[0]) > else: > currentDir = os.path.dirname(__file__) I think you meant to test for "__main__", but anyway, this should be enough: currentDir = os.path.dirname(__file__) or perhaps os.path.dirname(os.path.abspath(__file__)). Try to determine that early in your program because __file__ may contain a relative path (and will give a wrong result after changing the current directory). -- Gabriel Genellina From email at christoph-haas.de Wed Jul 25 16:02:44 2007 From: email at christoph-haas.de (Christoph Haas) Date: Wed, 25 Jul 2007 22:02:44 +0200 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185392048.737400.290050@j4g2000prf.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> Message-ID: <20070725200244.GC12600@torf.workaround.org> On Wed, Jul 25, 2007 at 12:34:08PM -0700, walterbyrd wrote: > When I posted "Python" I meant the Python web-developement world. In > particular, python frameworks, like CherryPy, have requirements that > are not realistic for most shared hosting plans. It's true that the requirements are higher than what the old-school CGI/PHP web hosters offer. But with todays virtual root servers it's really inexpensive to run such a server. And using frameworks allows you to control all aspects of the web serving like URL dispatching, error handling and is probably even faster than PHP because necessary resources (like database connections) are initalized upon startup of the web application. PHP and CGIs do this everytime they get called. > Maybe I'm wrong, but I often get the idea that those who develop > python frameworks don't give a thought to the realities of shared > hosting. They seem to think that everybody has complete control over > the server. Things are very different in the PHP universe. Without wanting to sound arrogant: it's my belief that web hosters just offering htdocs/PHP will probably just be useful for the noob-customers who have no idea of operating systems but just want their blinking personal homepage online. There are good PHP applications and I wouldn't want to give up phpmyadmin or squirrelmail. But with today's demand for fully controllable interactive (you will never hear me propagate that bullshit buzzword "Web x.0") web sites a framework seems to be a viable way. For me PHP has a bitter taste of "easy enough for every noob to use it" which makes it the language the most insecure applications are written in. > The point is: PHP framework makers are very considerate of the > realities of shared hosting. Python framework makers don't seem to > give it a thought. Just maybe, that's something that Python could > learn from PHP. Perhaps. But the hosting market changes. And I believe that PHP suits the simpler applications better. I would point a beginner in web programming more likely to PHP than torture them with frameworks. It's just too heavy. OTOH full-featured frameworks are way more complicated and have eviler requirements but there are hardly any limitation on the kinds of sites you can power with them. EO2? Cheers Christoph From musiccomposition at gmail.com Tue Jul 17 21:54:19 2007 From: musiccomposition at gmail.com (Benjamin) Date: Wed, 18 Jul 2007 01:54:19 -0000 Subject: wxPython, threads, and search engine Message-ID: <1184723659.204544.229000@x35g2000prf.googlegroups.com> I'm writing a search engine in Python with wxPython as the GUI. I have the actual searching preformed on a different thread from Gui thread. It sends it's results through a Queue to the results ListCtrl which adds a new item. This works fine or small searches, but when the results number in the hundreds, the GUI is frozen for the duration of the search. I suspect that so many search results are coming in that the GUI thread is too busy updating lists to respond to events. I've tried buffer the results so there's 20 results before they're sent to the GUI thread and buffer them so the results are sent every .1 seconds. Nothing helps. Any advice would be great. From wildemar at freakmail.de Thu Jul 12 19:09:48 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 13 Jul 2007 01:09:48 +0200 Subject: [Fwd: RE: Lists in classes] In-Reply-To: <4696B083.70801@freakmail.de> References: <4696B083.70801@freakmail.de> Message-ID: <4696B4BC.4090305@freakmail.de> Adam Pletcher wrote: > I'm curious (and somewhat new to Python)... What's the benefit of > inheriting from 'object'? > > The docs aren't clear on that, nor is that used in the class examples > I've seen. > Thanks in advance. > Well, they are, but they are just not well integrated. Which they, the docs themselves, admit. The keyword is 'new-style classes'. Have a read or two: Maybe this is a better intro, however: Hope that helps. /W From tchur at optusnet.com.au Mon Jul 9 22:34:56 2007 From: tchur at optusnet.com.au (Tim Churches) Date: Tue, 10 Jul 2007 12:34:56 +1000 Subject: Pythonic cats (and dogs?) Message-ID: <200707100234.l6A2YuiE023296@mail16.syd.optusnet.com.au> An embedded and charset-unspecified text was scrubbed... Name: not available URL: From gamehack at gmail.com Wed Jul 18 11:05:37 2007 From: gamehack at gmail.com (gamehack) Date: Wed, 18 Jul 2007 08:05:37 -0700 Subject: Property Descriptor - Public Getter, Private Setter Message-ID: <1184771137.140502.187210@e16g2000pri.googlegroups.com> Hi all, I was looking around the net to figure out how I can use the property() descriptor to make a property readable by everyone and only settable by the class or any derived classes. Thanks. Regards, gh From zyzhu2000 at gmail.com Fri Jul 27 10:11:28 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 27 Jul 2007 14:11:28 -0000 Subject: Another C API Question In-Reply-To: References: <1185498383.333248.225360@19g2000hsx.googlegroups.com> Message-ID: <1185545488.751250.200270@z24g2000prh.googlegroups.com> Hi Farshid, On Jul 26, 8:18 pm, Farshid Lashkari wrote: > beginner wrote: > > I know obj is a number, but I do not know the exact type. How can I > > convert it to double without writing a giant switch() that exhausts > > every single type of number? > > Try using the PyFloat_AsDouble(...) function, it should be able to > convert an object to a double, as long as the object implements the > __float__ method. This works with PyFloat only. It does not work with integers. Thanks, b From steven at REMOVE.THIS.cybersource.com.au Wed Jul 11 01:28:18 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Jul 2007 05:28:18 GMT Subject: stripping the first byte from a binary file References: <1184063032.195000.25880@i13g2000prf.googlegroups.com> <1184115964.912526.273780@e16g2000pri.googlegroups.com> Message-ID: On Wed, 11 Jul 2007 01:06:04 +0000, rvr wrote: > Is there a way to edit the file in place? The best I seem to be able to > do is to use your second solution to read the file into the string, then > re-open the file for writing and put the whole thing back (minus the > first byte). Thanks. I don't believe that any of the popular operating systems in common use (Windows, Linux, Mac, *BSD) have any such functionality. For safety, you are best off copying the file (minus the first byte) to a temporary file, then renaming the copy over the original. That way if your process dies midway through copying the file, you don't lose data. Renaming the file is atomic under Linux and (probably) Mac, so it is as safe as possible. Even under Windows, which isn't atomic, it has a smaller margin for disaster than over-writing the file in place. -- Steven. From kyosohma at gmail.com Mon Jul 9 13:47:01 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 09 Jul 2007 10:47:01 -0700 Subject: ImportError: MemoryLoadLibrary failed loading Message-ID: <1184003221.733125.38270@57g2000hsv.googlegroups.com> Hi, Recently I began my journey into creating executables. I am using Andrea Gavana's cool GUI2EXE program which works very well and that is a GUI for py2ece. I am also using Inno Setup to create a script/executable. Anyway, today I am putting the program to the test with some volunteer testers and I've hit a wall. On the first tester's PC the program installed beautifully and runs great. The next tester's PC, the program failed to run complaining that MSVCR71.dll didn't exist. I copied that file on there and now I get the following traceback written to my exe's log file: Traceback (most recent call last): File "reminder.py", line 23, in ? File "zipextimporter.pyo", line 78, in load_module File "wx\__init__.pyo", line 45, in ? File "zipextimporter.pyo", line 78, in load_module File "wx\_core.pyo", line 4, in ? File "zipextimporter.pyo", line 91, in load_module ImportError: MemoryLoadLibrary failed loading wx\_core_.pyd I see other user's have this issue too sometimes and they talk a lot about a "gdiplus.dll" file. My user's PC has that file in 4 places on her computer and my development PC has it in 6 places. Does either DLL have to be in a specific location for the executable to find it? Is this something else entirely? I tried sticking the gdiplus.dll file in the directory my executable runs from too, but that didn't work either. I have posted this to the wxPython's group and the py2exe group, but the latter doesn't have much activity and the wxPython suggestions didn't work. Thanks a lot! Mike From klove at tax.ok.gov Fri Jul 27 15:11:02 2007 From: klove at tax.ok.gov (Kenneth Love) Date: Fri, 27 Jul 2007 14:11:02 -0500 Subject: Comparing Dictionaries In-Reply-To: <1185529358.128424.52450@19g2000hsx.googlegroups.com> References: <1185529358.128424.52450@19g2000hsx.googlegroups.com> Message-ID: <6.1.0.6.2.20070727130505.02646798@tax.ok.gov> At 04:42 AM 7/27/2007, Ali wrote: >On Jul 26, 10:18 pm, Kenneth Love wrote: > > Hello, > > > > I am new to Python, but not programming. I would like to start my > > Python career by developing programs according to the "best practices" > > of the industry. Right now, that appears to be unit tests, patterns, > > and source code control. > >I am not sure about "best", but one of my "favourite practices" is to >not re-write code that other people have written, and have released >under licenses that allow you to do anything with it. > > > So, I am trying to write a unit test for some code that reads a Windows > > style INI file and stores the section, key, and values in a dictionary > >So, in the standard library: >http://docs.python.org/lib/module-ConfigParser.html >And if you want a more involved approach: >http://www.voidspace.org.uk/python/configobj.html > >Ali The published recipe (based on ConfigParser) did not handle my INI files. I have periods in both the section names and the key names. The INI files contents were developed according to an internally defined process that other non-Python programs rely on. The published recipe *did not work* with this scenario. Believe me, not modifying 3rd-party code is something I prefer and already practice. The code has to work first. In case anyone is curious, here is a link to the original: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65334 I combined the load/save routines, slogged through the unfamiliar syntax, changed the section/key separator to '$', and started writing unit tests. Sincerely, Kenneth Love -- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Kenneth Love | Oklahoma Tax Commission DP Programmer/Analyst | Information Technology (405) 522 - 5864 | http://www.tax.ok.gov/ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- From martin at see.sig.for.address Wed Jul 11 08:39:20 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Wed, 11 Jul 2007 13:39:20 +0100 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <5fh0imF3cjte7U1@mid.individual.net> Message-ID: Ilya Zakharevich wrote: > [A complimentary Cc of this posting was sent to > Martin Gregorie > ], who wrote in article : >> Its in "A Short History of Time". Sorry I can't quote chapter or page, >> but a friend borrowed my copy and lent me Dawkins "Climbing Mount >> Improbable" before vanishing, never to be seen since. Not an equal >> exchange: I preferred ASHOT to CMI. > Oops - I should have written "A Brief History of Time". It was the first edition, so I don't know if it was altered/edited out of later versions. > I would prefer a reference to a peer-reviewed paper. ;-) > Sure, but I don't think you'll find one. It was in a descriptive, rather than rigorous, passage. But then, the book famously had only one equation in it. -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From jeffrey at fro.man Thu Jul 19 14:01:49 2007 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 19 Jul 2007 11:01:49 -0700 Subject: Python version changes, sys.executable does not Message-ID: <139v9oe22rihh40@corp.supernews.com> Hello All, I have two python versions installed, one in /usr/bin, and one in /usr/local/bin. However, when invoking python without a full path, I get the wrong executable with the right sys.executable string! ---------------------------------------------------------------------------- [root at M1 ~]# ls -l /usr/local/bin/python* -rwxr-xr-x 2 root root 3783810 Jul 19 09:15 /usr/local/bin/python -rwxr-xr-x 2 root root 3783810 Jul 19 09:15 /usr/local/bin/python2.5 -rwxr-xr-x 1 root root 1281 Jul 19 09:16 /usr/local/bin/python2.5-config lrwxrwxrwx 1 root root 16 Jul 19 09:16 /usr/local/bin/python-config -> python2.5-config [root at M1 ~]# ls -l /usr/bin/python* -rwxr-xr-x 2 root root 5396 May 2 16:28 /usr/bin/python lrwxrwxrwx 1 root root 6 Jul 18 12:20 /usr/bin/python2 -> python -rwxr-xr-x 2 root root 5396 May 2 16:28 /usr/bin/python2.3 [root at M1 ~]# which python /usr/local/bin/python [root at M1 ~]# /usr/local/bin/python -c "import sys; print sys.executable; print sys.version; set()" /usr/local/bin/python 2.5 (r25:51908, Jul 19 2007, 09:13:48) [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] [root at M1 ~]# env python -c "import sys; print sys.executable; print sys.version; set()" /usr/local/bin/python 2.5 (r25:51908, Jul 19 2007, 09:13:48) [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] [root at M1 ~]# python -c "import sys; print sys.executable; print sys.version; set()" /usr/local/bin/python 2.3.4 (#1, May 2 2007, 19:26:00) [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] Traceback (most recent call last): File "", line 1, in ? NameError: name 'set' is not defined --------------------------------------------------------------------------------- On a different machine, with same setup (as far as I can tell), I get the expected results: --------------------------------------------------------------------------------- [root at M2 ~]# /usr/local/bin/python -c "import sys; print sys.executable; print sys.version; set()" /usr/local/bin/python 2.5 (r25:51908, Feb 8 2007, 16:29:18) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] [root at M2 ~]# env python -c "import sys; print sys.executable; print sys.version; set()" /usr/local/bin/python 2.5 (r25:51908, Feb 8 2007, 16:29:18) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] [root at M2 ~]# python -c "import sys; print sys.executable; print sys.version; set()" /usr/local/bin/python 2.5 (r25:51908, Feb 8 2007, 16:29:18) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] --------------------------------------------------------------------------------- Can anyone tell me what might be causing the erroneous behavior in the first example? Thanks, Jeffrey From steve at holdenweb.com Sun Jul 8 09:14:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 08 Jul 2007 09:14:43 -0400 Subject: Where is the syntax for the dict() constructor ?! In-Reply-To: <00bc01c7c13f$573770a0$03000080@hendrik> References: <468D1D9D.6060002@gmail.com><468D3445.2060408@gmail.com><1183675552.466967.136360@i13g2000prf.googlegroups.com><5f6fo1F3b25tsU1@mid.uni-berlin.de><5f8rrpF3c8qopU1@mid.uni-berlin.de> <1183853628.296224.107400@i13g2000prf.googlegroups.com> <00bc01c7c13f$573770a0$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "John Machin" wrote: > > 8<------------ nice explanation of quoting problems ------------- > >> (2) A field containing an odd number of " characters (or more >> generally, not meeting whatever quoting convention might be expected >> in the underlying data) should be treated with suspicion. > > How does one program to treat something with suspicion? > > My stuff tends to either accept or reject... > > This reminds me (for no discernible reason) of the word > "eschew", and of an illustration in a Goon author's book > of someone eschewing an architectural example with a > pocket sized eschewing instrument - a "pocket eschewer". > (He is shown peering at it through the eyepiece) > > Maybe such fields should be eschewed instead. > Would we do that with esteeth? 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 jeffober at gmail.com Wed Jul 25 20:30:45 2007 From: jeffober at gmail.com (Jeff) Date: Thu, 26 Jul 2007 00:30:45 -0000 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185402705.421724.3680@x35g2000prf.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <82d28c40707251158ibae2f9u70889f01ac45a9f6@mail.gmail.com> <1185402705.421724.3680@x35g2000prf.googlegroups.com> Message-ID: <1185409845.466642.146410@e9g2000prf.googlegroups.com> No programming language can fix bad programmers. And if cost is an issue, www.nearlyfreespeech.net has Python, clisp, and OCaml. From mail at timgolden.me.uk Wed Jul 4 06:35:38 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 04 Jul 2007 11:35:38 +0100 Subject: Which Python Version In-Reply-To: <00ac01c7be22$01202d80$03608880$@rawlins@thinkbluemedia.co.uk> References: <00ac01c7be22$01202d80$03608880$@rawlins@thinkbluemedia.co.uk> Message-ID: <468B77FA.3050907@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > Is there a command I can run to confirm which version of python I'm running? From outside Python: python -V (that's a capital V) From inside Python: import sys print sys.version (and a couple of more easily parseable alternatives; look at the sys module docs) TJG From danb_83 at yahoo.com Sun Jul 8 13:57:23 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Sun, 08 Jul 2007 10:57:23 -0700 Subject: Learning Basics In-Reply-To: <1183914604.792954.80260@c77g2000hse.googlegroups.com> References: <1183914604.792954.80260@c77g2000hse.googlegroups.com> Message-ID: <1183917443.740130.177730@o61g2000hsh.googlegroups.com> On Jul 8, 12:10 pm, Brad wrote: > So I've been studying python for a few months (it is my first foray > into computer programming) and decided to write my own little simple > journaling program. It's all pretty basic stuff but I decided that I'd > learn more from it if more experienced programmers could offer some > thoughts on how I could do things better. > > #simple little journal > > from time import asctime > myjournal=file('journal.txt','a+') > > formatter="*"*80+"\n" > todaysdate=asctime() > myjournal.write(formatter) > myjournal.write(todaysdate + "\n\n") > > loop="set" > > while loop!=':a': > loop=raw_input(':') > if loop!=':a': > myjournal.write(loop+"\n") > if loopz==':a': > myjournal.close() > > #end of stuff > > So I'd appreciate some good feedback or ideas. #!/usr/bin/env python """simple little journal""" import sys import time EXIT_COMMAND = ':a' HEADER = "*" * 80 def add_journal_entry(filename='journal.txt'): """ Prompt the user to enter text, and write it into the journal file. """ print "Enter your journal entry." print "When done, type %r." % EXIT_COMMAND journal_file = file(filename, 'a+') journal_file.write(HEADER + "\n") journal_file.write(time.asctime() + "\n\n") while True: line = raw_input(':') if line == EXIT_COMMAND: break journal_file.write(line + "\n") journal_file.close() def _main(argv=None): """Executed when file is run as a script.""" if argv is None: argv = sys.argv if len(argv) == 1: # No filename specified; use the default add_journal_entry() else: add_journal_entry(argv[1]) if __name__ == '__main__': _main() From steve at holdenweb.com Thu Jul 26 20:41:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Jul 2007 20:41:57 -0400 Subject: SQLObject 0.9.1 In-Reply-To: References: <20070726143614.GI30176@phd.pp.ru> Message-ID: Sherm Pendley wrote: > Steve Holden writes: > >> Sherm Pendley wrote: >>> Gerardo Herzig writes: >>> >>>> So..at 11:23 we got version 0.7.8...at 11:30 was version 0.8.5...now >>>> there is a 0.9.1 version?? Have a coffe dude >>> Sounds more to me like he needs to lay off the coffee, or at least switch >>> to decaffeinated for a while. :-) >>> >> Come on, give Oleg a break. He's maintaining three separate versions >> in parallel. > > What part of ":-)" did you not understand? > The part that completely bypassed my sense of humor, I guess. Feel free to ignore me until further notice :-) 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 jmoy.matecon at gmail.com Fri Jul 13 13:38:24 2007 From: jmoy.matecon at gmail.com (Jyotirmoy Bhattacharya) Date: Fri, 13 Jul 2007 17:38:24 -0000 Subject: Fast powerset function In-Reply-To: References: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> <7xodigr6xk.fsf@ruckus.brouhaha.com> <20070713120150.M89148@uniqsys.com> Message-ID: <1184348304.043233.241780@22g2000hsm.googlegroups.com> On Jul 13, 6:34 pm, Carsten Haese wrote: > def recursive_powerset(s): > if not s: yield set() > for x in s: > s2 = s - set([x]) > for subset in recursive_powerset(s2): > yield subset > yield subset.union(set([x])) > Your recursive_powerset is buggy--it generates too many sets. The loop over the elements of s is unnecessary. Here is one alternative: def recursive_powerset(s): def do_recursive(S): if not S: yield set([]) return x=set(S.pop()) for t in do_recursive(S): yield t yield t|x return do_recursive(s.copy()) From claird at lairds.us Wed Jul 18 17:20:51 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 18 Jul 2007 21:20:51 +0000 Subject: Python-URL! - weekly Python news and links (Jul 16) References: <1184623565.893149.254600@22g2000hsm.googlegroups.com> Message-ID: In article <1184623565.893149.254600 at 22g2000hsm.googlegroups.com>, Kay Schluehr wrote: > >Gabriel Genellina schrieb: >> QOTW: "That's a property of open source projects. Features nobody really >> needs are not implemented." - Gregor Horvath > >It's a good QOTW but social romantic nonsense nevertheless. > >Not sure if it's important enough to be mentioned in weekly Python >news but Europython 2007 actually happened and took place in Vilnius. > >Kay > *I* sure think it's important; is there a summary or narrative from the event you recommend? From twisted0n3 at gmail.com Thu Jul 12 22:09:48 2007 From: twisted0n3 at gmail.com (Twisted) Date: Fri, 13 Jul 2007 02:09:48 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <87myy1gqwk.fsf@catnip.gol.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373419.522607.14500@g4g2000hsf.googlegroups.com> <1182374902.920671.171900@k79g2000hse.googlegroups.com> <85ir9ifgtx.fsf@lola.goethe.zz> <1182376044.852820.261530@n2g2000hse.googlegroups.com> <87myy1gqwk.fsf@catnip.gol.com> Message-ID: <1184292588.754789.265720@22g2000hsm.googlegroups.com> On Jul 12, 7:10 pm, Miles Bader wrote: > Twisted writes: > > I won't dignify your insulting twaddle and random ad-hominem verbiage > > with any more responses after this one. Something with actual logical > > argumentation to rebut may be another matter of course. > > Er, why don't you just answer his question (what version)? He's asking > for actual information, which will help us understand what you are > (trying) to to say. > > If you continue to just make vague and unsupported (and rather hostile) > assertions, without examples, version numbers, or other concrete > information, do you expect anybody will continue listening to you? Some people can't let sleeping dogs lie I guess. I can't remember the specific version after all these years. It may have been 18 or 19 point something. As for "concrete information" this thread is littered with fairly specific anecdotes. I know, I know; anecdotes aren't really proof of anything. Got any better suggestions? HCI stuff is a bit slippery to try to hang a rigorous theory and quantitative facts upon. For most people, a crappy interface isn't something they can precisely define, but they know it when they see it (or at least try to use it). From escalation746 at yahoo.com Sun Jul 22 10:06:32 2007 From: escalation746 at yahoo.com (escalation746) Date: Sun, 22 Jul 2007 07:06:32 -0700 Subject: custom plugin architecture: how to see parent namespace? Message-ID: <1185113192.049692.258310@k79g2000hse.googlegroups.com> I've got a namespace query that amounts to this: How can an imported function see data in the parent custom namespace? I have read through numerous posts which skirt this issue without answering it. To illustrate, create plugin.py with a couple of functions. The second will obviously fail. ---- def Hello(): print 'hello' def ViewValuable(): print VALUABLE ---- Then create master.py which loads the plugin at runtime, later running various code fragments against it. ---- # location of plugin module filespec = '/path/to/plugins/plugin.py' filepath, filename = os.path.split(filespec) filename = os.path.splitext(filename)[0] # add to system path if filepath not in sys.path: sys.path.append(filepath) # import into our namespace space = __import__(filename, globals(), locals(), []) namespace = space.__dict__ # sometime later in the code... define a new function def _plus(): print 'plus' # add that to our namespace namespace.update({'Plus': _plus, 'VALUABLE': 'gold'}) # run custom code code = """ Hello() Plus() Valuable() """ exec code in namespace ---- This code will echo the lines: hello plus Followed by a traceback for: NameError: global name 'VALUABLE' is not defined The question is: How do I get a function in plugin.py to see VALUABLE? Using external storage of some sort is not viable since many different instances of plugin.py, all with different values of VALUABLE, might be running at once. (In fact VALUABLE is to be a key into a whole whack of data stored in a separate module space.) Extensive modifications to plugin.py is also not a viable approach, since that module will be created by users. Rather, I need to be able to pass something at execution time to make this happen. Or create an access function along the lines of _plus() that I can inject into the namespace. Any help, please? I've been losing sleep over this one. -- robin From jstroud at mbi.ucla.edu Thu Jul 12 19:27:48 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 12 Jul 2007 23:27:48 GMT Subject: Where does str class represent its data? In-Reply-To: <1184276470.733520.265990@n2g2000hse.googlegroups.com> References: <1184196082.903895.176020@n60g2000hse.googlegroups.com> <%Egli.5395$rL1.3818@newssvr19.news.prodigy.net> <1184276470.733520.265990@n2g2000hse.googlegroups.com> Message-ID: ChrisEdgemon at gmail.com wrote: > I guess I don't understand what benefits come from using > UserString instead of just str. I hit send without remembering to include this kind of example: from UserString import UserString as UserString class MyString(UserString): def __init__(self, astr): UserString.__init__(self, astr) self.history = [astr] self.fix_ms() def update(self): if self.history[-1] != self.data: self.history.append(self.data) def fix_ms(self): self.data = self.data.replace('m', 'f') self.update() def fix_whitespace(self): self.data = "".join(c if c not in string.whitespace else '-' for c in self.data.strip()) self.update() Now, you have a record of the history of the string, which may help you later py> s = MyString('mail man') py> s 'fail fan' py> s.data 'fail fan' py> s.history ['mail man','fail fan'] py> s.fix_whitespace() py> s 'fail-fan' py> s.history() ['mail man', 'fail fan', 'fail-fan'] A history of a str or instances or its subclasses make no sense because str is immutable. You may or may not want a history (I just made up this use case), but hopefully you see the utility in using regular classes for complex behavior instead of forcing an immutable built in type to do magic. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From rjh at see.sig.invalid Wed Jul 4 03:07:36 2007 From: rjh at see.sig.invalid (Richard Heathfield) Date: Wed, 04 Jul 2007 07:07:36 +0000 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> <7x645al8kc.fsf@ruckus.brouhaha.com> <1182894003.920335.317620@a26g2000pre.googlegroups.com> <7x7ipoy6cf.fsf@ruckus.brouhaha.com> <1183041149.275562.114490@o11g2000prd.googlegroups.com> <7xbqethpr8.fsf@ruckus.brouhaha.com> <468AD888.6A023A0E@yahoo.com> Message-ID: Peter J. Holzer said: > It is possible that the observatory at Greenwich still keeps and > announces GMT, but it has no practical importance anymore. Certainly > what everybody (except specialists in the field) means when they talk > about "GMT" is UTC. I am not a specialist in the field. When I talk about GMT, I mean GMT, not UTC. Therefore, I am a counter-example to your claim. -- Richard Heathfield Email: -www. +rjh@ Google users: "Usenet is a strange place" - dmr 29 July 1999 From evan at yelp.com Wed Jul 25 20:38:58 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 25 Jul 2007 17:38:58 -0700 Subject: python-fam documentation. In-Reply-To: <1185181629.147654.248420@r34g2000hsd.googlegroups.com> References: <1185181629.147654.248420@r34g2000hsd.googlegroups.com> Message-ID: On 7/23/07, Shriphani wrote: > Folks, > I am trying to create an app which stares at a file and when the file > is altered, the script joins a channel on freenode and reports that > the file has been altered. > I found a module called python-fam, unfortunately i have been unable > to find documentation for it. Can someone please help me ? > Thanks, > Shriphani Palakodety. If you're running a newish version of Linux; this module has fairly complete documentation. -- Evan Klitzke From vedrandekovic at v-programs.com Mon Jul 23 15:53:01 2007 From: vedrandekovic at v-programs.com (...:::JA:::...) Date: Mon, 23 Jul 2007 21:53:01 +0200 Subject: code indentation Message-ID: Hello, In my previously post I have been talk about running code with exec in...... So now I have problem with code indentation, as Gabriel Genellina says: >If you are using the tokenize module as suggested some time ago, try to >analyze the token sequence you get using { } (or perhaps begin/end pairs >in your own language, that are easier to distinguish from a dictionary >display) and the sequence you get from the "real" python code. Then write >a script to transform one into another: >from tokenize import generate_tokens > from token import tok_name >from cStringIO import StringIO >def analyze(source): > g = generate_tokens(StringIO(source).readline) > for toknum, tokval, _, _, _ in g: > print tok_name[toknum], repr(tokval) >I think you basically will have to ignore INDENT, DEDENT, and replace >NAME+"begin" with INDENT, NAME+"end" with DEDENT. So......how can I do this????????????? I will appreciate any help!!!!! Regards, Vedran __________________________________________________________________ Vedran veki ICQ#: 264412055 Current ICQ status: + More ways to contact me Get ICQ! __________________________________________________________________ From gagsl-py2 at yahoo.com.ar Tue Jul 10 20:54:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Jul 2007 21:54:15 -0300 Subject: Transfer folders to ftp References: <896312.73769.qm@web36715.mail.mud.yahoo.com> Message-ID: En Tue, 10 Jul 2007 05:44:09 -0300, Laurentiu escribi?: > i am new to python and i made some digging about how > to send files and folders to ftp server. Welcome! > i manage to send a file, but i don't know how to send > folders with subfolders in it. > > please, can someone help me to accomplish this tasks: > > 1. send a folder with subfolders to ftp server. Use os.walk to navigate thru the directory structure, creating new directories and uploading files as needed. > 2. make the program invisible... running hide That depends on the OS and how much invisibility you want. > 3. send only folder that is different to the host Most programs check file size, date and time to detect differences. It's easy if you transfer one-way only. > i know that this tasks can be easily accomplish with a > sync program, but i want to make this in python. Good luck! -- Gabriel Genellina From brycer22 at gmail.com Fri Jul 13 00:28:56 2007 From: brycer22 at gmail.com (bdude) Date: Thu, 12 Jul 2007 21:28:56 -0700 Subject: Most efficient way to evaluate the contents of a variable. Message-ID: <1184300936.115235.121980@g12g2000prg.googlegroups.com> Hey, I'm new to python and am looking for the most efficient way to see if the contents of a variable is equal to one of many options. Cheers, Bryce R From ptmcg at austin.rr.com Fri Jul 27 09:39:04 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 27 Jul 2007 06:39:04 -0700 Subject: pyparser and recursion problem In-Reply-To: <1185507613.143993.175840@19g2000hsx.googlegroups.com> References: <1185479408.520124.40670@k79g2000hse.googlegroups.com> <1185504855.745706.241590@d55g2000hsg.googlegroups.com> <1185507613.143993.175840@19g2000hsx.googlegroups.com> Message-ID: <1185543544.227131.158640@r34g2000hsd.googlegroups.com> On Jul 26, 10:40 pm, pyscottish... at hotmail.com wrote: > Hey, > > Thanks Neil and Paul! > > After reading Neil's advice I started playing around with the > setParseAction method, and then I found Paul's script > 'macroExpander.py' (http://pyparsing.wikispaces.com/space/showimage/ > macroExpander.py). > Great! I'm glad those examples are useful (I keep meaning to get them a little better organized.) Just one side note. macroExpander uses the Forward class in a non- traditional way. The Forward class is usually used to define a recursive grammar, like in this simple list grammar that defines a comma-separated list, with nested sublists enclosed in parentheses: listExpr = Forward() listItem = Word(alphanums) | Group( '(' + listExpr + ')' ) listExpr << delimitedList( listItem ) I need to use listExpr as part of the definition of listItem, but I need to use listItem to define listExpr. So I "forward declare" listExpr by calling it a Forward instance, then I "inject" the grammar contents using the shift '<<' operator when I have defined listItem. macroExpander is a little different. In this case, I'm using a Forward as a parse-time dynamic grammar element. A Forward is used as a placeholder for all previously seen macro names, beginning as an empty Forward (an empty Forward never matches). As new macro definitions are found, the placeholder content gets defined as a MatchFirst of all macro definitions that have been seen so far - sort of a self-modifying parser. This explains why you had to reverse the order of your example string when you adapted macroExpander to your example. Your original string referenced macros that hadn't been encountered yet, so the only way to handle that was to parse everything, and then recursively post-process the structure with a parse action on the top-level expression. (I tried a version using parse actions on the all-uppercase macro expression, and a dict of previously-seen references and placeholders in the cumulative ParseResults, but I couldn't get this working, so I went with the recursive post-process instead - much simpler and more straightforward.) Glad you worked out your question, hope to hear from you further in your pyparsing exploits. -- Paul From bbxx789_05ss at yahoo.com Sat Jul 28 18:09:59 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 28 Jul 2007 15:09:59 -0700 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1185658013.859359.47700@57g2000hsv.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> <1184458002.961657.267830@x35g2000prf.googlegroups.com> <1184466882.446791.127670@x35g2000prf.googlegroups.com> <1185658013.859359.47700@57g2000hsv.googlegroups.com> Message-ID: <1185660599.329035.193820@d55g2000hsg.googlegroups.com> I also get this: >>> import mod_python.psp Traceback (most recent call last): File "", line 1, in ? ImportError: No module named mod_python.psp >>> From byte8bits at gmail.com Wed Jul 18 16:09:55 2007 From: byte8bits at gmail.com (brad) Date: Wed, 18 Jul 2007 16:09:55 -0400 Subject: Deleting files and folders used by other processes on Windows In-Reply-To: <1184696481.970075.232530@m37g2000prh.googlegroups.com> References: <1184696481.970075.232530@m37g2000prh.googlegroups.com> Message-ID: tkondal at gmail.com wrote: > Hi, > > I have been looking into making my file cleaning script more > intelligent. The goal of the script is to delete everything on a > drive except for a couple of folders which are skipped by the script. > Recently, I noticed that some files where not being deleted because a > process was using them. Try this: try: # Make the file's attributes normal so file can be deleted. win32api.SetFileAttributes(os.path.join(root, f), win32con.FILE_ATTRIBUTE_NORMAL) # HKLM/SYSTEM/CurrentControlSet/Control/Session Manager/PendingFileRenameOperations win32api.MoveFileEx(os.path.join(root, f), None, win32con.MOVEFILE_DELAY_UNTIL_REBOOT) except Exception, e: print e Upon reboot the file will be gone... careful though, this canl delete any Windows system file too. From t-alexm at windows.microsoft.com Thu Jul 19 19:35:12 2007 From: t-alexm at windows.microsoft.com (Alex Mont) Date: Thu, 19 Jul 2007 16:35:12 -0700 Subject: Efficiently removing duplicate rows from a 2-dimensional Numeric array Message-ID: <76EEE12626B7A84EBACE67EC513AE53D060F8CE9@WIN-MSG-20.wingroup.windeploy.ntdev.microsoft.com> I have a 2-dimensional Numeric array with the shape (2,N) and I want to remove all duplicate rows from the array. For example if I start out with: [[1,2], [1,3], [1,2], [2,3]] I want to end up with [[1,2], [1,3], [2,3]]. (Order of the rows doesn't matter, although order of the two elements in each row does.) The problem is that I can't find any way of doing this that is efficient with large data sets (in the data set I am using, N > 1000000) The normal method of removing duplicates by putting the elements into a dictionary and then reading off the keys doesn't work directly because the keys - rows of Python arrays - aren't hashable. The best I have been able to do so far is: def remove_duplicates(x): d = {} for (a,b) in x: d[(a,b)] = (a,b) return array(x.values()) According to the profiler the loop takes about 7 seconds and the call to array() 10 seconds with N=1,700,000. Is there a faster way to do this using Numeric? -Alex Mont -------------- next part -------------- An HTML attachment was scrubbed... URL: From socialanxiety at gmail.com Sun Jul 8 22:18:00 2007 From: socialanxiety at gmail.com (socialanxiety at gmail.com) Date: Sun, 08 Jul 2007 19:18:00 -0700 Subject: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc) In-Reply-To: References: <1183939608.088756.178320@m37g2000prh.googlegroups.com> Message-ID: <1183947480.922943.8370@o11g2000prd.googlegroups.com> On Jul 8, 5:37 pm, Carsten Haese wrote: > On Sun, 2007-07-08 at 17:06 -0700, socialanxi... at gmail.com wrote: > > i hope someone here can help me. > > > basically, me and my friend have a summer project. > > > in this project, we need something that would basically function as a > > blender. we know we'll need to buy a motor that spins, but what we're > > having trouble with is figuring out how to program it. we want to be > > able to control the speed of the motor. how would we accomplish this? > > > i'm new to all of this, so i'm having a hard time wrapping my mind > > around how it'd be possible to program one of those things :\ > > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then > > turn the other direction. > > > would you program it the same way you would on a personal computer > > (via c, python, etc)? > > The answers to your questions depend very much on what you're working > with and how the motor is controlled. Is this supposed to be a > self-contained machine, or is it supposed to be connected to a personal > computer as a peripheral device? > > The easier way is the peripheral device. In that case, you need some way > of sending signals e.g. from your computer's parallel or serial port to > a relay switch or voltage controller that controls your motor. In that > case, apart from the nitty gritty hardware to make the physical > connections, it's a matter of controlling the parallel or serial port > that the "robot" is attached to, which can definitely be done in Python. > > I won't go into details because you're not saying enough about your > project constraints, and as fascinating as your question is, it is > somewhat off-topic on this list (as if that's a deterrent to discussing > something on this list ;-). As John said, you're more likely to receive > useful advice on comp.robotics.misc. > > Good luck, > > -- > Carsten Haesehttp://informixdb.sourceforge.net I would like the robot to be self contained. basically, I'd like to be able to program functions in python, ex: while True: motor.rotate(1) and have it repeat the same piece of code every time it's turned on. From nagle at animats.com Wed Jul 11 19:30:56 2007 From: nagle at animats.com (John Nagle) Date: Wed, 11 Jul 2007 16:30:56 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <5dveb4F360un0U1@mid.individual.net> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: Donn Cave wrote: > I've wondered if programmers might differ a lot in how much they > dread errors, or how they react to different kinds of errors. > For example, do you feel a pang of remorse when your program > dies with a traceback - I mean, what a horrible way to die? > Do you resent the compiler's reprimands about your code errors, > or nagging about warnings? Maybe the language implementation's > job has as much to do with working around our feelings as anything > else. That's worth thinking about. I've worked in big mainframe shops, where an operating system crash caused everything to suddenly freeze, red lights came on all over the building, and a klaxon sounded. I've worked for aerospace companies, where one speaks of "defects", not "bugs", and there are people around whose job involves getting in high performance aircraft and flying with the software written there. I've worked with car-sized robot vehicles, ones big enough to injure people. This gives one a stronger feeling about wanting to eliminate software defects early. John Nagle From semanticist at gmail.com Fri Jul 20 19:27:50 2007 From: semanticist at gmail.com (Miles) Date: Fri, 20 Jul 2007 19:27:50 -0400 Subject: Sorting dict keys In-Reply-To: References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> Message-ID: On 7/20/07, Alex Popescu wrote: > If you just want to iterate over your dict in an ordered manner than all > you have to do is: > > for k in my_dict.keys().sort(): > # rest of the code I think you meant sorted(my_dict.keys()), since, as you just pointed out, the sort() method returns None. > If you just want to keep a list of ordered keys you can probably do > something like: > > key_list = list(my_dict.keys()) > key_list.sort() Creating a copy with list() is unnecessary, as keys() already returns a copy. -Miles From moranar at gmail.com Mon Jul 9 04:30:44 2007 From: moranar at gmail.com (Adriano Varoli Piazza) Date: Mon, 09 Jul 2007 01:30:44 -0700 Subject: socket: connection reset by server before client gets response In-Reply-To: References: <1183819907.249945.239700@o11g2000prd.googlegroups.com> <1183900086.021428.83580@e9g2000prf.googlegroups.com> Message-ID: <1183969844.697022.298650@w3g2000hsg.googlegroups.com> Hendrik van Rooyen wrote: > Sometimes I think that all would be programmers should be > forced to write a "Hello World" to transmit out of a serial port > in assembler on hardware that carries no OS - just to teach > them about interrupts and time. > > I would require them to hand assemble the code too, to make > them appreciate what a compiler or an interpreter does. > > And if you fail the test, you get taken out and fed to the > sacred crocodiles. > > - Hendrik > > -- > For training with a bite, enrol now in Heavy Henry's > Wholesome Hackadamy for Precocious Programmers Gives a whole new meaning to chomp(), byte, nybble, and more :) I wholeheartedly endorse this effort. I'm sick of reading about students from WTF University (check thedailywtf.com if you don't know, but beware. There be dragons). -- Adriano Once bitten, one arm less to code snafus with. From cai.haibin at gmail.com Mon Jul 23 23:19:05 2007 From: cai.haibin at gmail.com (james_027) Date: Tue, 24 Jul 2007 03:19:05 -0000 Subject: classmethod & staticmethod Message-ID: <1185247145.678362.75150@i38g2000prf.googlegroups.com> hi, python's staticmethod is the equivalent of java staticmethod right? with classmethod, I can call the method without the need for creating an instance right? since the difference between the two is that classmethod receives the class itself as implicti first argument. From my understanding classmethod are for dealing with class attributes? Can somebody teach me the real use of classmethod & staticmethod? Thanks james From steve at holdenweb.com Sun Jul 15 12:06:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 15 Jul 2007 12:06:05 -0400 Subject: zipfile 2GB problems? In-Reply-To: <1184509541.717169.89920@d55g2000hsg.googlegroups.com> References: <1184474112.081258.111490@n60g2000hse.googlegroups.com> <1184509541.717169.89920@d55g2000hsg.googlegroups.com> Message-ID: Jim wrote: > On Jul 14, 10:35 pm, xamdam wrote: >> Hi fellas, >> I am experiencing problems reading a 2GB zipfile consisting of >> multiple zipped files. I found a threadhttp://mail.python.org/pipermail/python-dev/2005-April/053027.html >> that mentions a problem on the writing side, does such a problem exist >> on a reading side? I am using 2.4.1, perhaps there is a fix in a later >> version? > > Hi, > I use PKZIP V9.00 and maintain a 2.5GB zipfile that consists of over > 6,600 zipped files. > There is no problem with reading or writing. ... with reading or writing *using the Python libraries*? regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get 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 Mon Jul 16 14:05:34 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 16 Jul 2007 20:05:34 +0200 Subject: Discover instance variables References: <1184606748.599294.293570@n60g2000hse.googlegroups.com> Message-ID: <5g1qbdF3ccms7U1@mid.individual.net> JonathanB wrote: > Ok, I know there has to be a way to do this, but my google-fu > fails me (once more). I have a class with instance variables (or > should they be called attributes, I'm newish to programming and > get really confused with OO sometimes), To complete confusion, those terms vary with languages :) > like the one in this example: > > class Foo(): > self.a = "bar" > self.z = "test" > self.var = 2 This will not work. Please use working code for examples. > I can handle the formatting and changing the variable itself, no > problem, but how do I get a list of all the variables in a class > instance? I almost put a list in there called vars and appended > all the variables to it so I could iterate the list, but this > sounds like something useful enough that someone has come up with > a better way to do it than that. I'd use exactly this, since there may be attributes you don't want to be changed from outside (perhaps __class__). > It almost looks like self.__dir__() is what I want, but that > returns methods as well, correct? I only want variables, but I > can't think of how to do a list comprehension that would remove > the methods. That's quite a problem with your concept. There are no variables and methods. There are only attributes. Attributes may be objects. Some objects may be callable (like function objects). If you know exactly what you want to be accessible like this, you could filter __dir__() output with name/callable/isinstance tests. Regards, Bj?rn -- BOFH excuse #320: You've been infected by the Telescoping Hubble virus. From kw at codebykevin.com Thu Jul 26 08:01:08 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 26 Jul 2007 08:01:08 -0400 Subject: Tix.Tk() on Mac Intel In-Reply-To: References: Message-ID: <46A88D04.7070701@codebykevin.com> Alan wrote: > Hi List! > > I have I Macbook Pro Intel running OSX 10.4.10. > > I downloaded Python 2.5 and tried > TclTkAquaBI-8.4.10.0.dmg, but I got: > > Traceback (most recent call last): > File "", line 1, in > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py", > > line 210, in __init__ > self.tk.eval('package require Tix') > _tkinter.TclError: no suitable image found. Did find: > /Library/Tcl/Tix8.4/libTix8.4.dylib: mach-o, but wrong architecture > > Which make sense since tcltkaqua is released only for PPC. Googling a > bit, since tcltkaqua stopped development, I found they recommended > ActiveTcl, but Tix is not included in the package. > > So removing tcltkaqua and ActiveTcl, when trying Tix.Tk() I got: >>>> Tix.Tk() > Traceback (most recent call last): > File "", line 1, in > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py", > > line 210, in __init__ > self.tk.eval('package require Tix') > _tkinter.TclError: can't find package Tix > > The only way I got Tix.Tk() working so far was using Fink but I want > the nice aqua visual for python. Is there any way of getting it > working? > > I would appreciate any help here. > Many thanks in advance. > Cheers, > Alan You'll need to build Tix yourself from source, and Tix must be built in the same directory as the Tcl/Tk source tree (so you'll at least need to download and untar those source trees). -- Kevin Walzer Code by Kevin http://www.codebykevin.com From grflanagan at yahoo.co.uk Wed Jul 4 08:03:13 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Wed, 04 Jul 2007 05:03:13 -0700 Subject: Generator for k-permutations without repetition In-Reply-To: <1183548133.495759.191390@d30g2000prg.googlegroups.com> References: <1183548133.495759.191390@d30g2000prg.googlegroups.com> Message-ID: <1183550593.782246.140820@g4g2000hsf.googlegroups.com> On Jul 4, 1:22 pm, bullockbefriending bard wrote: > I was able to google a recipe for a k_permutations generator, such > that i can write: > > x = range(1, 4) # (say) > [combi for combi in k_permutations(x, 3)] => > > [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, > 3, 1], [1, 3, 2], [1, 3, 3], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2, > 1], [2, 2, 2], [2, 2, 3], [2, 3, 1], [2, 3, 2], [2, 3, 3], [3, 1, 1], > [3, 1, 2], [3, 1, 3], [3, 2, 1], [3, 2, 2], [3, 2, 3], [3, 3, 1], [3, > 3, 2], [3, 3, 3]] > > but what i really want is the above without repetition, i.e.: > > [combi for combi in k_permutations_without_repetitions(x, 3)] => > > [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] > See `kslice` function here: http://gflanagan.net/site/python/utils/sequtils/ Regards Gerard From zyzhu2000 at gmail.com Sat Jul 28 08:10:11 2007 From: zyzhu2000 at gmail.com (beginner) Date: Sat, 28 Jul 2007 05:10:11 -0700 Subject: Tkinter -- Show Data in an Excel like Read-Only Grid In-Reply-To: <1185595733.188575.275680@m37g2000prh.googlegroups.com> References: <1185573410.087935.146830@d30g2000prg.googlegroups.com> <1185595733.188575.275680@m37g2000prh.googlegroups.com> Message-ID: <1185624611.738269.292700@x35g2000prf.googlegroups.com> On Jul 27, 11:08 pm, Zentrader wrote: > On Jul 27, 2:56 pm, beginner wrote: > > > Hi All, > > > I am really new to Tk and Tkinter. I googled the web but it was not > > mentioned how to build a data grid with Tkinter. > > > Basically, I want to show an excel like data grid with fixed column > > and row headers and sortable columns. But the grids can be read-only. > > > Can anyone give some hint on implementing this? > > > Thanks, > > beginner > > See if tkTable will helphttp://tkinter.unpythonic.net/wiki/TkTable Thanks for your help. From vriolk at gmail.com Mon Jul 16 15:22:30 2007 From: vriolk at gmail.com (coldpizza) Date: Mon, 16 Jul 2007 19:22:30 -0000 Subject: sqlite3 db update extremely slow Message-ID: <1184613750.873464.312390@r34g2000hsd.googlegroups.com> I am trying to fill a sqlite3 database with records, and to this end I have written a class that creates the db, the table and adds rows to the table. The problem is that the updating process is *extremely* slow, and occasionally I get the message "database locked". I tried removing "self.con.commit()" in the add_record method, but then nothing is saved in the db. I don't know whether this has anything to do with it, but I have found no option to enable autocommit. This is the class that I am using: class sqliteDB(object): "Wrapper for SQLite methods" def __init__(self, db_file="sqlite3.db"): 'Intialize SQLite database, sqlite_db_init("db_file_name.db")' print 'SQLite db init: ', db_file self.con = sqlite3.connect(db_file) self.cur = self.con.cursor() def create_table(self, table): "create table (table_name)" query ='CREATE TABLE %s (hword VARCHAR(256) PRIMARY KEY, definition TEXT)' % table try: self.cur.execute(query) self.con.commit() except Exception, e: print e def add_record (self, table, headWord, definition): try: self.cur.execute('INSERT INTO ' + table + '(hword, definition) VALUES(?, ?)', (headWord, definition)) self.con.commit() except Exception, e: print e And this is the actual code that I use to write to the db file: db = sqliteDB() db.create_table("table_name") for k, v in myData: db.add_record(table, k,v) This works extremely slow (~10KB of data per second) and takes ages to complete even with small files. Where did I go wrong? Would it be faster (or possible) to import a text file to sqlite using something like the mysql's command LOAD DATA INFILE "myfile.csv"...? From edward.dodge at gmail.com Sat Jul 7 16:26:31 2007 From: edward.dodge at gmail.com (Edward Dodge) Date: Sat, 07 Jul 2007 13:26:31 -0700 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> Message-ID: Twisted writes: > Besides, ANY interface that involves fumbling around in the dark > trying to find a light switch is clunky. You should be able to see > what the hell you're doing and navigate easily. Applications that not > only eschew normal methods of navigation of the interface, but force > you to fumble your way between the help and the task you're trying to > do, are definitely clunky. An analogy to a genuine emacs experience: > you enter a workshop with some raw materials and tools. Unfortunately > there's no big ceiling lights so you can just flip the switch by the > door and then always be able to see where everything is. Instead > there's little lights here and there by various specific tools and > storage areas, and in one area a map of the place with switches to > control the lights. So -- what magical computer app illuminates the entire room and shows you how to use everything at the flip of a switch? This brilliant discovery would put Sam's, O'Reilly, the for-Dummies series, and virtually every other computer book publisher out of business in weeks. Naturally, this would include the publishers of books on "easy-to-use" Microsoft products. -- Edward Dodge From exarkun at divmod.com Mon Jul 9 09:13:20 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 9 Jul 2007 09:13:20 -0400 Subject: Per thread data In-Reply-To: <469230a0$0$5856$da0feed9@news.zen.co.uk> Message-ID: <20070709131320.4947.382271044.divmod.quotient.9426@ohm> On Mon, 09 Jul 2007 13:57:02 +0100, Will McGugan wrote: >Hi, > >Is there a canonical way of storing per-thread data in Python? > See threading.local: http://python.org/doc/lib/module-threading.html Jean-Paul From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 24 06:20:34 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 24 Jul 2007 12:20:34 +0200 Subject: Hacking with __new__ In-Reply-To: References: <1185241394.990936.206360@k79g2000hse.googlegroups.com> Message-ID: <46a5d26b$0$18658$426a74cc@news.free.fr> Duncan Booth a ?crit : (snip) > I think what you want for Bar is something more along the lines: (snip) > class Bar(Foo): > def __new__(cls, a, b, c, *args): > print 'Bar.__new__', len(args) > target = cls You don't use 'target' anywhere... > if not args: > cls = Zoo > obj = super(Bar, cls).__new__(cls, a, b, c, *args) > if args: > return obj > > obj.__init__(a, b, c, 7) IIRC, __new__ is supposed to return the newly created object - which you are not doing here. class Bar(Foo): def __new__(cls, a, b, c, *args): print 'Bar.__new__', len(args) if not args: cls = Zoo obj = super(Bar, cls).__new__(cls, a, b, c, *args) if not args: obj.__init__(a, b, c, 7) return obj From aisaac at american.edu Wed Jul 4 21:32:56 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 05 Jul 2007 01:32:56 GMT Subject: allow scripts to use .pth files? In-Reply-To: <1183483686.935115.285820@x35g2000prf.googlegroups.com> References: <1183483686.935115.285820@x35g2000prf.googlegroups.com> Message-ID: > On Jul 3, 7:35 am, Alan Isaac wrote: >>Suppose I have a directory `scripts`. >>I'd like the scripts to have access to a package >>that is not "installed", i.e., it is not on sys.path. >>On this list, various people have described a variety >>of tricks they use, but nobody has proposed a >>pretty way to allow this. >>I am therefore assuming there is not one. (?) >> >>How about allowing a `scripts.pth` file in such a `scripts` >>directory, to work like a path configuration file? >>(But to be used only when __name__=="__main__".) >>Drawbacks? half.italian at gmail.com wrote: > import sys > sys.path.append("../scripts") > import Module_from_scripts_dir That is not actually an answer to the question. In any case, path manipulation in scripts is often pronounced "not pretty". (And would also have to be done in every script file.) Cheers, Alan Isaac From wbrehaut at mcsnet.ca Mon Jul 16 13:16:32 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Mon, 16 Jul 2007 11:16:32 -0600 Subject: Can a low-level programmer learn OOP? References: <4697d9f0$0$7614$426a74cc@news.free.fr> <1184485640.495801.194200@z28g2000prd.googlegroups.com> <469b27dd$0$21672$426a74cc@news.free.fr> Message-ID: On Mon, 16 Jul 2007 10:10:05 +0200, Bruno Desthuilliers wrote: >Wayne Brehaut a ?crit : >(snip) > > after Bruno made the >> claim: "OO is about machines - at least as conceveid by Alan Key, who >> invented the term and most of the concept." > >Please reread more carefully the above. I do give credit to Smalltalk's >author for the *term* "OOP", and *most* (not *all*) of the concepts (I >strongly disagree with your opinion that message-passing is not a core >concept of OO). One problem is that it's often not clear what lists of properties are his definition of OOP vs. what are the intended properties of Smalltalk--his intended impelmentation of OOP. Many of the lists begin with the basic requirements that "everything is an object" and "objects communicate by message passing", but the most common "generally agreed upon" definition abstracts just four requirements from these (changing) lists--attempting to separate implementation details from what is essential to the underlying framework. As I note below, these were: 1. modularity (class-based? object-based?) 2. inheritance (sub-classing) 3. encapsulation (information hiding) 4. polymorphism ((sub-) class-specific response to a message, or processing of a method) Other details in Kay's lists are considered implementation details, and important advances or alternatives to pevious methods, but not required for a language to _be_ OO. It is reputed, though, that in 2003 Kay said (http://c2.com/cgi/wiki?AlanKaysDefinitionOfObjectOriented) "OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme LateBinding of all things." So I understand your accepting one of Kay's lists as being a definition of OOP instead of "just" a description of Smalltalk, or of accepting this fairly recent "definition" as being the true one (as opposed to the previous lists of usually 6 properties). "It's hard to hit a moving target!" >FWIW, I first mentionned Simula too (about the state-machine and >simulation aspect), then sniped this mention because I thought it was >getting a bit too much OT - we're not on comp.object here. Understood--sort of--but there is sufficient accurate information about Simula available on the web now that it's no longer necessary to use quotes from Kay about OOP and Smalltalk just because they're more accessible, as used to be the case. What would be so OT about referring to Simulain one sentence instead of or in addition to Smalltalk? But I digress--my only real objection to your post was your opinion and claim that Kay "invented the term and most of the concept": I've never seen anyone claim that anyone else invented the term, but for the claim that he invented "most of the concept" we need only refer to Nygaard's claim in "How Object-Oriented Programming Started" at http://heim.ifi.uio.no/~kristen/FORSKNINGSDOK_MAPPE/F_OO_start.html that "Simula 67 introduced most of the key concepts of object-oriented programming: both objects and classes, subclasses (usually referred to as inheritance) and virtual procedures, combined with safe referencing and mechanisms for bringing into a program collections of program structures described under a common class heading (prefixed blocks)." Combine this with the fact--as stated above by Bonnie MacBird (Alan Kay's significant other)--that "Alan Kay has always publicly credited Simula as the direct inspiration for Smalltalk, and... this implication of taking credit for the first OOP language is not true, it is a credit assigned to him by others, and one which he usually rights when confronted with it." If he acknowledges this perhaps others should too? As has been noted before, it's often the fact that a cause becomes a religion: true believers tend to take it over from the originator, and this religiosity tends to blind them from the facts. Opinions and rumours become facts, stories are invented, definitions are changed or twisted, and another religion is born! Even those who don't belong to the religion cpme to believe the oft-repreated stories, and then help spread and perpetuate them. (Continuing in my original humorous vein I was tempted to use terms like "religious zealots", "false gospel", "propaganda", etc., but thought better of it in case I was again misunderstood.) Again, I disagree only with this one claim. You make significant contributions to the group and to ellucidating Python and OOP to the great unwashed: in contrast, all I've done so far is complain about those who don't accept the correct (i.e., my) definition or use of terms. wwwayne From attn.steven.kuo at gmail.com Sun Jul 29 12:34:13 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Sun, 29 Jul 2007 09:34:13 -0700 Subject: Split a string based on change of character In-Reply-To: References: <1185687096.830640.319110@z28g2000prd.googlegroups.com> Message-ID: <1185726853.614521.159270@x35g2000prf.googlegroups.com> On Jul 28, 11:36 pm, Andrew Savige wrote: (snipped) > > Yes. Here's a simpler example without any backreferences: > > s = re.split(r'(?<=\d)(?=\D)', '1B2D3') > > That works in Perl but not in Python. > Is it that "chaining" assertions together like this is not supported in Python > re? > Or is that the case only in the split function? > The match objects returned by finditer return the expected span positions: >>> pat = re.compile(r'(?<=\d)(?=\D)') >>> s = '1B2D3' >>> for mobj in pat.finditer(s): ... print mobj.span() ... (1, 1) (3, 3) >From your original post: >>> pat = re.compile(r'(?<=(.))(?!\1)') >>> s = 'ABBBCC' >>> for mobj in pat.finditer(s): ... print mobj.span() ... (1, 1) (4, 4) (6, 6) So, it seems split doesn't split on what amounts to a zero-width assertion. I couldn't find this explanation from a quick look at the documentation, however. -- Hope this helps, Steven From vodela.sai at gmail.com Thu Jul 26 17:19:16 2007 From: vodela.sai at gmail.com (Rohan) Date: Thu, 26 Jul 2007 21:19:16 -0000 Subject: CSV Issue Message-ID: <1185484756.890736.10890@q75g2000hsh.googlegroups.com> I'm having a trouble consider this import csv f = open("/home/t/tp/va/some7.csv", "rb") reader =csv.reader(f) rows =[] for row in reader: rows.append(row) rows[1].append('1') print rows f = open("/home/t/tp/va/e7.csv", "ab") writer =csv.writer(f) writer.writerows(rows) f.close() In the file some7.csv there is already some data like this 1 2 3 4 Now i'm trying to add a '1' in row2 so that data can be like this 1 2,1 3 4 Instead i'm getting like this 1 2 3 4 1 2,1 3 4 can some one explain this and how to get it in the way i want it/ From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jul 10 07:32:49 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 10 Jul 2007 13:32:49 +0200 Subject: highly einteractive editor for python References: Message-ID: <5fh931F3crmfnU2@mid.individual.net> Atul Bhingarde wrote: > What I want to see is that it is possible to create a python based > application in a environment where I can see the results as I am > creating it, specifically gui widgets (from say TK). This will > provide a robust mechanism to see gui layout as well. Py is an IDE for Python/wxPython that, AFAICS, does what you look for. http://www.wxpython.org/py.php Regards, Bj?rn -- BOFH excuse #318: Your EMAIL is now being delivered by the USPS. From kimiraikkonen85 at gmail.com Thu Jul 5 05:28:19 2007 From: kimiraikkonen85 at gmail.com (kimiraikkonen) Date: Thu, 05 Jul 2007 02:28:19 -0700 Subject: The best platform and editor for Python In-Reply-To: References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> Message-ID: <1183627699.941481.92660@g4g2000hsf.googlegroups.com> Thanks for the links and replies, taking care. My another aim is: Can i develop graphical applications (like in Windows) which contain menus, interactive dialog boxes etc. using Ptyhon? I got it quite but not sure. I don't know Ptyhon's capability skills for creating interactive softwares like in Windows's created by C++ or Delphi. From ask at me Thu Jul 19 22:07:55 2007 From: ask at me (alf) Date: Thu, 19 Jul 2007 21:07:55 -0500 Subject: subprocess (spawned by os.system) inherits open TCP/UDP/IP port Message-ID: Hi, I need a help with explaining following behavior. Although it is not python issue per say, python helped me to write sample programs and originally I encountered the issue using python software. So let's assume we have two following programs: [myhost] ~> cat ss.py import socket UDPSock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) UDPSock.bind(("",12345)) import os os.system('python cc.py') [myhost] ~> cat cc.py import time time.sleep(2036) then I start master one, do ctrl-Z and bg. [myhost] ~> python ss.py Suspended [myhost] ~> bg [1] python ss.py & [myhost] ~> ps UID PID PPID C STIME TTY TIME CMD myuser00 3192 3189 0 14:57 pts/0 00:00:00 -tcsh myuser00 3247 3192 0 14:57 pts/0 00:00:00 python ss.py myuser00 3248 3247 0 14:57 pts/0 00:00:00 python cc.py [myhost] ~> netstat -uanp |grep 12345 (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) udp 0 0 0.0.0.0:12345 0.0.0.0:* 3247/python As expected netstat indicates process 3247 having port allocated. Then I kill the master process and interestingly the child inherits the port open. [myhost] ~> kill 3247 [myhost] ~> netstat -uanp | grep 12345 (Not all processes could be identified, non-owned process info will not be shown, you would have to be root to see it all.) udp 0 0 0.0.0.0:12345 0.0.0.0:* 3248/python [1] + Terminated python ss.py Why it is happening? I know that os.system uses fork, but still this is something unexpected. Thx, Alf From sjmachin at lexicon.net Sat Jul 7 09:27:00 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 07 Jul 2007 06:27:00 -0700 Subject: malloc error for newbie In-Reply-To: <1183791562.999601.83790@z28g2000prd.googlegroups.com> References: <1183791562.999601.83790@z28g2000prd.googlegroups.com> Message-ID: <1183814820.594726.301340@e9g2000prf.googlegroups.com> On Jul 7, 4:59 pm, David wrote: > Hi, > > Very new to python. When I uncomment the line > # self.im.putpalette(mkpalette()) Try to focus in on where the nasty is happening: p = mkpalette() # self.im.putpalette(p) > in the following code, I get the error: > > python $ ./mandelbrot.py > Python(2860) malloc: *** Deallocation of a pointer not malloced: > 0xff000000; This could be a double free(), or free() called with the > middle of an allocated block; Try setting environment variable > MallocHelp to see tools to help debug > > I don't have the expertise to get by this error. Can someone help? > > Thanks. > > #! /usr/local/bin/python > # Filename: mandelbrot.py > > import Image, ImagePalette Read the docs: http://effbot.org/imagingbook/imagepalette.htm They imply that len(palette) should be 769 (256*3) > > def mkpalette(): > global palette Nothing to do with your problem, but lose the above line, and examine carefully whatever induced you to include it. > palette = [0,0,0] > for i in range(256): > palette.extend([i*5%200+55,i*7%200+55,i*11%200+55]) > return palette So now len(palette) == 257*3 instead of 256*3; this may be your problem. HTH, John From steven at REMOVE.THIS.cybersource.com.au Wed Jul 11 01:20:33 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Jul 2007 05:20:33 GMT Subject: bool behavior in Python 3000? References: <7xodijdd8r.fsf@ruckus.brouhaha.com> Message-ID: On Tue, 10 Jul 2007 16:56:36 -0700, Paul Rubin wrote: > We had a huge discussion of this stuff when bools were introduced in > Python 2.3 or thereabouts. The current system is about the best way > that doesn't break everything in sight. But Python 3 is allowed to break backwards compatibility, so that's no longer a reason for keeping the current behaviour. > The weirdness is basically a > consequence of bools being an afterthought in Python. Python has a long > tradition of implicitly casting other values to bool, e.g. strings, > lists, sets etc. are all false if empty, etc. No, that's not true. How could Python cast objects to bool before bool existed? What Python has is much more powerful: the concept of Something versus Nothing. "x" and 4 and [23, "foo"] are all Something. "" and 0 and [] and None are all Nothing. No cast, whether implicit or explicit, is needed. What Python does is call the object's __nonzero__ method, if it has one, otherwise it checks to see if the object has a non-zero length (if it has a length), and otherwise the object is considered true. >From a purely functional perspective, bools are unnecessary in Python. I think of True and False as syntactic sugar. But they shouldn't be syntactic sugar for 1 and 0 any more than they should be syntactic sugar for {"x": "foo"} and {}. -- Steven. From nagle at animats.com Sun Jul 22 22:14:10 2007 From: nagle at animats.com (John Nagle) Date: Sun, 22 Jul 2007 19:14:10 -0700 Subject: URL parsing for the hard cases In-Reply-To: <1185138747.707836.69740@n2g2000hse.googlegroups.com> References: <1185138747.707836.69740@n2g2000hse.googlegroups.com> Message-ID: memracom at yahoo.com wrote: > Once you eliminate IPv6 addresses, parsing is simple. Is there a > colon? Then there is a port number. Does the left over have any > characters not in [0123456789.]? Then it is a name, not an IPv4 > address. > > --Michael Dillon > You wish. Hex input of IP addresses is allowed: http://0x525eedda and http://0x52.0x5e.0xed.0xda are both "Python.org". Or just put 0x52.0x5e.0xed.0xda into the address bar of a browser. All these work in Firefox on Windows and are recognized as valid IP addresses. On the other hand, 0x52.com is a valid domain name, in use by PairNIC. But http://test.0xda is handled by Firefox on Windows as a domain name. It doesn't resolve, but it's sent to DNS. So I think the question is whether every term between dots can be parsed as a decimal or hex number. If all terms can be parsed as a number, and there are no more than four of them, it's an IP address. Otherwise it's a domain name. There are phishing sites that pull stuff like this, and I'm parsing a long list of such sites. So I really do need to get the hard cases right. Is there any library function that correctly tests for an IP address vs. a domain name based on syntax, i.e. without looking it up in DNS? John Nagle From steve at REMOVE.THIS.cybersource.com.au Sat Jul 21 20:41:27 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 22 Jul 2007 10:41:27 +1000 Subject: problem with exec References: Message-ID: On Sat, 21 Jul 2007 16:31:38 -0400, Steve Holden wrote: > I'm afraid I don't understand this question. If you are talking about > the indentation of the code, if you don't want indentation you will have > to use braces - { and } - to indicate the nesting structure of your program. Oh my, teasing the n00bs like that is not nice. You know Python doesn't uses braces, it uses BEGIN ... END blocks. -- Steven. From carsten at uniqsys.com Fri Jul 20 16:38:21 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 20 Jul 2007 16:38:21 -0400 Subject: Pythonic way for missing dict keys In-Reply-To: References: <1184959878.3586.18.camel@dot.uniqsys.com> Message-ID: <1184963901.3586.29.camel@dot.uniqsys.com> On Fri, 2007-07-20 at 20:10 +0000, Alex Popescu wrote: > Carsten Haese wrote in > news:1184959878.3586.18.camel at dot.uniqsys.com: > > > On Fri, 2007-07-20 at 19:08 +0000, Alex Popescu wrote: > >> Hi all! > >> > > > > > [snip...] > > > > > > This is called "Look before you leap." Note that "if key in my_dict" > > is preferred over has_key(). > > > > Can you please detail why in is prefered over has_key? Is it about > readability/performance? Yes, it's about both readability and performance: [carsten at dot ~]$ python -m timeit -s "a={}" "a.has_key('foo')" 1000000 loops, best of 3: 0.601 usec per loop [carsten at dot ~]$ python -m timeit -s "a={}" "'foo' in a" 1000000 loops, best of 3: 0.307 usec per loop > Unfortunately, the get(key, None) suggestion is not 100% equivalent to > my posted code, and once I add the addition of the new object to the map > I think 1/ and 3/ are equivalent (if no other > readability/performance/etc is involved). Indeed, I missed that in 1/ and 2/ you're also adding the value to the dictionary. You could use setdefault instead of get: my_obj = my_dict.setdefault(key, myobject()) But if you want to defer creation of the default value until it's actually needed, you're better off with the "Look before you leap" approach. -- Carsten Haese http://informixdb.sourceforge.net From josiah.carlson at sbcglobal.net Sat Jul 7 13:40:54 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 07 Jul 2007 10:40:54 -0700 Subject: Getting the home directory in Python and a bug in os.path.expanduser In-Reply-To: References: Message-ID: <5aQji.1085$m%.196@newssvr17.news.prodigy.net> Edward Diener wrote: > What is the generic operating system way of getting the home directory ? > > I am guessing it is os.path.expanduser("~"). Is there a better way or an > alternate way ? > > If it is as I surmise, the aforementioned expanduser("~") of os.path > seems incorrect to me under Windows. The document says: > > "On Windows, only "~" is supported; it is replaced by the environment > variable HOME or by a combination of HOMEDRIVE and HOMEPATH." > > But HOME is never the home directory for Windows, only the combination > of HOMEDRIVE and HOMEPATH is valid, which is always set. If MSYS is > installed under Windows, where HOME must be set to the MSYS home > directory for a given user in order to emulate Linux/Unix, attempting to > use os.path.expanduser("~") will incorrectly return the MSYS home > directory for a given user rather than the Windows home directory for > the logged in user. So I think the os.path.expanduser("~") works > incorrectly in this case and needs to be fixed, else you are telling > users never to use MSYS under Windows. Some people have "sane" values for HOME on Windows. That's the only reason why it was included in expanduser(). The current trunk version of ntpath offers HOME, USERPROFILE or HOMEDRIVE+HOMEPATH, as well as the expansion of ~/extra/stuff . If you would like to get rid of Python's support of HOME, please post a bug report or feature request on the sourceforge tracker. - Josiah From tazmaster at rocketmail.com Thu Jul 19 21:29:31 2007 From: tazmaster at rocketmail.com (Jim Langston) Date: Thu, 19 Jul 2007 18:29:31 -0700 Subject: Python version changes, sys.executable does not References: <139v9oe22rihh40@corp.supernews.com> Message-ID: "Jeffrey Froman" wrote in message news:139v9oe22rihh40 at corp.supernews.com... > Hello All, > > I have two python versions installed, one in /usr/bin, and one in > /usr/local/bin. However, when invoking python without a full path, > I get the wrong executable with the right sys.executable string! > ---------------------------------------------------------------------------- > [root at M1 ~]# ls -l /usr/local/bin/python* > -rwxr-xr-x 2 root root 3783810 Jul 19 09:15 /usr/local/bin/python > -rwxr-xr-x 2 root root 3783810 Jul 19 09:15 /usr/local/bin/python2.5 > -rwxr-xr-x 1 root root 1281 Jul 19 09:16 > /usr/local/bin/python2.5-config > lrwxrwxrwx 1 root root 16 Jul 19 09:16 > /usr/local/bin/python-config -> python2.5-config > > [root at M1 ~]# ls -l /usr/bin/python* > -rwxr-xr-x 2 root root 5396 May 2 16:28 /usr/bin/python > lrwxrwxrwx 1 root root 6 Jul 18 12:20 /usr/bin/python2 -> python > -rwxr-xr-x 2 root root 5396 May 2 16:28 /usr/bin/python2.3 > > [root at M1 ~]# which python > /usr/local/bin/python > > [root at M1 ~]# /usr/local/bin/python -c "import sys; print sys.executable; > print sys.version; set()" > /usr/local/bin/python > 2.5 (r25:51908, Jul 19 2007, 09:13:48) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] > > [root at M1 ~]# env python -c "import sys; print sys.executable; print > sys.version; set()" > /usr/local/bin/python > 2.5 (r25:51908, Jul 19 2007, 09:13:48) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] > > [root at M1 ~]# python -c "import sys; print sys.executable; print > sys.version; set()" > /usr/local/bin/python > 2.3.4 (#1, May 2 2007, 19:26:00) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'set' is not defined > --------------------------------------------------------------------------------- > > > On a different machine, with same setup (as far as I can tell), I get the > expected > results: > --------------------------------------------------------------------------------- > [root at M2 ~]# /usr/local/bin/python -c "import sys; print sys.executable; > print sys.version; set()" > /usr/local/bin/python > 2.5 (r25:51908, Feb 8 2007, 16:29:18) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] > > [root at M2 ~]# env python -c "import sys; print sys.executable; print > sys.version; set()" > /usr/local/bin/python > 2.5 (r25:51908, Feb 8 2007, 16:29:18) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] > > [root at M2 ~]# python -c "import sys; print sys.executable; print > sys.version; set()" > /usr/local/bin/python > 2.5 (r25:51908, Feb 8 2007, 16:29:18) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] > --------------------------------------------------------------------------------- > > Can anyone tell me what might be causing the erroneous behavior in the > first example? er, of course I meant python2.3 before python2.5 From skpatel20 at gmail.com Wed Jul 18 08:23:46 2007 From: skpatel20 at gmail.com (Sanjay) Date: Wed, 18 Jul 2007 05:23:46 -0700 Subject: pytz giving incorrect offset and timezone In-Reply-To: <1184240636.179512.54590@o61g2000hsh.googlegroups.com> References: <1184233668.072963.264020@d55g2000hsg.googlegroups.com> <1184240636.179512.54590@o61g2000hsh.googlegroups.com> Message-ID: <1184761426.592867.130680@m37g2000prh.googlegroups.com> Hi Simon, localize worked perfectly. Thanks a lot for the vital help! Your elaboration on the concepts was also very nice and informative! thanks Sanjay From Xin.Zheng at jpl.nasa.gov Thu Jul 12 16:03:32 2007 From: Xin.Zheng at jpl.nasa.gov (Jason Zheng) Date: Thu, 12 Jul 2007 13:03:32 -0700 Subject: os.wait() losing child? In-Reply-To: References: <4694903B.8000105@cosc.canterbury.ac.nz> <87fy3tg5zn.fsf@mulj.homelinux.net> Message-ID: Nick Craig-Wood wrote: > Sure! > > You could get rid of this by sleeping until a SIGCHLD arrived maybe. Yah, I could also just dump Popen class and use fork(). But then what's the point of having an abstraction layer any more? >> This can still be a problem for applications that call wait in a >> dedicated thread, but the program can always ignore the processes >> it doesn't know anything about. > > Ignoring them isn't good enough because it means that the bit of code > which was waiting for that process to die with os.getpid() will never > get called, causing a deadlock in that bit of code. > Are you talking about something like os.waitpid(os.getpid())? If the process has completed and de-zombified by another os.wait() call, I thought it would just throw an exception; it won't cause a deadlock by hanging the process. ~Jason From steven at REMOVE.THIS.cybersource.com.au Wed Jul 11 01:42:51 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Jul 2007 05:42:51 GMT Subject: pattern match ! References: <1184125206.034047.175340@n60g2000hse.googlegroups.com> Message-ID: On Wed, 11 Jul 2007 03:40:06 +0000, hari.siri74 wrote: > Extract the application name with version from an RPM string like > hpsmh-1.1.1.2-0-RHEL3-Linux.RPM, i require to extract hpsmh-1.1.1.2-0 > from above string. Sometimes the RPM string may be hpsmh-1.1.1.2-RHEL3- > Linux.RPM. Thank you for sharing. The answer to your problem is here: http://tinyurl.com/anel -- Steven. From Solon.Lee at spirent.com Wed Jul 11 09:26:06 2007 From: Solon.Lee at spirent.com (Lee, Solon) Date: Wed, 11 Jul 2007 09:26:06 -0400 Subject: Python and Test Director Message-ID: <3027F8ACF1DDC8429BBC0C305358DDD87BF263@spcrokexcbe01.AD.SPIRENTCOM.COM> Hello, Can anyone tell me how to drive python test script via Test Director?? I am doing a project to translate Procomm script to python which is doable, but the purpose is so that the new .py scripts can be driven via Test Director. I am trying to research how to do it before this translation will be started. Either advice me with steps if you ever did or refer me to some materials I can read, thanks. PS: I heard (true or not) Test Director can run only python 2.2 or below, if that's the case what to do since I am running 2.4. Can I use WinRunner in between (Test Director and python) though I don't know how to do it either? Thanks again !! Solon Lee
    E-mail confidentiality. -------------------------------- This e-mail contains confidential and / or privileged information belonging to Spirent Communications plc, its affiliates and / or subsidiaries. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution and / or the taking of any action based upon reliance on the contents of this transmission is strictly forbidden. If you have received this message in error please notify the sender by return e-mail and delete it from your system. If you require assistance, please contact our IT department at helpdesk at spirent.com. Spirent Communications plc, Spirent House, Crawley Business Quarter, Fleming Way, Crawley, West Sussex, RH10 9QL, United Kingdom. Tel No. +44 (0) 1293 767676 Fax No. +44 (0) 1293 767677 Registered in England Number 470893 Registered at Spirent House, Crawley Business Quarter, Fleming Way, Crawley, West Sussex, RH10 9QL, United Kingdom Or if within the US, Spirent Communications, 26750 Agoura Road, Calabasas, CA, 91302, USA. Tel No. 1-818-676- 2300
    -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim.arnold at sas.com Fri Jul 27 11:53:37 2007 From: tim.arnold at sas.com (Tim Arnold) Date: Fri, 27 Jul 2007 11:53:37 -0400 Subject: encode/decode misunderstanding References: Message-ID: > If I read in the latin1 file using > codecs.open(filename,encoding='latin1') and write out the utf8 file by > opening with > codecs.open(othername,encoding='utf8'), would I no longer have a > problem -- I could just read in latin1 and write out utf8 with no more > worries about encoding? > > thanks, Replying to my own post, I feel so lonely! I guess that silence means I *am* thinking correctly about the encoding/decoding stuff; I'll keep heading in this direction unless someone out there sees it differently..... --Tim From jeff at jmcneil.net Wed Jul 25 15:37:45 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 25 Jul 2007 15:37:45 -0400 Subject: is_iterable function. In-Reply-To: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> Message-ID: <82d28c40707251237i313a39c8se4d97dd5d9d3eae4@mail.gmail.com> That's not going to hold true for generator functions or iterators that are implemented on sequences without '__iter__.' You might also want to check for __getitem__. I'm not sure if there's a way to tell if a function is a generator without actually calling it. -Jeff On 7/25/07, danmcleran at yahoo.com wrote: > You can use the built-in dir() function to determine whether or not > the __iter__ method exists: > > class Iterable(object): > def __iter__(self): > pass > > class NotIterable(object): > pass > > def is_iterable(thing): > return '__iter__' in dir(thing) > > print 'list is iterable = ', is_iterable(list()) > print 'int is iterable = ', is_iterable(10) > print 'float is iterable = ', is_iterable(1.2) > print 'dict is iterable = ', is_iterable(dict()) > print 'Iterable is iterable = ', is_iterable(Iterable()) > print 'NotIterable is iterable = ', is_iterable(NotIterable()) > > Results: > list is iterable = True > int is iterable = False > float is iterable = False > dict is iterable = True > Iterable is iterable = True > NotIterable is iterable = False > > On Jul 25, 12:24 pm, Neil Cerutti wrote: > > def is_iterable(obj): > > try: > > iter(obj) > > return True > > except TypeError: > > return False > > > > Is there a better way? > > > > -- > > Neil Cerutti > > > -- > http://mail.python.org/mailman/listinfo/python-list > From adecchi at gmail.com Wed Jul 4 12:32:43 2007 From: adecchi at gmail.com (Alejandro Decchi) Date: Wed, 4 Jul 2007 13:32:43 -0300 Subject: Help search files In-Reply-To: References: Message-ID: Hello Someone can help me how to search file in a directory. I need to do a form where the user write the word to search and if the file was found the user must could download the file making click in the link Sorry my english thz Alex -------------- next part -------------- An HTML attachment was scrubbed... URL: From vvikram at gmail.com Sun Jul 8 05:59:29 2007 From: vvikram at gmail.com (vvikram at gmail.com) Date: Sun, 08 Jul 2007 09:59:29 -0000 Subject: optparse commandline Message-ID: <1183888769.130421.245250@x35g2000prf.googlegroups.com> I want to call some function from my program and just pass it a commandline. It should parse the commandline and return back a list of parsed arguments (just like the sys.argv list) Example: foo.parse_cmdline("/usr/bin/foorun -v -d -h") ==> ['/usr/bin/foorun', '-v', '-d','-h'] Any suggestions on how to do this are appreciated. Regards Vikram From squabbit8 at gmail.com Mon Jul 2 23:29:25 2007 From: squabbit8 at gmail.com (felix seltzer) Date: Mon, 2 Jul 2007 21:29:25 -0600 Subject: good matlab interface In-Reply-To: <09ADD5BE-19EF-47E5-BD9A-BFEF16973ED2@bryant.edu> References: <09ADD5BE-19EF-47E5-BD9A-BFEF16973ED2@bryant.edu> Message-ID: my problems where more with scipy, which i needed for pymat. scipy gives two import errors (but still imports), and then pymat cant find the libraries that scipy provides. ohwell... i think i can just modify it to work with numpy untill i can sort out the errors. thanks, -felix On 7/2/07, Brian Blais wrote: > > On Jun 30, 2007, at 2:31 AM, felix seltzer wrote: > > > Does any one know of a good matlab interface? > > I would just use scipy or numpy, but i also need to use > > the matlab neural network functions. I have tried PyMat, but am > > having > > a hard time getting it to install correctly. > > > > What problems are you having installing? I had one problem with the > terrible matlab license server, which I had to solve by making site- > packages world writable, installing pymat as a user, and then > removing the world writable flag. Root just didn't have access to > matlab on my machine. :P > > > > bb > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jul 9 14:02:16 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 09 Jul 2007 20:02:16 +0200 Subject: What is the most efficient way to test for False in a list? References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <7x7ipajvst.fsf@ruckus.brouhaha.com> <5fejp2F3cp3igU1@mid.individual.net> <5feju0F3c7pd1U1@mid.uni-berlin.de> <5ff2ruF3cpan3U1@mid.individual.net> <7xk5t9egbq.fsf@ruckus.brouhaha.com> Message-ID: <5ffbh8F3b1ie7U2@mid.individual.net> Paul Rubin wrote: > Bjoern Schliessmann > writes: >> That's an identity test for True, not for False (the latter was >> requested). Thus, I'm not mistaken. > > No, "true" is not the same thing as "True". Oops, read over that case. Still: No identity test for False. Regards, Bj?rn -- BOFH excuse #145: Flat tire on station wagon with tapes. ("Never underestimate the bandwidth of a station wagon full of tapes hurling down the highway" Andrew S. Tannenbaum) From no at no.no Fri Jul 13 13:57:28 2007 From: no at no.no (Daniel) Date: Fri, 13 Jul 2007 20:57:28 +0300 Subject: NoneType object not iterable References: Message-ID: On Fri, 13 Jul 2007 20:44:13 +0300, wrote: > > Hi! > My code is > > > db = {} > > >> def display(): >> keyList = db.keys() >> sortedList = keyList.sort() >> for name in sortedList: >> line = 'Name: %s, Number: %s' % (name, db[name]) >> print line.replace('\r', '') > > And it gives following error: > >> for name in sortedList: >> TypeError: 'NoneType' object is not iterable > > How can sortedList variable turn into NoneType? I just don't get it... db is out of scope, you have to pass it to the function: >> def display(db): >> keyList = db.keys() >> sortedList = keyList.sort() >> for name in sortedList: >> line = 'Name: %s, Number: %s' % (name, db[name]) >> print line.replace('\r', '') -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From siona at chiark.greenend.org.uk Fri Jul 20 09:00:06 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 20 Jul 2007 14:00:06 +0100 (BST) Subject: Pickled objects over the network References: Message-ID: Rustom Mody wrote: >Since pickle has problems >-- does not interface well with networking In what way does pickle not interface well with networking? Other than, possibly, security issues which you list as a separate problem with it. I've taken a working XML-RPC system and replaced the XML with pickle, and had no issues. Other than an order of magnitude performance gain. (OK, a cow-orker allegedly and unreproducibly found that cPickle was leaking memory, and as the performance gains weren't so great with the pure Python implementation, it got shelved and we stuck with XML-RPC.) -- \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 raims at dot.com Tue Jul 31 06:03:10 2007 From: raims at dot.com (Lawrence Oluyede) Date: Tue, 31 Jul 2007 12:03:10 +0200 Subject: simple string backspace question References: <1185875052.153091.23300@19g2000hsx.googlegroups.com> <1185876068.755101.316320@b79g2000hse.googlegroups.com> Message-ID: <1i246s3.vl3okdq1tdw2N%raims@dot.com> wrote: > If you mean on operating system then unfortunately Windows XP. I don't know for sure but maybe it doesn't support all ASCII escapes codes. Why do you care about \b anyway :-) ? -- 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 detlev at die-offenbachs.de Sat Jul 21 05:21:02 2007 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 21 Jul 2007 11:21:02 +0200 Subject: ANN: eric 4.0.1 release Message-ID: Hi, I would like to announce the immediate availability of eric 4.0.1. This is a bug fix release. As usual it is available via http://www.die-offenbachs.de/eric/index.html Just follow the eric4 download link. What is eric ------------ eric is a Python IDE with all batteries included. For details see the a.m. link. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From gilbert.fine at gmail.com Mon Jul 30 12:48:39 2007 From: gilbert.fine at gmail.com (Gilbert Fine) Date: Mon, 30 Jul 2007 09:48:39 -0700 Subject: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why? In-Reply-To: References: <1185791793.141118.44080@x35g2000prf.googlegroups.com> <5h5ufoF3hmufcU4@mid.uni-berlin.de> Message-ID: <1185814119.604341.204100@z28g2000prd.googlegroups.com> Thanks. I think I have some direction to do logging, to get more information about this problem. It seems that I don't get used to dynamic language yet. -- Gilbert On Jul 30, 7:20 pm, Duncan Booth wrote: > Marc 'BlackJack' Rintsch wrote: > > > On Mon, 30 Jul 2007 03:36:33 -0700, Gilbert Fine wrote: > > >> This is a very strange exception raised from somewhere in our > >> program. I have no idea how this happen. And don't know how to > >> reproduce. It just occurs from time to time. > > > Maybe different `Decimal`\s? Here's how to reproduce such a > > traceback: > > > > Or even just one Decimal type but not one which supports subtraction: > > >>> class Decimal(object): > > pass > > >>> a = Decimal() > >>> b = Decimal() > >>> a-b > > Traceback (most recent call last): > File "", line 1, in > a-b > TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal' > > Another option of course is that Decimal() did support substraction but > someone deleted it: > > >>> from decimal import Decimal > >>> del Decimal.__sub__ > >>> Decimal()-Decimal() > > Traceback (most recent call last): > File "", line 1, in > Decimal()-Decimal() > TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal' From jm.suresh at gmail.com Tue Jul 3 06:06:13 2007 From: jm.suresh at gmail.com (jm.suresh@no.spam.gmail.com) Date: Tue, 03 Jul 2007 10:06:13 -0000 Subject: Freeze and problem with shared libraries Message-ID: <1183457173.919384.74780@a26g2000pre.googlegroups.com> I am trying to use freeze to create a single binary executable for one of my program. When I run freeze, it runs fine with the following modules. These modules are available in the dyn-load directory and I can import them from the python interpreter. Warning: unknown modules remain: _bisect _heapq _locale _random _socket Make also runs fine, but when I run the program on another machine, it compiles saying could not import these modules. Any idea how to get this working... Or can I have a directory of shared libs in a directory and do, import imp imp.load_dynamic() This will not be as good as having a single binary file, but will work I guess... Thanks. - Suresh From duncan.booth at invalid.invalid Tue Jul 24 15:00:59 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Jul 2007 19:00:59 GMT Subject: Hacking with __new__ References: <1185241394.990936.206360@k79g2000hse.googlegroups.com> <46a5d26b$0$18658$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Duncan Booth a ?crit : > (snip) >> I think what you want for Bar is something more along the lines: > > (snip) > >> class Bar(Foo): >> def __new__(cls, a, b, c, *args): >> print 'Bar.__new__', len(args) >> target = cls > You don't use 'target' anywhere... > >> if not args: >> cls = Zoo >> obj = super(Bar, cls).__new__(cls, a, b, c, *args) >> if args: >> return obj >> >> obj.__init__(a, b, c, 7) > > IIRC, __new__ is supposed to return the newly created object - which you > are not doing here. > Yup. I committed that cardinal sin of checking the code and then tidying it up by hand but not checking the tidied version. :( From http Thu Jul 26 17:18:54 2007 From: http (Paul Rubin) Date: 26 Jul 2007 14:18:54 -0700 Subject: Why PHP is so much more popular for web-development References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> <13ahh6kosqqeba1@corp.supernews.com> <7xlkd3m1si.fsf@ruckus.brouhaha.com> <7xhcnq7vye.fsf@ruckus.brouhaha.com> Message-ID: <7xzm1ihni9.fsf@ruckus.brouhaha.com> "Chris Mellon" writes: > Would you make this directory name be the username+the password? If > not, why not? The answer is the same reason why this isn't a reliable > method of security. I would not store plaintext passwords in a database, but that doesn't mean it's security by obscurity to do so. From gagsl-py2 at yahoo.com.ar Tue Jul 24 21:45:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Jul 2007 22:45:51 -0300 Subject: datetime.time() class - How to pass it a time string? References: <1185297087.998644.53940@r34g2000hsd.googlegroups.com> Message-ID: En Tue, 24 Jul 2007 14:37:20 -0300, Miles escribi?: > On 7/24/07, Robert Dailey wrote: >> I have a string in the following format: >> >> "00:00:25.886411" >> >> I would like to pass this string into the datetime.time() class and >> have it parse the string and use the values. However, the __init__() >> method only takes integers (which means I'd be forced to parse the >> string myself). Does anyone know of a way I can make it use the >> string? Thanks. > > timestr = "00:00:25.886411" > timesep = re.compile('[:.]') > datetime.time(*[int(i) for i in timesep.split(timestr)]) That's OK if one can always guarantee the 6 digits after the decimal point; else a bit more work is required: py> timestr = "00:00:25.886" py> h, m, s = timestr.split(":") py> if '.' in s: ... s, us = s.split('.') ... us = us[:6].ljust(6, '0') ... else: ... us = 0 ... py> datetime.time(int(h), int(m), int(s), int(us)) datetime.time(0, 0, 25, 886000) -- Gabriel Genellina From exarkun at divmod.com Fri Jul 20 07:03:27 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 20 Jul 2007 07:03:27 -0400 Subject: Pickled objects over the network In-Reply-To: <011401c7caa0$3e3e5900$03000080@hendrik> Message-ID: <20070720110327.4947.1283584382.divmod.quotient.13762@ohm> On Fri, 20 Jul 2007 09:32:17 +0200, Hendrik van Rooyen wrote: > Walker Lindley wrote: > >>Right, I could use Pyro, but I don't need RPC, I just wanted an easy way to >send objects across the network. I'm sure >both Pyro and Yami can do that and I >may end up using one of them. For the initial version pickle will work because >we >have the networking issues figured out with it, just not the security >problem. So we may end up just sending strings back >and forth that will let us >fill out an object's member variables on the other end. It's much less cool, but >it seems like it'd >be more secure. >> > >This passing of a pickled structure is so handy for simple things like lists of >parameters, and so on, that I wonder if it would not be worth while to somehow >beef up the security of the pickle stuff. > >One heretical way I can think of would involve strict "typing" at the receiving >end - if you expect say a dict, then you should somehow specify that anything >else should fail... > >as dict my_received_dict = cpickle.loads(data_from_network) > >or, better without a new "as" keyword: > >my_received_dict=cpickle.loads(data_from_network,type=dict) > >Is this at all feasible? No. You could write a replacement for pickle, though. Oh, wait... Jean-Paul From software at ginstrom.com Tue Jul 31 20:43:05 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Wed, 1 Aug 2007 09:43:05 +0900 Subject: Utilizing a raw IDispatch Pointer from Python In-Reply-To: References: Message-ID: <01eb01c7d3d4$eca803f0$020ba8c0@MOUSE> > On Behalf Of Brad Johnson > I would like to give the Python interpreter access to these > interfaces that were created in C++ land. > > Stated another way, how can I have Python consume a IDispatch > pointer from C++ and wrap it with one of those nice Python > classes automatically? If I understand you correctly, you can use client.Dispatch from win32com import client com_object = client.Dispatch(idispatch_pointer_from_cpp) Regards, Ryan Ginstrom From hjp-usenet2 at hjp.at Tue Jul 3 09:47:53 2007 From: hjp-usenet2 at hjp.at (Peter J. Holzer) Date: Tue, 3 Jul 2007 15:47:53 +0200 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> <7x645al8kc.fsf@ruckus.brouhaha.com> <1182894003.920335.317620@a26g2000pre.googlegroups.com> <7x7ipoy6cf.fsf@ruckus.brouhaha.com> <1183041149.275562.114490@o11g2000prd.googlegroups.com> <7xbqethpr8.fsf@ruckus.brouhaha.com> Message-ID: On 2007-07-03 08:57, Richard Heathfield wrote: > Paul Rubin said: >> sla29970 at gmail.com writes: >>> As for the primacy of UTC vs. TAI, this is the classical chicken and >>> egg problem. The bureaucratic reality is opposed to the physical >>> reality. >> >> Well, if you're trying to pick just one timestamp standard, I'd say >> you're better off using a worldwide one rather than a national one, no >> matter how the bureaucracies work. > > In that case, the obvious choice is Greenwich Mean Time. :-) Hardly. That hasn't been in use for over 35 years (according to Wikipedia). > Seriously, GMT is recognised all over the world (far more so, in fact, > than UTC, which tends to be recognised only by some well-educated > people, and there are precious few of those), so why not use it? While the layman may recognize the term "GMT", he almost certainly means "UTC" when he's talking about GMT. GMT was based on astronomical observations and the be best approximation available today is probably UT1, which may differ from UTC by up to 0.5 seconds. > I always leave my PC's clock set to GMT, Your PC is directly linked to an observatory? Impressive :-). If you synchronize your PC to any external time source, it's almost certainly UTC, not GMT or UT1. If you don't synchronize it it's so far off that it doesn't matter. hp -- _ | Peter J. Holzer | I know I'd be respectful of a pirate |_|_) | Sysadmin WSR | with an emu on his shoulder. | | | hjp at hjp.at | __/ | http://www.hjp.at/ | -- Sam in "Freefall" From tjreedy at udel.edu Mon Jul 23 13:07:57 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Jul 2007 13:07:57 -0400 Subject: Need Help with base64 References: <1185193741.420611.302290@z28g2000prd.googlegroups.com> Message-ID: "pycraze" wrote in message news:1185193741.420611.302290 at z28g2000prd.googlegroups.com... | Hi , | | I am currently trying to implement base64 encoding and decoding | scheme in C . Python has a module , base64 , that will do the | encoding and decoding with ease . I am aware of OpenSSL having support | for base64 encoding and decoding , but i will have to now implement | both in C without using the openssl libraries . | | I was able to download a code w.r.t. base 64 encoding and | decoding . I am attaching the code below . [C coce snipped] | But this code gives different hex values as compared to the | python base64.encodestring and base64.decodestring respectively . | | I need some help on this matter . I need some pointers on | where is the mistake for the above file . Looking at the source code for those functions might tell you why you get different outputs. The python code for base64 is in /Lib. Those two functions are thin wrappers around corresponding C-coded binascii functions. You can access that module via this source tree directory: http://svn.python.org/view/python/trunk/Modules/ The current binascii code is http://svn.python.org/view/python/trunk/Modules/binascii.c?rev=55205&view=auto The interpreter is open source with a liberal license that should allow you to pluck the functions for use elsewhere as long as the add a copyright notice. Otherwise, I agree with Diez that this is OT here. tjr From hjenea at earthlink.net Tue Jul 3 12:44:53 2007 From: hjenea at earthlink.net (Horace Enea) Date: Tue, 03 Jul 2007 09:44:53 -0700 Subject: PyObjC and Xcode Message-ID: I'm trying to use Python on a Mac running OSX 10.4.9. I installed Python 2.5 along with Idle. My problem is that Xcode no longer works with PyObjC. It gives an error message: ImportError: No module named PyObjCTools. I've down-loaded PyObjC and re-installed it along with PyObjCTools, but still get the same error from Xcode. Any suggestions? Thanks. From carsten at uniqsys.com Wed Jul 25 15:47:50 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 25 Jul 2007 15:47:50 -0400 Subject: is_iterable function. In-Reply-To: <5uNpi.36822$G23.3430@newsreading01.news.tds.net> References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> <5uNpi.36822$G23.3430@newsreading01.news.tds.net> Message-ID: <1185392870.4432.62.camel@dot.uniqsys.com> On Wed, 2007-07-25 at 19:26 +0000, Neil Cerutti wrote: > Speaking of the iter builtin function, is there an example of the > use of the optional sentinel object somewhere I could see? Example 1: If you use a DB-API module that doesn't support direct cursor iteration with "for row in cursor", you can simulate it this way: for row in iter(cursor.fetchone, None): # do something Example 2: Reading a web page in chunks of 8kB: f = urllib.urlopen(url) for chunk in iter(lambda:f.read(8192), ""): # do something HTH, -- Carsten Haese http://informixdb.sourceforge.net From doug at alum.mit.edu Thu Jul 5 17:12:22 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Thu, 05 Jul 2007 17:12:22 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <9uRhi.17027$xk5.14289@edtnps82> Message-ID: "Chris Mellon" writes: >> Some people here have been arguing that all code should use "with" to >> ensure that the files are closed. But this still wouldn't solve the >> problem of the large data structures being left around for an >> arbitrary amount of time. > I don't think anyone has suggested that. Let me be clear about *my* > position: When you need to ensure that a file has been closed by a > certain time, you need to be explicit about it. When you don't care, > just that it will be closed "soonish" then relying on normal object > lifetime calls is sufficient. This is true regardless of whether > object lifetimes are handled via refcount or via "true" garbage > collection. But it's *not* true at all when relying only on a "true GC"! Your program could easily run out of file descriptors if you only have a real garbage collector and code this way (and are opening lots of files). This is why destructors are useless in Java -- you can't rely on them *ever* being called. In Python, however, destructors are quite useful due to the refcounter. > Relying on the specific semantics of refcounting to give > certain lifetimes is a logic error. > > For example: > > f = some_file() #maybe it's the file store for a database implementation > f.write('a bunch of stuff') > del f > #insert code that assumes f is closed. That's not a logic error if you are coding in CPython, though I agree that in this particular case the explicit use of "with" would be preferable due to its clarity. |>oug From nospam at nowhere.com Fri Jul 13 22:51:48 2007 From: nospam at nowhere.com (DavidM) Date: 14 Jul 2007 14:51:48 +1200 Subject: ANN: PyBridge: Drupal modules in Python Message-ID: <46983a44$1@news.orcon.net.nz> Hi all, I wonder if I'm the only one who likes the Drupal (www.drupal.org) web CMS framework, but much prefers Python as a programming language. Anyway, I've put up the first cut of PyBridge - a framework that allows Drupal extension modules to be written in Python. http://www.freenet.org.nz/pybridge It's alpha code, but working fine with all my tests. Nice to have the best of both worlds. Cheers David From aleax at mac.com Tue Jul 3 11:38:21 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 3 Jul 2007 08:38:21 -0700 Subject: python 3.0 or 3000 ....is it worth waiting??? Newbie Question References: <1183475626.705580.214870@n2g2000hse.googlegroups.com> Message-ID: <1i0o2a2.1uey20p13blulzN%aleax@mac.com> Nomad.C at gmail.com wrote: > I'm considering learning Python...but with the python 3000 comming > very soon, is it worth waiting for?? I know that the old style of > coding python will run parallel with the new, but I mean, its going to > come to an end eventually. It will be years before Py3k is fully usable for "industrial-strength" programming: the language itself must stabilize, then the standard library, then third-party extensions. And migrating from Python 2.6 to Python 3000 will be very easy once the latter has all the 3rd party and standard library modules you need -- just as moving from 2.5 to 2.6 will be. So, there's really no reason to wait: start learning Python with 2.5, the solid implementation available right now and with tons of 3rd party extensions, tools, etc, and there will just be tiny amounts of effort required to eventually move up a long time in the future. Alex From python at jayloden.com Tue Jul 31 14:07:05 2007 From: python at jayloden.com (Jay Loden) Date: Tue, 31 Jul 2007 14:07:05 -0400 Subject: Iteration over strings In-Reply-To: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> Message-ID: <46AF7A49.3040804@jayloden.com> Robert Dailey wrote: > Hi, > > 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. Hi Robert, strings in Python are immutable - in other words, they cannot be updated in place as you're doing above. However, that doesn't mean you can't achieve what you're after. In Python, the way to approach this problem since you cannot modify the string in place, is to create a new string object with the desired content: str = "C:/somepath/folder/file.txt" newstr = "" for char in str: if char == "\\": char = "/" newstr = newstr + char str = newstr Note that for this particular example, there are also better ways of acheiving your goal: str = "C:/somepath/folder/file.txt" str = str.replace("\\", "/") HTH, -Jay From conra2004 at yahoo.com Tue Jul 31 09:24:18 2007 From: conra2004 at yahoo.com (yadin) Date: Tue, 31 Jul 2007 06:24:18 -0700 Subject: how to add a toolbar to a Frame using wxpython Message-ID: <1185888258.035919.55880@b79g2000hse.googlegroups.com> hi please am learning wxpython and I Need help on getting examles of how to create a toolbar with images that is add a toolbar to a Frame using wxpython using wxpython on a windows pc how can i add a toolbar to a GUI all sample codes i could find contain errors. i did the following but it is wrong! my biggest trouble seems to be with the IMAGES? do i have to create them, load them...? or they come with python like in Matlab thank you. import wx from pylab import* class MainWindow(wx.Frame): def __init__(self,parent,id,title): self.dirname='' wx.Frame.__init__(self,parent,wx.ID_ANY, title,wx.DefaultPosition, wx.Size(320,410)) ##############_______________________ADDING A TOOLBAR___________________###################### toolbar = wx.ToolBar(self, -1, style=wx.TB_HORIZONTAL | wx.NO_BORDER) toolbar.AddSimpleTool(1, wx.Image('stock_new.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'New', '') toolbar.Realize() Frame.Add(toolbar, 0, border=5) app = wx.PySimpleApp() frame = MainWindow(None, -1, " dipole antenna ") frame.show(1) frame.SetBackgroundColour('light grey') app.MainLoop() From apetresc at uwaterloo.ca Thu Jul 19 11:40:28 2007 From: apetresc at uwaterloo.ca (Adrian Petrescu) Date: Thu, 19 Jul 2007 08:40:28 -0700 Subject: Posted messages not appearing in this group In-Reply-To: <1184742315.618696.202600@z24g2000prh.googlegroups.com> References: <1184742315.618696.202600@z24g2000prh.googlegroups.com> Message-ID: <1184859628.544564.127670@m3g2000hsh.googlegroups.com> On Jul 18, 3:05 am, Sanjay wrote: > Hi All, > > I tried posting in this group twice since last week, but the messages > did not appear in the forum. Don't know why. Trying this message > again... > > Sanjay I think I'm having the exact same problem. I posted a new thread last night and it still hasn't shown up for me. I'm using Google Groups for both posting and reading. Maybe it has shown up and Google simply isn't showing it yet. Can anyone confirm that a thread posted yesterday (July 18th, 2007) whose title was something like "interpreting os.lstat() output" exists or not? This is quite distressing :( From bdesth.quelquechose at free.quelquepart.fr Mon Jul 2 10:54:22 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 02 Jul 2007 16:54:22 +0200 Subject: howto resend args and kwargs to other func? In-Reply-To: <5er6doF31bulkU1@mid.individual.net> References: <1183279997.244378.105810@n60g2000hse.googlegroups.com> <1183280667.542964.175570@u2g2000hsc.googlegroups.com> <1183282733.179683.174350@c77g2000hse.googlegroups.com> <5er6doF31bulkU1@mid.individual.net> Message-ID: <4688a103$0$29642$426a34cc@news.free.fr> Frank Swarbrick a ?crit : > dmitrey wrote: > >> Thanks all, I have solved the problem. > > > Why do people do this without posting what the actual solution is!!!! Probably because those people think usenet is a free help desk ? From sturlamolden at yahoo.no Sun Jul 8 16:35:55 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 08 Jul 2007 13:35:55 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: Message-ID: <1183926955.502410.215810@n60g2000hse.googlegroups.com> On Jun 20, 8:53 pm, Stephen R Laniel wrote: > Reading [1], I wonder: why isn't the compiler making better > use of (purely optional) type labeling? Why not make a compiler > directive so that > > a) it will check the types of all my arguments and return > values, If that is what you want, you can get typechecking using a simple function decorator: def typechecked(func): types = func.func_defaults def decorator(*args): if len(args) != len(types): raise TypeError, 'Wrong number or arguments, expected %d got %d' % (len(types),len(args)) for a,t in zip(args,types): if type(t) == type: if type(a) is not t: raise TypeError, 'Expected ' + str(t) + ' got ' + str(type(a)) else: if type(a) is not type(t): raise TypeError, 'Expected ' + str(type(t)) + ' got ' + str(type(a)) return func(*args) return decorator Now code like this: @typechecked def foobar(a = int, b = float, c = tuple): return None or @typechecked def foobar(a = int, b = float, c = 1.0): return None Your calls to foobar will be typechecked (at runtime, not statically), and a TypeError exception thrown if your calling types were incorrect. Regards, Sturla Molden From kevin.t.ryan at gmail.com Fri Jul 27 18:55:29 2007 From: kevin.t.ryan at gmail.com (Kevin T. Ryan) Date: Fri, 27 Jul 2007 22:55:29 -0000 Subject: Packages Message-ID: <1185576929.136179.174440@b79g2000hse.googlegroups.com> Hi All - I'm having a problem and I hope you can help. I can't seem to import packages from within the package substructure as I think I should be able to. For example, I create a directory structure as follows: testpkg __init__.py [empty] testsub1/ __init__.py [empty] bad.py [import testpkg.testsub2.good; print "hello from bad"] <- error testsub2/ __init__.py [empty] good.py [print "hello from good"] Whenever I try to run bad.py (just python bad.py from within the testsub2 subdirectory or from above the testpkg directory) I get an error. For example: $ python testpkg/testsub1/bad.py Traceback (most recent call last): File "testpkg/testsub1/bad.py", line 1, in References: Message-ID: <1185035998.956845.244510@o61g2000hsh.googlegroups.com> On Jul 13, 7:50 pm, Dan Stromberg - Datallegro wrote: > You could start up a pty and do your own Pexpect-like thing, using > read/readline/write. > > However, this may not be portable to windows. Maybe if you get the python > that comes with cygwin, or build your own python under the cygwin thanks for the suggestion. I will follow up on Noah's pexpect sugestion bellow. thanks for the input, cross platform is key with low overhead. From gnewsg at gmail.com Wed Jul 11 22:11:37 2007 From: gnewsg at gmail.com (billiejoex) Date: Wed, 11 Jul 2007 19:11:37 -0700 Subject: asyncore and OOB data In-Reply-To: References: <1184172867.420979.215300@q75g2000hsh.googlegroups.com> Message-ID: <1184206297.813178.141000@n2g2000hse.googlegroups.com> Douglas Wells wrote: > Second, when I look at the FTP specification, I don't find the > concept of OOB anywhere. So, it's not clear what OOB data would > mean in terms of the defined FTP commands in any case. Steve Holde wrote: > You are correct, however, in stating that the FTP > protocol doesn't support or implement out-of-band > data transmissions. Wait a sec. RFC959 [1], on chapter 4.1.3 says: > Certain commands (such as ABOR, STAT, QUIT) may be sent over the > control connection while a data transfer is in progress. Some > servers may not be able to monitor the control and data connections > simultaneously, in which case some special action will be necessary > to get the server's attention. The following ordered format is > tentatively recommended: > 1. User system inserts the Telnet "Interrupt Process" (IP) signal > in the Telnet stream. > 2. User system sends the Telnet "Synch" signal. > 3. User system inserts the command (e.g., ABOR) in the Telnet > stream. > 4. Server PI, after receiving "IP", scans the Telnet stream for > EXACTLY ONE FTP command. I believe that the TCP "urgent" flag, activated by using socket.MSG_OOB, should be set when client must send the "Sync" signal (RFC854 [2] talks about it). I think that you do not find references of OOB in RFC959 (FTP) just because it is specified into RFC854 (Telnet). According to RFC854 a Sync signal should consist of sending Telnet DATA MARK (DM) inside a TCP packet with URGent flag set: > The Synch is sent via the TCP send operation with the Urgent > flag set and the DM as the last (or only) data octet. If we'd want to traduce this in Python we could assume that a fully RFC-compliant FTP client implementation sending 'ABOR' command should act like this: >>> import socket, telnetlib >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>> s.connect(('127.0.0.1', 21)) >>> s.sendall(telnetlib.IP) >>> s.sendall(telnetlib.DM, socket.MSG_OOB) >>> s.sendall('ABOR\r\n') We also could find references about such flag ("URG"ent, alias OOB) even in Bernstein FTP-related paper (http://cr.yp.to/ftp/ pipelining.html) which says: > The client is required to send the TELNET string \377\364, and > then send the TELNET string \377\362 with the TCP Urgent bit > set, immediately before the ABOR request. ...that, traduced, should appear like this: >>> s.sendall("\377\364") # Telnet IP signal? >>> s.sendall("\377\362", socket.MSG_OOB) # Telnet Synch signal? >>> s.sendall("ABOR\r\n") I also find interesting the fact that ftplib ABOR command implementation is not RFC-compliant (and I can't realize how my server could recognize it): def abort(self): '''Abort a file transfer. Uses out-of-band data. This does not follow the procedure from the RFC to send Telnet IP and Synch; that doesn't seem to work with the servers I've tried. Instead, just send the ABOR command as OOB data.''' line = 'ABOR' + CRLF if self.debugging > 1: print '*put urgent*', self.sanitize(line) self.sock.sendall(line, MSG_OOB) resp = self.getmultiline() if resp[:3] not in ('426', '226'): raise error_proto, resp [1] http://www.faqs.org/rfcs/rfc959.html [2] http://www.faqs.org/rfcs/rfc854.html From aahz at pythoncraft.com Sat Jul 7 09:46:29 2007 From: aahz at pythoncraft.com (Aahz) Date: 7 Jul 2007 06:46:29 -0700 Subject: Mixing Python and C threads References: Message-ID: In article , =?utf-8?b?U3TDqXBoYW5l?= Larouche wrote: >Aahz pythoncraft.com> writes: >> In article python.org>, >> =?utf-8?b?U3TDqXBoYW5l?= Larouche polymtl.ca> wrote: >>> >>>If I call the methods in the C++ modules from the Python main thread, I >>>don't have any problem. However, they are usually called from another >>>Python thread (using the threading module) to keep the GUI responsive >>>and, then, Python crashes. >> >> The question is whether your C++ code is designed to be called from >> multiple threads. That is, if you call your C++ code from a *single* >> non-main thread, does it work? > >It does work if I call it from a single non-main thread. But everything >must be called from that thread, including the import of the module. > >I still do not understand what is the problem. The C++ code is not >thread safe, but I call it from 1 Python thread at a time. Anyway, >I have always called it from multiple Python threads without any >problem. Having put a few printf in the module, I can say that it >crashes exactly when it tries to create C threads. 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. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I support the RKAB From sjmachin at lexicon.net Wed Jul 25 18:44:29 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 25 Jul 2007 15:44:29 -0700 Subject: Reading files, splitting on a delimiter and newlines. In-Reply-To: <46a783a1$0$25842$9b622d9e@news.freenet.de> References: <1185378363.166434.172190@r34g2000hsd.googlegroups.com> <1185380186.215288.83990@b79g2000hse.googlegroups.com> <46a783a1$0$25842$9b622d9e@news.freenet.de> Message-ID: <1185403469.715876.210020@j4g2000prf.googlegroups.com> On Jul 26, 3:08 am, Stargaming wrote: > On Wed, 25 Jul 2007 09:16:26 -0700, kyosohma wrote: > > On Jul 25, 10:46 am, chris... at gmail.com wrote: > >> Hello, > > >> I have a situation where I have a file that contains text similar to: > > >> myValue1 = contents of value1 > >> myValue2 = contents of value2 but > >> with a new line here > >> myValue3 = contents of value3 > > >> My first approach was to open the file, use readlines to split the > >> lines on the "=" delimiter into a key/value pair (to be stored in a > >> dict). > > >> After processing a couple files I noticed its possible that a newline > >> can be present in the value as shown in myValue2. > > >> In this case its not an option to say remove the newlines if its a > >> "multi line" value as the value data needs to stay intact. > > >> I'm a bit confused as how to go about getting this to work. > > >> Any suggestions on an approach would be greatly appreciated! > > > I'm confused. You don't want the newline to be present, but you can't > > remove it because the data has to stay intact? If you don't want to > > change it, then what's the problem? > > > Mike > > It's obviously that simple line-by-line filtering won't handle multi-line > statements. > > You could solve that by saving the last item you added something to and, > if the line currently handles doesn't look like an assignment, append it > to this item. You might run into problems with such data: > > foo = modern maths > proved that 1 = 1 > bar = single > > If your dataset always has indendation on subsequent lines, you might use > this. Or if the key's name is always just one word. > My take: all of the above, plus: Given that you want to extract stuff of the form = I'd suggest developing a fairly precise regular expression for LHS, maybe even for RHS, and trying this on as many of these files as you can. Why an RE for RHS? Consider: foo = somebody said "I think that REs = trouble maybe_better = pyparsing" :-) From filox_realmmakniovo at yahoo.com Wed Jul 4 10:50:38 2007 From: filox_realmmakniovo at yahoo.com (filox) Date: Wed, 4 Jul 2007 16:50:38 +0200 Subject: reading email using django Message-ID: i've just installed django and it seems pretty cool. i've managed to send an email succesfully, but i didn't find any information on reading email. is that even possible with django (e.g. open my gmail inbox and read mail from it)? -- You're never too young to have a Vietnam flashback From luke.hoersten at gmail.com Tue Jul 3 10:19:17 2007 From: luke.hoersten at gmail.com (Luke Hoersten) Date: Tue, 03 Jul 2007 14:19:17 -0000 Subject: Correct abstraction for TK In-Reply-To: <7xlkdyapsz.fsf@ruckus.brouhaha.com> References: <1183412267.513714.183800@q75g2000hsh.googlegroups.com> <7xlkdyapsz.fsf@ruckus.brouhaha.com> Message-ID: <1183472357.471939.293820@w5g2000hsg.googlegroups.com> Thanks for all the suggestions guys. I'm realizing that I need to chose more of a specific paradigm. With closures, I was able to stay away from unneeded classes before but Tk brings it to a whole other level. Thanks again, Luke On Jul 3, 2:50 am, Paul Rubin wrote: > luke.hoers... at gmail.com writes: > > I'm looking for a good example of how to correctly abstract TK code > > from the rest of my program. I want to just get some user info and > > then get 4 values from the GUI. Right now I've written it OOP per the > > examples on python.org but it doesn't seem to be meshing very well > > with the rest of my project. > > Simplest: just have gui operations call the application code. The > application main loop is just the gui event loop. Example (first tk > program I ever wrote, and one of my first python programs): > > http://www.nightsong.com/phr/python/calc.py > > That might be enough for what you're doing. > > Fancier: put gui in separate thread. Be careful, it's not reentrant; > all communication with the application has to be through queues, sort > of like writing a miniature web server. Most straightforward is to > pass tuples like (function, args, **kwargs) through the queues, where > the opposite end invokes the function on the arg list. There are some > recipes in the Python cookbook for triggering the event loop on a > periodic timeout from inside tkinter. > > See also "model-view-controller" for a more complex design approach > intended to separate the interface from the application logic. > > Finally, consider total separation by embedding an http server in the > application, so the gui is a web browser and you write a web app. > It's often easier to code a simple html interface than to mess with > the damn Tk widgets and trying to get them to look decent on the > screen, plus it lets you easily put the client on a remote machine, > support multiple clients simultaneously, etc. From dtgeadamo at yahoo.com Fri Jul 20 12:37:17 2007 From: dtgeadamo at yahoo.com (Viewer T.) Date: Fri, 20 Jul 2007 09:37:17 -0700 Subject: Images in Tkinter Message-ID: <1184949437.876063.78860@w3g2000hsg.googlegroups.com> I wrote a class in which I have to use Tkinter images. When I create an image object in the class and reference it with the image attribute of label within the class, it does not dhow the image. It just shows a blank label that conforms to the size of the image. My images is a GIF image. My code takes the form: class Login: def __init__(self): create image object and other things necessary for class initialisation self.make_widgets def make_widgets(self): Then I create my widgets Then, I instantiate the login class. I use Python 2.5. Does anyone have any idea why my imae does not diplay itself? I have tried using the image before outside a class and it works! Also, I tried creating the image object outside class but it gives a runtime error saying it is too early to create an image object. Please help! From LarinAM at gmail.com Thu Jul 5 05:23:24 2007 From: LarinAM at gmail.com (LarinAM at gmail.com) Date: Thu, 05 Jul 2007 09:23:24 -0000 Subject: Python daemon in Linux Message-ID: <1183627404.157350.105560@o61g2000hsh.googlegroups.com> i made MyThread(Thread) when isDaemon() == 0: everything works when isDaemon() == 1: nothing works why??? From star.public at gmail.com Tue Jul 17 13:16:08 2007 From: star.public at gmail.com (star.public at gmail.com) Date: Tue, 17 Jul 2007 10:16:08 -0700 Subject: Fetching a clean copy of a changing web page In-Reply-To: <469B3160.3060306@web.de> References: <5g0g5hF3egi7pU1@mid.uni-berlin.de> <469B3160.3060306@web.de> Message-ID: <1184692568.570254.96520@m37g2000prh.googlegroups.com> On Jul 16, 4:50 am, Stefan Behnel wrote: > Diez B. Roggisch wrote: > > John Nagle wrote: > >> I'm reading the PhishTank XML file of active phishing sites, > >> at "http://data.phishtank.com/data/online-valid/" This changes > >> frequently, and it's big (about 10MB right now) and on a busy server. > >> So once in a while I get a bogus copy of the file because the file > >> was rewritten while being sent by the server. > > >> Any good way to deal with this, short of reading it twice > >> and comparing? > > > Apart from that - the only thing you could try is to apply a SAX parser > > on the input stream immediatly, so that at least if the XML is non-valid > > because of the way they serve it you get to that ASAP. > > Sure, if you want to use lxml.etree, you can pass the URL right into > etree.parse() and it will throw an exception if parsing from the URL fails to > yield a well-formed document. > > http://codespeak.net/lxml/http://codespeak.net/lxml/dev/parsing.html > > BTW, parsing and serialising it back to a string is most likely dominated by > the time it takes to transfer the document over the network, so it will not be > much slower than reading it using urlopen() and the like. > > Stefan xml.etree.ElementTree is in the standard lib now, too. Also, xml.etree.cElementTree, which has the same interface but is blindingly fast. (I'm working on a program which needs to read/recreate the (badly designed, horrible, evil) iTunes Library XML, of which mine is about 10mb, and cEtree parses it in under a second and 60mb of ram (whearas minidom takes like two minutes and 600+mb to do the same thing).) (I mean really -- the playlists are stored as five megs of lists with elements that are dictionaries of one element, all looking exactly like this: \nTrack ID4521\n \n --- ) -- star From gabe at dragffy.com Mon Jul 23 12:32:19 2007 From: gabe at dragffy.com (Gabriel Dragffy) Date: Mon, 23 Jul 2007 17:32:19 +0100 Subject: Reading data from an ISA port Message-ID: <60F0AA76-9D30-4CE6-A2D8-4CC97809C2EB@dragffy.com> Dear list members I must admit I am a new user of Python, but it is a language that I enjoy using. For one of my university projects I need to write a program that can read several bytes from an ISA port. It has been suggested to me that I look at using C or Pyinline. If I can I would prefer to continue to use Python, and Pyinline won't play ball. I am sure Python can do this for me, but the question is how? What modules and code do I need to look? I'd be very grateful for any suggestions and advice. Best regards Gabriel Dragffy gabe at dragffy.com From aaron.watters at gmail.com Fri Jul 13 13:14:40 2007 From: aaron.watters at gmail.com (aaron.watters at gmail.com) Date: Fri, 13 Jul 2007 10:14:40 -0700 Subject: renaming an open file in nt like unix? Message-ID: <1184346880.093826.176350@n2g2000hse.googlegroups.com> Hi. I'm writing an archival system which I'd like to be portable to Windows. The system relies on the property of Unix which allows a process to keep a file open even if another process renames it while it is open. Neither process sees any anomaly or error. Do the NT file systems support this feature (which I think is standard for POSIX systems)? Inquiring minds want to know. -- Aaron Watters === an apple every 8 hours will keep 3 doctors away. -- kliban From steve at holdenweb.com Mon Jul 23 16:14:56 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Jul 2007 16:14:56 -0400 Subject: inet_addr() in Python In-Reply-To: References: Message-ID: brad wrote: > Does Python have an equivalent to C's inet_addr()? > socket.inet_aton() produces a four-byte string you can pass as a struct in_addr, if that's what you are looking for. If you want a number then use the struct module to manipulate it further. >>> s.inet_aton('127.0.0.1') '\x7f\x00\x00\x01' 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 nospam.themindstorm at gmail.com Thu Jul 26 07:27:30 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Thu, 26 Jul 2007 11:27:30 +0000 (UTC) Subject: os.path.walk usage on WinXP References: Message-ID: Alex Popescu wrote in news:Xns997991CDF7710themindstorm at 80.91.229.5: > Hi all! > > I am trying to use the os.path.walk function, but I am getting a weird > error: > > def _walk(dir_name): > def selector(arg, dirname, fnames): > print "selector" > > os.path.walk(dir_name, selector, None) > > File "C:\zengarden\python\python25\lib\ntpath.py", line 325, in walk > names = os.listdir(top) > TypeError: coercing to Unicode: need string or buffer, list found > > After searching through the documentation the only thing that I've > found is the comment on os.listdir(path): > > [quote] > Changed in version 2.3: On Windows NT/2k/XP and Unix, if path is a > Unicode object, the result will be a list of Unicode objects. > [/quote] > > Unfortunately, I have no idea what to do next. > > TIA, > ./alex > -- > .w( the_mindstorm )p. > This seems to work in Python console, so I'm more puzzled now :-(. bests, ./alex -- .w( the_mindstorm )p. From alexandre.ferrieux at gmail.com Sun Jul 22 18:33:54 2007 From: alexandre.ferrieux at gmail.com (Alexandre Ferrieux) Date: Sun, 22 Jul 2007 15:33:54 -0700 Subject: Lazy "for line in f" ? In-Reply-To: References: <1185120650.412694.314280@o61g2000hsh.googlegroups.com> Message-ID: <1185143634.778056.227720@g4g2000hsf.googlegroups.com> On Jul 22, 7:21 pm, Miles wrote: > On 7/22/07, Alexandre Ferrieux wrote: > > > The Tutorial says about the "for line in f" idiom that it is "space- > > efficient". > > Short of further explanation, I interpret this as "doesn't read the > > whole file before spitting out lines". > > In other words, I would say "lazy". Which would be a Good Thing, a > > much nicer idiom than the usual while loop calling readline()... > > > But when I use it on the standard input, be it the tty or a pipe, it > > seems to wait for EOF before yielding the first line. > > It doesn't read the entire file, but it does use internal buffering > for performance. On my system, it waits until it gets about 8K of > input before it yields anything. If you need each line as it's > entered at a terminal, you're back to the while/readline (or > raw_input) loop. How frustrating ! Such a nice syntax for such a crippled semantics... Of course, I guess it is trivial to write another iterator doing exactly what I want. But nonetheless, it is disappointing not to have it with the standard file handles. And speaking about optimization, I doubt blocking on a full buffer gains much. For decades, libc's fgets() has been doing it properly (block- buffering when data come swiftly, but yielding lines as soon as they are complete)... Why is the Python library doing this ? -Alex From stefan.behnel-n05pAM at web.de Mon Jul 9 17:00:32 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 09 Jul 2007 23:00:32 +0200 Subject: dealing with nested xml within nested xml within...... In-Reply-To: <1184011424.662766.176530@k79g2000hse.googlegroups.com> References: <1184011424.662766.176530@k79g2000hse.googlegroups.com> Message-ID: <4692A1F0.1050100@web.de> Ultrus wrote: > I don't need specific examples, but I'm trying to wrap my head around > parsing xml within xml and even further, not limiting how far someone > will nest xml. I'm already making great use of BeautifulSoup's > BeautifulStoneSoup to parse xml, but what do I do if I come across > something like this? > > >
  • This is a random response (once parsed)
  • >
  • > >
  • This is a random response within a random response
  • >
  • > >
  • This is a random response within a random response, > within another random response
  • >
  • Like above, this is another random response.
  • >
    > > > > > > Not knowing how far one will nest random responses, how would one > manage digging into xml like this? I don't know what you want to do with this document, but you might want to consider using lxml.etree to handle it: >>> from lxml import etree >>> tree = etree.parse("myfile.xml") >>> for random in tree.getiterator("random"): ... for li in random: ... if li.text.strip(): ... print li.text http://codespeak.net/lxml/ Stefan From len-l at telus.net Mon Jul 2 20:09:21 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Tue, 03 Jul 2007 00:09:21 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: Douglas Alan wrote: > Lenard Lindstrom writes: > >>> You don't necessarily want a function that raises an exception to >>> deallocate all of its resources before raising the exception, since >>> you may want access to these resources for debugging, or what have >>> you. > >> No problem: >> >> [...] >> >> >>> class MyFile(file): >> def __exit__(self, exc_type, exc_val, exc_tb): >> if exc_type is not None: >> self.my_last_posn = self.tell() >> return file.__exit__(self, exc_type, exc_val, exc_tb) > > I'm not sure I understand you here. You're saying that I should have > the foresight to wrap all my file opens is a special class to > facilitate debugging? > > If so, (1) I don't have that much foresight and don't want to have > to. (2) I debug code that other people have written, and they often > have less foresight than me. (3) It would make my code less clear to > ever file open wrapped in some special class. > Obviously you had the foresight to realize with statements could compromise debugging. I never considered it myself. I don't know the specifics of your particular project, what the requirements are. So I can't claim this is the right solution for you. But the option is available. > Or are you suggesting that early in __main__.main(), when I wish to > debug something, I do something like: > > __builtins__.open = __builtins__.file = MyFile > > ? > > I suppose that would work. No, I would never suggest replacing a builtin like that. Even replacing a definite hook like __import__ is risky, should more than one package try and do it in a program. > I'd still prefer to clear exceptions, > though, in those few cases in which a function has caught an exception > and isn't going to be returning soon and have the resources generally > kept alive in the traceback. To me, that's the more elegant and > general solution. > As long as the code isn't dependent on explicitly cleared exceptions. But if it is I assume it is well documented. -- Lenard Lindstrom From crobc at BOGUS.sbcglobal.net Sat Jul 28 22:56:13 2007 From: crobc at BOGUS.sbcglobal.net (CC) Date: Sat, 28 Jul 2007 19:56:13 -0700 Subject: How to stop print printing spaces? In-Reply-To: <1RPqi.20711$rB1.1018083@phobos.telenet-ops.be> References: <1RPqi.20711$rB1.1018083@phobos.telenet-ops.be> Message-ID: Roel Schroeven wrote: > CC schreef: >> ln = '\x00\x01\xFF 456789abcdef' >> # This works: >> import sys >> for i in range(0,15): >> sys.stdout.write( '%.2X' % ord(ln[i]) ) >> print >> Is that the best way, to work directly on the stdout stream? > > It's not a bad idea: print is mostly designed to be used in interactive > mode and for quick and dirty logging; not really for normal program > output (though I often use it for that purpose). > > There is another way: construct the full output string before printing > it. You can do that efficiently using a list comprehension and the > string method join(): > > >>> print ''.join(['%.2X' % ord(c) for c in ln]) > 0001FF20343536373839616263646566 Oh yeah, that's right! > In Python 2.4 and higher, you can use a generator expression instead of > a list comprehension: > > >>> print ''.join('%.2X' % ord(c) for c in ln) > 0001FF20343536373839616263646566 Hmm. I'm at 2.3 :-( > BTW, in your examples it's more pythonic not to use range with an index > variable in the for-loop; you can loop directly over the contents of ln > like this: > > import sys > for c in ln: > sys.stdout.write('%.2X' % ord(c)) > print Ah yes, duh! I played with this means of iterating over items in a sequence the other day while studying the tutorial, but it sinks in slowly for a C programmer. That's why I posted my silly code. I'll probably do that a lot until I get used to this pythonic business. Thanks for the input! -- _____________________ Christopher R. Carlen crobc at bogus-remove-me.sbcglobal.net SuSE 9.1 Linux 2.6.5 From deets at nospam.web.de Mon Jul 16 02:05:32 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 16 Jul 2007 08:05:32 +0200 Subject: Fetching a clean copy of a changing web page In-Reply-To: References: Message-ID: <5g0g5hF3egi7pU1@mid.uni-berlin.de> John Nagle schrieb: > I'm reading the PhishTank XML file of active phishing sites, > at "http://data.phishtank.com/data/online-valid/" This changes > frequently, and it's big (about 10MB right now) and on a busy server. > So once in a while I get a bogus copy of the file because the file > was rewritten while being sent by the server. > > Any good way to deal with this, short of reading it twice > and comparing? Make them fix the obvious bug they have would be the best of course. Apart from that - the only thing you could try is to apply a SAX parser on the input stream immediatly, so that at least if the XML is non-valid because of the way they serve it you get to that ASAP. But it will only shave off a few moments. Diez From ninja.krmenadl at nes.com Sat Jul 7 18:44:45 2007 From: ninja.krmenadl at nes.com (Boris Ozegovic) Date: Sun, 8 Jul 2007 00:44:45 +0200 Subject: httplib module References: Message-ID: Boris Ozegovic wrote: > Why do I get double new lines when geting data from server? Example: Fixed. -- Ne dajte da nas la?ljivac Bandi? truje: http://cnn.blog.hr/arhiva-2007-06.html#1622776372 From jeffrey at fro.man Sun Jul 22 03:21:40 2007 From: jeffrey at fro.man (Jeffrey Froman) Date: Sun, 22 Jul 2007 00:21:40 -0700 Subject: Python version changes, sys.executable does not References: <139v9oe22rihh40@corp.supernews.com> Message-ID: <13a61c4lt5in220@corp.supernews.com> Jim Langston wrote: > I think it's because your python directory is in the path before your > python2.5 directory. Thanks for the tip. In fact, /usr/local/bin/python (2.5) is on my PATH before /usr/bin/python (2.3). I did find the problem however -- it turns out that caching the executable path is a feature of the bash shell, possibly a buggy one. After installing the new executable in /usr/local/bin, bash claimed to be running that executable, but was actually invoking the cached "python" at /usr/bin/python. What sorted out the confusion for me was when someone demonstrated to me how sys.executable could be fooled: $ exec -a /usr/bin/foobar python Python 2.5.1 (r251:54863, May 4 2007, 16:52:23) [GCC 4.1.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.executable '/usr/bin/foobar' To remove the cached version, I ran: $ hash -d python After which, running "python" invoked a properly named /usr/local/bin/python as expected. Thanks, Jeffrey From tinaweb at bestemselv.com Sat Jul 28 06:39:45 2007 From: tinaweb at bestemselv.com (Tina I) Date: Sat, 28 Jul 2007 12:39:45 +0200 Subject: Wikicodia - The code snippets wiki In-Reply-To: <1185542076.188208.70040@d55g2000hsg.googlegroups.com> References: <1185542076.188208.70040@d55g2000hsg.googlegroups.com> Message-ID: Wikicodia Admin wrote: > Dears, > > Wikicodia is a wiki based project for sharing code snippets. We're > collecting large number of code snippets for all code-based > programming languages, scripts, shells and consoles. We wish you could > help us. We're still BETA. Your suggestions, ideas and criticisms are > very welcomed. We're waiting for you contributions. You can easily > share and search our snippet using our Google Desktop Gadget. Share > your Python snippets to help the world :) > > http://www.wikicodia.com > > Thanks > Wikicodia Admin > Just in case you are not aware of it; there already exists a fairly identical service called "The Rosetta Code" at http://www.rosettacode.org/ Maybe you could join forces instead? ;-) Tina PS: I'm not affiliated with Rosetta in any way... From gagsl-py2 at yahoo.com.ar Mon Jul 23 17:38:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Jul 2007 18:38:37 -0300 Subject: Confused with csv.reader copies References: <1185216342.833408.56690@m3g2000hsh.googlegroups.com> Message-ID: En Mon, 23 Jul 2007 15:45:42 -0300, Robert Dailey escribi?: > import csv > > def pass1( reader ): > print reader.next() > print reader.next() > > def pass2( reader ): > print reader.next() > print reader.next() > > reader = csv.reader( open( "C:/IT/Method/SpaceImpact/code/tools/ > ProfileViewer/performance_profile.csv", "rb" ) ) > > pass1( reader ) > pass2( reader ) [expecting the two calls to print the same two lines] > My understanding is that objects are passed by reference, meaning > there is no hard copy of the data, however the copies passed to > functions do not affect the version passed in. In other words, when I > call "next" on the reference passed into each function, it should not > affect the variable that was originally passed in. Both functions receive the *same* reader object, not a copy. Calling next() affects the reader internal state, it doesn't matter where you call it from. You should read this threads from last week: http://groups.google.com/group/comp.lang.python/browse_thread/thread/45732106f147ac07/ http://groups.google.com/group/comp.lang.python/browse_thread/thread/56e7d62bf66a435c/ > I'm attempting to use recursion to build a TreeCtrl in wxPython using > this data, and I can't get it to work properly if the variable outside > of the function call ends up having its state (e.g., its "next" > pointer) modified by passing it into other functions. > > Any tips on getting this to work? I'm a native C++ programmer still > learning Python, so I apologize for any confusion. Thanks. The simplest way -if the file is not so huge- is to read the whole file and keep the results in a list: lines = list(reader) There are other alternatives using the itertools module but aren't easy to grasp for a beginner. -- Gabriel Genellina From lillowboman24 at yahoo.com Mon Jul 30 23:09:27 2007 From: lillowboman24 at yahoo.com (lowboman) Date: Mon, 30 Jul 2007 20:09:27 -0700 Subject: Free SMS from Computer Worldwide Message-ID: <1185851367.570284.215960@x35g2000prf.googlegroups.com> Hello there I invite you to check out my site http://www.nocostsms.com you can send free sms text 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 Sascha.Kuhlmann at gmail.com Tue Jul 3 22:30:35 2007 From: Sascha.Kuhlmann at gmail.com (KuhlmannSascha) Date: Wed, 04 Jul 2007 02:30:35 -0000 Subject: How can i change an Object type ? Message-ID: <1183516235.774875.45710@q69g2000hsb.googlegroups.com> Hi, i tried now for several hours to read through a win32com API to access Itunes and read out myplaylists. First of all the Code: import os, sys, pythoncom, win32com.client, pywintypes, sets def showplaylists(): iTunes = win32com.client.Dispatch("iTunes.Application") playlists = iTunes.LibrarySource.Playlists numPlaylists = playlists.Count while (numPlaylists != 0): curPlaylist = playlists.Item(numPlaylists) if curPlaylist.Kind == 2: if curPlaylist.Smart(): numPlaylists -= 1 else: print curPlaylist.Name numtrack = curPlaylist.Tracks.Count while (numtrack !=0): curPlaylist.Tracks(numtrack).Name numtrack -= 1 numPlaylists -= 1 showplaylists() The current Logic is to access first Itunes and then a Playlist Collection. This Playlist collection returns different kind of objects for Playlists. I am focussing on the Playlists of the object UserPlaylist. (CodeLine: if curPlaylist.Kind == 2:) After that i should be sure to have a UserPlaylist, but Python stops with an exception that the requested Attribute "Smart" is not available Error MEssage: AttributeError: '' object has no attribute 'Smart' Any help is appreciated...... Regards Sascha From aleax at mac.com Mon Jul 16 10:53:14 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 16 Jul 2007 07:53:14 -0700 Subject: Accessing Python variables in an extension module References: <1184553584.757696.92630@g4g2000hsf.googlegroups.com> <1i1b7zw.64m7g071sk32N%aleax@mac.com> <1184591293.938223.105800@o61g2000hsh.googlegroups.com> Message-ID: <1i1c33r.1tle2a728vehlN%aleax@mac.com> MD wrote: > Hi Alex, > Thanks for your reply. It was exactly what I was looking for. Two > additional questions > 1) Is there anyway to find out which modules a variable belongs to > when I have only its name (and its not qualified with the complete > name like module.varname) Loop through all modules in sys.modules and you will find a set (which may be empty) of modules which happen to have that name as an attribute. It's a very peculiar thing to do (not clear what you expect to do based on that information) but not difficult. > 2) Is there anyway to find the type of the object in C using something > like a switch statement? I was looking for something like this > switch type(object) { > STRING: "This is a string object"; > break; > INTEGER: "This is an integer object"; > break; > BOOLEAN: "This is a boolean object"; > ......... > ......... > } > I don't want to run all the C Py***_Check functions on the object. > Something like the switch statement above will lead to nice and clean > code. Each Python object, in C, carries a pointer to its type object. Of course there are unbounded numbers of types, but at least you can get such information as the type's name and the module if any in which it may have been defined, essentially like you'd do with type(somobj) if you were working directly in Python. Alex From steve at holdenweb.com Fri Jul 13 14:38:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Jul 2007 14:38:18 -0400 Subject: Understanding python functions - Instant Python tutorial In-Reply-To: <4866bea60707131039l6d2027a9q5f0909f1c2e4b0@mail.gmail.com> References: <878x9kkeif.fsf@benfinney.id.au> <4866bea60707131039l6d2027a9q5f0909f1c2e4b0@mail.gmail.com> Message-ID: Chris Mellon wrote: > On 7/13/07, Chris Carlen wrote: >> Ben Finney wrote: >>> Chris Carlen writes: > >>> That's not how Python works. Every value is an object; the assignment >>> operator binds a name to an object. This is more like writing the name >>> on a sticky-note, and sticking it onto the object. >>> >>> * The object itself doesn't change or "move". >>> >>> * The object can be referred to by that name, but isn't "inside" the >>> name in any way. >>> >>> * Assigning multiple names to the same object just means you can >>> refer to that same object by all those names. >>> >>> * When a name goes away, the object still exists -- but it can't be >>> referred to if there are no longer any names left on it. >>> >>> * Assigning a different object to an existing name just means that >>> the same sticky-note has moved from the original object to the new >>> one. Referring to the same name now references a different object, >>> while the existing object keeps all the other names it had. >> Excellent description. This understandable to me since I can envision >> doing this with pointers. But I have no idea how Python actually >> implements this. It also appears that I am being guided away from >> thinking about it in terms of internal implementation. >> > > I assume that you're familiar with the general concept of hash tables. > Scopes in Python are hash tables mapping strings to Python objects. > Names are keys into the hash table. > > a = 10 > > is the same as > currentScope["a"] = 10 > > print a > > is the same as > print currentScope["a"] > > As you can see, there's no way that assignment can result in any sort > of sharing. The only way that changes can be seen between shared > objects is if they are mutated via mutating methods. > > Python objects (the values in the hashtable) are refcounted and can be > shared between any scope. > >>> When you pass an object as a parameter to a function, the object >>> receives a new sticky-label: the parameter name under which it was >>> received into the function scope. Assignment is an act of binding a >>> name to an object; no new object is created, and it still has all the >>> other names it had before. > > Each scope is it's own hashtable. The values can be shared, but not > the keys. When you call a function, the objects (retrieved from the > callers local scope by name) are inserted into the functions local > scope, bound to the names in the function signature. This is what > Guido calls "call by object reference". > This is, of course, something of an oversimplification. First, the global statement allows you to modify a name of module scope from inside another scope such as a functions. > > >> Ok, so I can understand the code above now. >> >> In the first case I pass the reference to the list to change(). In the >> function, some_list is another name referring to the actual object >> [1,2,3]. Then the function changes the object referred to by the second >> element of the list to be a 4 instead of a 2. (Oh, the concept applies >> here too!) Out of the function, the name x refers to the list which has >> been changed. >> >> In the second case, y refers to a '1' object and when the function is >> called the object 1 now gets a new reference (name) x inside the >> function. But then a new object '0' is assigned to the x name. But the >> y name still refers to a '1'. >> >> I get it. But I don't like it. Yet. Not sure how this will grow on me. >> > > You need to learn about Pythons scoping now, not it's object passing > semantics. When you're used to thinking in terms of pointers and > memory addresses it can take some work to divorce yourself from those > habits. Then, of course, there are the nested scoping rule for functions defined inside other 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 deets at nospam.web.de Mon Jul 16 13:42:51 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 16 Jul 2007 19:42:51 +0200 Subject: The ** operator ambiguous? In-Reply-To: <1184607614.904143.219330@w3g2000hsg.googlegroups.com> References: <1184607614.904143.219330@w3g2000hsg.googlegroups.com> Message-ID: <5g1p11F3env9hU1@mid.uni-berlin.de> Robert Dailey schrieb: > I noticed that the ** operator is used as the power operator, however > I've seen it used when passing variables into a function. For example, > I was researching a way to combine dictionaries. I found that if you > do this: > > a = {"t1":"a", "t2":"b"} > b = {"t3":"c"} > dict( a, **b ) > > > This combines the two dictionaries. However, I have no idea what the > ** operator is here. I know that when you specify ** as a parameter in > a function definition, it represents a dictionary of parameters passed > in. However, in this example it is NOT being used in a function > definition. It is being used when passing variables into a function. > Can someone explain what this means? I looked in the documentation but > I couldn't find anything. It's the opposite to the function definition **-operator: def foo(a=0, b=1): print a,b foo(**{a:100, b:200}) -> 100 200 Diez From timr at probo.com Sat Jul 28 01:30:00 2007 From: timr at probo.com (Tim Roberts) Date: Sat, 28 Jul 2007 05:30:00 GMT Subject: 128 or 96 bit integer types? References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com> <1185562901.206212.52570@j4g2000prf.googlegroups.com> Message-ID: "mensanator at aol.com" wrote: > >On Jul 27, 1:27 pm, Peter Otten <__pete... at web.de> wrote: >> Robert Dailey wrote: >> > Is there build-in or third party support for large integer types, such >> > as 96 or 128 bits in size? I require such large sizes for precision >> > issues (nanoseconds). Thanks. >> >>> SECOND = 10**9 >> >>> YEAR = 365*24*60*60 >> >>> 2**128/SECOND/YEAR >> >> 10790283070806014188970L >> >> What are you measuring? The age of the universe? In nanoseconds? >> >> :-) > >Well, 2**96 would only be 2512308552583 years. Yes, but that's still roughly 100 times the estimated age of the universe. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve at REMOVE.THIS.cybersource.com.au Sat Jul 28 01:04:09 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Jul 2007 15:04:09 +1000 Subject: pythonic parsing of URL References: <1185592232.110391.69630@i13g2000prf.googlegroups.com> Message-ID: On Sat, 28 Jul 2007 03:10:32 +0000, GreenH wrote: > I get some string as below from a library method (qt3 > QDropEvent.data()) I use. > file:///C:/Documents%20and%20Settings/Username/My%20Documents/45-61-Abc%20fold-%20den.vru > > I need file path on my system, for the above example: > C:/Documents and Settings/Username/My Documents/45-61-Abc fold- > den.vru > > I am doing the below, it doesn't look pythonic, > can someone suggest any elegant solution, which is not too cryptic to > understand? yep, I do care about readability of the code to average > python user :) Try this: import urlparse, sys fileURLname = ("file:///C:/Documents%20and%20Settings/Username/" "My%20Documents/45-61-Abc%20fold-%20den.vru") pathname = urlparse.urlparse(fileURLname)[2] if sys.platform == "win32": import nturl2path clean = nturl2path.url2pathname(pathname) else: import urllib clean = urllib.unquote(pathname) print clean > -------------------- > tmpTuple = urlparse.urlparse(fileURLname) > > tmpString = tmpTuple[2].strip('/\\') > > fileName = urllib.unquote(tmpString) > > #For some reason the string contained in 'fileName' has some > unprintable trailing characters, Any ideas on that? It works for me: No trailing characters at all, printable or otherwise. >>> len(fileName.split('.vru', 1)[1]) 0 -- Steven. From miki.tebeka at gmail.com Wed Jul 18 10:51:05 2007 From: miki.tebeka at gmail.com (Miki) Date: Wed, 18 Jul 2007 14:51:05 -0000 Subject: Break up list into groups In-Reply-To: <1184620307.340479.253430@z28g2000prd.googlegroups.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> Message-ID: <1184770265.902718.213910@e9g2000prf.googlegroups.com> Hello Dan, Yet another option (using itertools.groupby): from itertools import groupby class GrouperToggler: def __init__(self): self.group = 1 def __call__(self, value): # New packet, toggle group if value & 0x80: self.group = 1 - self.group return self.group def group(items): for group, items in groupby(items, GrouperToggler()): # groupby return [key, group_iterator] yield [item for item in items] i = [ 0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, 13, 0xF0, 14, 0xF1, 15 ] for g in group(i): print g HTH, -- Miki http://pythonwise.blogspot.com From python at jayloden.com Tue Jul 31 22:23:18 2007 From: python at jayloden.com (Jay Loden) Date: Tue, 31 Jul 2007 22:23:18 -0400 Subject: Finding documentation (WAS: Iteration over strings) In-Reply-To: References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> <46AF7A49.3040804@jayloden.com> <46AF8046.7090702@gmx.net> <496954360707311307y7d503b8eybd72795c8e699104@mail.gmail.com> <46AF9B2D.8040501@jayloden.com> <46AF9F55.20105@gmx.net> <46AFA1D9.1010707@gmx.net> <46AFCB8C.9060800@jayloden.com> Message-ID: <46AFEE96.5050007@jayloden.com> Steve Holden wrote: > In this particular case the documentation is quite explicit about the > return value and the documentation for the function runs to almost 400 > words. Do you expect *everything* to be in the source? That isn't > practical, as documenting everything twice like that makes twice the > work when the function changes and the documentation has to be rewritten. (starting a new thread so that we're not off topic for the original one) Hmmm. Jerry Hill pointed out also that this information is documented clearly in the online docs (as opposed to docstrings I was looking at with pydoc). I guess I'm just confused about the purpose of pydoc and module documentation. I was under the impression it was intended to serve as the API reference, so when people say "consult the documentation" I usually check pydoc first before hitting the web browser. I was under the impression earlier that docs.python.org was mostly generated from the docstrings similar to how javadocs are converted to html. That being said, it does make sense to me however that you should be able to use pydoc to tell you simple things like the return value of a function, the required parameters, etc. I'd be interested to hear from some more experienced programmers what your typical usage would be when reference documentation for a given module. Are the HTML docs (e.g. what's on http://docs.python.org/) the canonical source? Is that where I should generally be looking? Are there other documentation resources you all have found useful as well? I'm curious to see if there are useful resources I'm just missing due to lack of knowledge or experience. Thanks, -Jay From lew at lewscanon.nospam Thu Jul 12 10:16:20 2007 From: lew at lewscanon.nospam (Lew) Date: Thu, 12 Jul 2007 10:16:20 -0400 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <873aztltwq.fsf@benfinney.id.au> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <873aztltwq.fsf@benfinney.id.au> Message-ID: <1rGdnWBTvMgpqgvbnZ2dnUVZ_sLinZ2d@comcast.com> Ben Finney wrote: > [0] Left unqualified, referring to a site named "Wiki" refers to *the* > Wiki, at . If you mean some other > subsequent Wiki site, you'll need to be more specific. I'm betting they meant or one of its non-English siblings. -- Lew From doulos05 at gmail.com Mon Jul 16 13:25:48 2007 From: doulos05 at gmail.com (JonathanB) Date: Mon, 16 Jul 2007 10:25:48 -0700 Subject: Discover instance variables Message-ID: <1184606748.599294.293570@n60g2000hse.googlegroups.com> Ok, I know there has to be a way to do this, but my google-fu fails me (once more). I have a class with instance variables (or should they be called attributes, I'm newish to programming and get really confused with OO sometimes), like the one in this example: class Foo(): self.a = "bar" self.z = "test" self.var = 2 foo = Foo() I want to print a list of the variables (strings, integers, etc) in Foo, without knowing their names. So that the user who needs to change a peice of information can view the variable list, enter the name of the variable they need to change and then make the change. This is what I'd like a sample run to look like: Attributes for foo: a = bar z = test var = 2 Change: a New value: foobar Change made! I can handle the formatting and changing the variable itself, no problem, but how do I get a list of all the variables in a class instance? I almost put a list in there called vars and appended all the variables to it so I could iterate the list, but this sounds like something useful enough that someone has come up with a better way to do it than that. It almost looks like self.__dir__() is what I want, but that returns methods as well, correct? I only want variables, but I can't think of how to do a list comprehension that would remove the methods. JonathanB From siegfried at heintze.com Thu Jul 5 00:41:13 2007 From: siegfried at heintze.com (Siegfried Heintze) Date: Wed, 4 Jul 2007 22:41:13 -0600 Subject: IDEs for COM scripting: C# v. Python v. Iron Python v. JPython Message-ID: I love the typing assist I get when using C# in VS2005 to write COM clients. I need to write a program to automate some tasks in outlook. Givin that the typing assist feature is very important to me, what would be the best combination of IDE and language for COM scripting? I was experimenting with Groovy and Eclipse and was extremely pleased to discover that I get the typing assist with that combination. However, I'm getting an accvio with a minimal outlook COM client. I hear great things about Iron Python: is there a good IDE for it that has a typing assist? Thanks, Siegfried From email at christoph-haas.de Fri Jul 13 14:52:49 2007 From: email at christoph-haas.de (Christoph Haas) Date: Fri, 13 Jul 2007 20:52:49 +0200 Subject: A Python newbie ask a simple question In-Reply-To: <1184351716.298630.80670@z28g2000prd.googlegroups.com> References: <1184351716.298630.80670@z28g2000prd.googlegroups.com> Message-ID: <20070713185249.GC11852@torf.workaround.org> On Fri, Jul 13, 2007 at 06:35:16PM -0000, xing93111 at gmail.com wrote: > what does the statement "choice = raw_input(prompt)[0]" mean? I don't > know why there is a '[0]' in the statement. It calls the "raw_input" function with the argument of "prompt". That function returns a list and you are getting the first ([0]) value from that list. Cheers Christoph From bignose+hates-spam at benfinney.id.au Thu Jul 26 02:21:16 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Jul 2007 16:21:16 +1000 Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> <1185425463.796350.128550@i13g2000prf.googlegroups.com> Message-ID: <874pjrit2b.fsf@benfinney.id.au> "mensanator at aol.com" writes: > On Jul 25, 8:54?pm, Steven D'Aprano > wrote: > Any number of whitespace characters? Just spaces or all whitespace > characters? > What about searching source code files? What's the regular > expression for locating a number with an arbitrary number of digits > seperated into an arbitrary number of blocks of an arbitray number > of digits with an arbitrary number of whitespace characters between > each block? These issues all exist for implicitly concatenated string literals. It seems the same rules would apply; that would both make sense from an implementation standpoint, and result in consistency for the Python programmer too. -- \ "Are you pondering what I'm pondering?" "I think so, Brain, but | `\ wouldn't his movies be more suitable for children if he was | _o__) named Jean-Claude van Darn?" -- _Pinky and The Brain_ | Ben Finney From steve at holdenweb.com Mon Jul 30 06:38:23 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Jul 2007 06:38:23 -0400 Subject: wxGlade: Who knows how to drive this application? In-Reply-To: <200707300646.l6U6k03P029079@dit.unitn.it> References: <200707300646.l6U6k03P029079@dit.unitn.it> Message-ID: <46ADBF9F.3040404@holdenweb.com> Alberto Griggio wrote: >> Here are some things I can think of, in no particular order: > > Thanks! I can't promise I'll take care of all of them (some are nontrivial > to implement, and would probably take a lot of time), but this list is > definitely valuable (e.g. I can circulate it through the other developers > to see if there's any volunteer...) > Roel's list is clearly based on much more experience than I have with wxGlade, and is pretty much a superset of mine. You are right, that is valuable feedback for a developer. Sorry ny own comments were less directed. 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 Tue Jul 24 00:01:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Jul 2007 01:01:08 -0300 Subject: idiom for RE matching References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> <1185157313.356112.159020@z24g2000prh.googlegroups.com> <2f6dnUlUxd2_7TjbnZ2dnUVZ_qy3nZ2d@comcast.com> Message-ID: En Tue, 24 Jul 2007 00:23:46 -0300, Gordon Airporte escribi?: > mik3l3374 at gmail.com wrote: >> if your search is not overly complicated, i think regexp is not >> needed. if you want, you can post a sample what you want to search, >> and some sample input. > > I'm afraid it's pretty complicated :-). I'm doing analysis of hand > histories that online poker sites leave for you. Here's one hand of a > play money ring game: > > > Full Tilt Poker Game #2042984473: Table Play Chip 344 - 10/20 - Limit > Hold'em - 18:07:20 ET - 2007/03/22 > Seat 1: grandmarambo (1,595) > Seat 4: justnoldfoolm (2,430) > justnoldfoolm posts the small blind of 5 > rickrn posts the big blind of 10 > The button is in seat #1 > *** HOLE CARDS *** > Dealt to moi [Jd 2c] > justnoldfoolm bets 10 > [more sample lines] > > So I'm picking out all kinds of info about my cards, my stack, my > betting, my position, board cards, other people's cards, etc. For > example, this pattern picks out which player bet and how much: > > betsRe = re.compile('^(.*) bets ([\d,]*)') > > I have 13 such patterns. The files I'm analyzing are just a session's > worth of histories like this, separated by \n\n\n. All of this > information needs to be organized by hand or by when it happened in a > hand, so I can't just run patterns over the whole file or I'll lose > context. > (Of course, in theory I could write a single monster expression that > would chop it all up properly and organize by context, but it would be > next to impossible to write/debug/maintain.) But you don't HAVE to use a regular expression. For so simple and predictable input, using partition or 'xxx in string' is around 4x faster: import re betsRe = re.compile('^(.*) bets ([\d,]*)') def test_partition(line): who, bets, amount = line.partition(" bets ") if bets: return who, amount def test_re(line): r = betsRe.match(line) if r: return r.group(1), r.group(2) line1 = "justnoldfoolm bets 10" assert test_re(line1) == test_partition(line1) == ("justnoldfoolm", "10") line2 = "Uncalled bet of 20 returned to justnoldfoolm" assert test_re(line2) == test_partition(line2) == None py> timeit.Timer("test_partition(line1)", "from __main__ import *").repeat() :2: SyntaxWarning: import * only allowed at module level [1.1922188434563594, 1.2086988709458808, 1.1956522407177488] py> timeit.Timer("test_re(line1)", "from __main__ import *").repeat() :2: SyntaxWarning: import * only allowed at module level [5.2871529761464018, 5.2763971398599523, 5.2791986132315714] As is often the case, a regular expression is NOT the right tool to use in this case. -- Gabriel Genellina From carsten at uniqsys.com Wed Jul 18 09:09:22 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 18 Jul 2007 09:09:22 -0400 Subject: accessing javascript variables within psp code In-Reply-To: <1184722167.222423.273040@z28g2000prd.googlegroups.com> References: <1184722167.222423.273040@z28g2000prd.googlegroups.com> Message-ID: <1184764162.3385.29.camel@dot.uniqsys.com> On Wed, 2007-07-18 at 01:29 +0000, BAnderton wrote: > Hello all, > > Question: Is there any way to access a javascript variable from > within psp code? > > > I'm aware of how to do the reverse of this (js_var='<%=psp_var%>'). > > > Here's a non-working example of what I'm trying to do: > > > - - - (begin example) - - - > > > function Test(txt) > { > a = confirm('Are you sure you want to delete '+txt+'?') > if (a) > { > //The problem is getting the value of js variable 'txt' recognized in > "psp space". > <% > os.remove( os.path.join(os.path.dirname(req.filename), '../notes/'+ > %>txt<%) ) > %> > > > } > } > > > - - - (end example) - - - > > FYI, I've already found a workaround for the above example (by placing > a "get" variable in the URL, reloading the page, and having psp check > for the existence of that variable before proceeding with deleting the > appropriate file) but I'd still like this general capability for > future projects. I've searched several forums, websites, etc. and > the > answer has aluded me for two days now. I'm new to apache, mod_python, > and javascript, so this may be ridiculously simple. >From your vague description it sounds like the contents of your JavaScript variable come from the server to begin with. In that case it's easier and more secure to "remember" the correct value on the server instead of sending it to the client and trusting the client[*] to send the same value back. To store variables on the server side between requests by the same client, use session variables. [*] A basic premise of web programming is that the client can't be trusted: Don't trust that maximum form field sizes will be honored, don't trust that cookies won't be changed, don't trust that GET parameters won't be changed, don't trust that hidden form fields won't be changed, etc. HTH, -- Carsten Haese http://informixdb.sourceforge.net From socialanxiety at gmail.com Sun Jul 8 20:06:48 2007 From: socialanxiety at gmail.com (socialanxiety at gmail.com) Date: Sun, 08 Jul 2007 17:06:48 -0700 Subject: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc) Message-ID: <1183939608.088756.178320@m37g2000prh.googlegroups.com> i hope someone here can help me. basically, me and my friend have a summer project. in this project, we need something that would basically function as a blender. we know we'll need to buy a motor that spins, but what we're having trouble with is figuring out how to program it. we want to be able to control the speed of the motor. how would we accomplish this? i'm new to all of this, so i'm having a hard time wrapping my mind around how it'd be possible to program one of those things :\ ex: what if i want the motor to turn for 10 seconds. stop for 5. then turn the other direction. would you program it the same way you would on a personal computer (via c, python, etc)? From steve at holdenweb.com Sat Jul 21 08:56:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 21 Jul 2007 08:56:36 -0400 Subject: Pickled objects over the network In-Reply-To: <012901c7cb60$5ba530c0$03000080@hendrik> References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com><011401c7caa0$3e3e5900$03000080@hendrik> <012901c7cb60$5ba530c0$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "Steve Holden" wrote: > >> Hmm, I suspect I detect the sounds of the square wheel being reinvented. > > Very helpful, thank you, Steve - Now how about pointing out in which > direction the round wheels are kept, and what their monikers are? > I think someone has already pointed out netstrings, which will allow you to send arbitrary strings over network connections deterministically. I'm afraid for the rest it's just a matter of encoding your information in a way that you can decode without allowing a malicious sender to cause arbitrary code to be called. The issue with pickle is that it's way too general a mechanism to be secure in open network applications, so a suggestion to beef up its security was misguided. Trying to "beef up pickle's security" is like trying to make a shotgun that can't kill anything. 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 http Mon Jul 2 01:00:21 2007 From: http (Paul Rubin) Date: 01 Jul 2007 22:00:21 -0700 Subject: Reversing a string References: <1182997438.541012.54100@o61g2000hsh.googlegroups.com> <1i0kjpx.wjw44j15np22dN%aleax@mac.com> Message-ID: <7xr6nrjt7e.fsf@ruckus.brouhaha.com> Martin Durkin writes: > Is it just a matter of reading *all* the documentation before I start > coding? It's worth spending an hour or two reading through the library manual, yes. From tjreedy at udel.edu Tue Jul 10 18:24:38 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 10 Jul 2007 18:24:38 -0400 Subject: bool behavior in Python 3000? References: Message-ID: "Alan Isaac" wrote in message news:z0Oki.1782$YH3.1751 at trnddc08... | Is there any discussion of having real booleans | in Python 3000? Say something along the line | of the numpy implementation for arrays of type 'bool'? As far as I know, there is no such discussion among the developers. Clp is always a different matter ;-) From cito at online.de Thu Jul 5 15:38:18 2007 From: cito at online.de (Christoph Zwerschke) Date: Thu, 05 Jul 2007 21:38:18 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: References: Message-ID: Neil Cerutti wrote: > You may need the traceback module to get at the error message, if > trying to read e.message can fail. > > Something like this mess here: ;) > > ... > except Exception, e: > etype, evalue, etb = sys.exc_info() > ex = traceback.format_exception_only(etype, evalue) > message = ex[0].partition(':')[2].strip() > raise etype, message+". Sorry!", etb > > Note that the above will break for SyntaxError (who's message > contains more than one line) and any kind of exception that > doesn't inherit from Exception. That's actually similar to what I was using in Kid already. The problem is that there are some Exceptions which cannot be instantiated with a single string argument, such as UnicodeDeocdeError. Please try the above with "unicode('\xe4')" instead of the dots. Instead of re-raising the UnicodeDecodeError, you will get a TypeError because of this problem. -- Chris From josiah.carlson at sbcglobal.net Wed Jul 4 11:28:46 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Wed, 04 Jul 2007 15:28:46 GMT Subject: CGI vs WSGI In-Reply-To: <1183553365.160758.29320@q75g2000hsh.googlegroups.com> References: <1183553365.160758.29320@q75g2000hsh.googlegroups.com> Message-ID: tuom.larsen at gmail.com wrote: > I'm wondering because the only variables I ever needed were PATH_INFO, > REQUEST_METHOD, QUERY_STRING and maybe one more, all of which should > be available from CGI, too. CGI starts up a new process for every request, using stdin/stdout for passing information. I believe WSGI can do that, but I believe it can also do in-process requests (think mod_python, only with a Python web server), external process requests (think FastCGI or LRWP), etc. I could certainly be mistaken, it's been a while since I looked into any of it. - Josiah From nis at superlativ.dk Fri Jul 6 00:24:03 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Fri, 06 Jul 2007 06:24:03 +0200 Subject: Where is the syntax for the dict() constructor ?! In-Reply-To: References: <468D1D9D.6060002@gmail.com> <468D3445.2060408@gmail.com> <468d49ff$0$90264$14726298@news.sunsite.dk> Message-ID: <468dc420$0$90269$14726298@news.sunsite.dk> Wildemar Wildenburger skrev: > Nis J?rgensen wrote: >> Neil Cerutti skrev: >> >> >>> Mostly you can use the default 'excel' dialect and be quite >>> happy, since Excel is the main reason anybody still cares about >>> this unecessarily hard to parse (it requires more than one >>> character of lookahead for no reason except bad design) data >>> format. >>> >> >> I knew there had to be a reason why everyone is using xml these days ... >> >> Nis >> > Are you serious? No. Nis From martin at v.loewis.de Mon Jul 9 19:11:40 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 10 Jul 2007 01:11:40 +0200 Subject: PyXML not installing? In-Reply-To: <1184013983.166849.32100@n2g2000hse.googlegroups.com> References: <1184013983.166849.32100@n2g2000hse.googlegroups.com> Message-ID: <4692c0ac$0$25817$9b622d9e@news.freenet.de> > error: Python was built with Visual Studio 2003; > extensions must be built with a compiler than can generate compatible > binaries. > Visual Studio 2003 was not found on this system. If you have Cygwin > installed, > you can try compiling with MingW32, by passing "-c mingw32" to > setup.py. > > It gives me the above error message. Any way to fix this? Do what the message tells you. Either install Visual Studio 2003, or MingW32. Regards, Martin From rustompmody at gmail.com Wed Jul 18 13:16:52 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 18 Jul 2007 22:46:52 +0530 Subject: Pickled objects over the network In-Reply-To: <9c8d48280707180812q4343bcbaodbc803e9c9a92acb@mail.gmail.com> References: <9c8d48280707171457p4448fdf3of40562bf62a18fc6@mail.gmail.com> <9c8d48280707180812q4343bcbaodbc803e9c9a92acb@mail.gmail.com> Message-ID: Sure pyro may be the solution but it may also be overkill Why not use safe_load from the yaml module? From ebankgame at gmail.com Sun Jul 15 12:48:06 2007 From: ebankgame at gmail.com (www.ebankgame.com) Date: Sun, 15 Jul 2007 16:48:06 -0000 Subject: www.eBankGame.com Buy WoW gold RS gold WG k gold Lotro gold Message-ID: <1184518086.929821.279210@o11g2000prd.googlegroups.com> www.eBankGame.com Buy WoW gold RS gold WG k gold Lotro gold http://www.eBankGame.com (w w w .e BankGame . c o m ) As you might or might not known that Taiwan earthquake has caused most of supplier are experiencing the serve problem to process the gold. However, eBankGame is always stay line with all the game players to help you guys to enjoy the game at any time. We provide Gold Farmer service for you to own the gold with little bit expense. Your expense will be more valuable by take one action and gain multiple purposes. The service is focus on gold farming for your character in the game by using professional human player to taking tasks and gain reputation in the game in order to gain the gold for you (We do not apply any plug- in or Bots on your character). Meanwhile your character will beimproved 1-15 power leveling which depends on your original level(this aspect is not available for Level 60). www.eBankGame.com (w w w .e BankGame . c o m) 1.The Fastest Delivery Speed on all Servers in 1-8 hours since your payment arrives.If the deliver is delayed over 8 hours, you will get 5% extra gold for the late.Or you can request a refund. 2.Special Discount Servers.Sometimes, there will be some servers, with special discounts, with extremely NICE PRice on some certain servers. 3.Perfect Service.24 hours service with various contact methods: MSN, ICQ, Online Chat on Web homepage,Welcome to www.eBankGame.com If any problem, please contact us asap! Happy shopping! Sincerely, http://www.eBankGame.com E-mail:ebankgame at gmail.com MSN:ebagame2010 at msn.com ICQ:468873592 Choose your game World of Warcraft EU World of Warcraft US Lord of The Rings Online EU Lord of The Rings Online US Lineage II EverQuest2 Guild Wars Final Fantacy XI Runescape 2 RFO Online Dungeons & Dragons Online Eve Online Star Wars Galaxies go to http://www.eBankGame.com From cfbolz at gmx.de Sun Jul 29 07:45:25 2007 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sun, 29 Jul 2007 13:45:25 +0200 Subject: 128 or 96 bit integer types? In-Reply-To: <7xlkd1ugvn.fsf@ruckus.brouhaha.com> References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com> <1185562901.206212.52570@j4g2000prf.googlegroups.com> <1185607142.096574.209200@e16g2000pri.googlegroups.com> <7xlkd1ugvn.fsf@ruckus.brouhaha.com> Message-ID: <46AC7DD5.9020201@gmx.de> Paul Rubin wrote: > "mensanator at aol.com" writes: >> has 146 digits. And that's just the begining. The above >> actually represents a polynomial with 264 terms, the >> exponents of which range from 0 to 492. One of those >> polynomials can have over 50000 decimal digits when >> solved. > > You should use gmpy rather than python longs if you're dealing with > numbers of that size. > Python multiplication uses a straightforward > O(n**2) algorithm where n is the number of digits. That's untrue since quite a while. CPython now uses Karatsuba-multiplication if the number of digits is larger than a certain threshold. Karatsuba is O(n**(log(3) / log(2)). > This is the best > way for up to a few hundred or maybe a few thousand digits. After > that, it's better to use more complicated FFT-based algorithms which > are O(n log n) despite their increased constant overhead. Gmpy does this. Karatsuba is still slower than these algorithms, but only if you have quite a big number of digits. Of course the core of your argument remains valid: CPython is not up to providing extremely good big integer arithmetic, so if you have extreme needs, you shouldn't use the builtin longs. Cheers, Carl Friedrich Bolz From http Mon Jul 30 19:15:53 2007 From: http (Paul Rubin) Date: 30 Jul 2007 16:15:53 -0700 Subject: Comparing Dictionaries References: <1185611025.943782.162330@w3g2000hsg.googlegroups.com> Message-ID: <7xzm1dqy8m.fsf@ruckus.brouhaha.com> Kenneth Love writes: > I will search on Google for more info on Doctest. Doctest is recent. Try: http://python.org/doc/lib/module-doctest.html Diveintopython should probably be updated to use doctest instead of unittest. unittest is Java-descended and doesn't fit into Python as well as doctest does. From conra2004 at yahoo.com Mon Jul 23 14:44:41 2007 From: conra2004 at yahoo.com (yadin) Date: Mon, 23 Jul 2007 11:44:41 -0700 Subject: link between python and the windows command prompt Message-ID: <1185216281.296805.191660@q75g2000hsh.googlegroups.com> hi! i need to know how i can run ussal commands that i ussally type at the windows command prompt from a python file. that is for example from the windows command prompt i ussually type "cd D:\folder\ nec2++ - i inputfile.nec -o outputfile.out " now how can i execute this command that i ussually type at the windows command prompt from a python file? i know it has to do with the sys and os module but how specifically? what commands? any references? From tleeuwenburg at gmail.com Wed Jul 25 03:00:01 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: Wed, 25 Jul 2007 07:00:01 -0000 Subject: Base class for file-like objects? (a.k.a "Stream" in Java) In-Reply-To: <1185330503.115918.41520@z24g2000prh.googlegroups.com> References: <1185317490.607920.100200@z24g2000prh.googlegroups.com> <1185330503.115918.41520@z24g2000prh.googlegroups.com> Message-ID: <1185346801.387250.171150@g12g2000prg.googlegroups.com> On Jul 25, 12:28 pm, Asun Friere wrote: > On Jul 25, 8:51 am, Boris Du?ek wrote: > > > In Python, I found that "file" objects exist. While specifying > > argument types in Python is not possible as in Java, it is possible to > > check whether an object is an instance of some class and that's what I > > need - I need to check if an argument is a "file"-like object, and if > > yes, behave accordingly, if not, treat the argument as string with > > URL. > > > But I am afraid there is no such a base class - I tried the following: > > Yup you are right. Look.>>> type(g).mro() > > [, ]>>> type(f).mro() > > [, ] > > "File-like object" refers the the behaviour of the object, not it's > inheritance. Python is an equal opportunity employer, we don't ask > and object what race it is, we simply ask "can you do the job?" This > is known colloquially as "duck-typing." In other words Python has > 'polymorphism by interface,' in contradistinction to Java's > 'polymorphism by implementation.' Until you understand this you will > be trying to write Java in Python, and you will not have much joy. > > > P.S.: The code should finally look in esence something like this: > > > if isinstance(f, file): > > pass > > elif isinstance(f, string): > > f = urllib.urlopen(f) > > else: > > raise "..." > > process_stream(f) > > Because of duck-typing, you should almost never use the isintance() > (or type(), hasattr(), or any others that don't immediately come to > mind ...) in actual code. It (usually) breaks Python's polymorphism! > If you find these methods popping up in your code it strongly > indicates that you should be using a try/except statement, if not a > complete change of your code's logic. Search for LBYL (look before > you leap) vs EAFP (easier to ask forgiveness than permission) for a > full explanation. > > I'm not sure why you would ever be sending a file object to urlopen > (or is the test isinstance(f, file) supposed to test for an already > opened url?), but you final code should actually look more like > something along these lines: > > try : > f = urlopen(f) > except AttributeError : > pass > > This is not as elegant as it could be, as it will pass not only on > open files (or urls), but on any type that lacks the .strip method > (ie. it doesn't account for your else condition). You'd probably have > to catch an exception later when you try to use what should be an open > url, or rewrite your code not to get in this position in the first > place. But however you refactor your code, it is advisable to > concentrate on what an object can do (and catch an exception where it > fails to perform), rather on the type of the object. I agree that using try statements is often, perhaps usually, a good idea. That said... One good reason to avoid using a try: except: methodology is if the actions taken in the try block could potentially modify data structures or the underlying data during processing, or if the action to be tried is expensive. Being able to check before taking an action that it will be safe can be important. In these cases, you can use isinstance. Python 3k, I believe, is thinking of being able to implement Abstract Base Classes for this very reason. As things stand, however, you will not be able to catch all cases with a simple isinstance call. Try except should work in almost all cases. If you want to do your own duck-typing, you can use dir(object) to get its methods and check whether what you need is in there. Anyway, good luck with it. From aleax at mac.com Wed Jul 4 23:23:33 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 4 Jul 2007 20:23:33 -0700 Subject: PyRun_String using my module in a def References: <1183601931.930115.132400@n2g2000hse.googlegroups.com> Message-ID: <1i0qtvm.sq102f16mpe7tN%aleax@mac.com> Stuart wrote: ... > PyObject *rstring = PyRun_String( cmd, Py_file_input, main_dict, > dlfl_dict ); You're passing difl_dict as the "locals" to PyRun_String -- but a function has its own locals, so it won't use those locals. Just update main_dict with difl_dict (that's the equivalent of the "from difl import *" which you appear to desire) and use main_dict for both globals and locals in your PyRun_String call. Alex From rcdailey at gmail.com Mon Jul 9 15:59:24 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 09 Jul 2007 19:59:24 -0000 Subject: Distributing python apps Message-ID: <1184011164.346200.9330@q75g2000hsh.googlegroups.com> Hi, I'm creating a set of command-line tools using Python. These tools manage resources for a game I'm working on. However, many people that will be using these tools will not want to install Python on their machines. This would be a very tedious process (for first time users of my tools). Ideally, I would like for someone to be able to use my tools without having to install Python. For example, if I could put python.exe in a hidden folder somewhere in my tools directory, and make a batch file that they run to start the tool, python could be executed from a relative path in my tools directory. Is this possible? What is an ideal way of distributing python apps? I would prefer a transparent and user-friendly approach. Thanks for any tips. From deets at nospam.web.de Tue Jul 10 10:12:03 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 10 Jul 2007 16:12:03 +0200 Subject: Get a filename list of a web site References: <1184058732.163303.96300@q75g2000hsh.googlegroups.com> <1184070085.921709.219020@r34g2000hsd.googlegroups.com> <1184073480.953485.12180@d55g2000hsg.googlegroups.com> Message-ID: <5fhidjF3bf54dU1@mid.uni-berlin.de> aidechamp at yahoo.it wrote: > Thanks, faulkner, > years ago I used on Windows Teleport, which had the possibilty to > download > only the file list. I hoped that in Linux with the aid of python & > wget.... ssh. Runs on nearly all linuxes. Diez From mccredie at gmail.com Tue Jul 17 13:48:53 2007 From: mccredie at gmail.com (Matimus) Date: Tue, 17 Jul 2007 17:48:53 -0000 Subject: Break up list into groups In-Reply-To: <1184620307.340479.253430@z28g2000prd.googlegroups.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> Message-ID: <1184694533.380918.169640@m37g2000prh.googlegroups.com> I did some more experimenting and came up with the code below. It shows several methods. When run, the script tests the robustness of each method (roughly), and profiles it using timeit. The results from running on my laptop are shown below the code. seqs = [# Original: [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, 13, 0xF0, 14, 0xF1, 15], # Single entry: [0xF0, 1, 2, 3], # empty [], # No values with 0x80 set [1, 2, 3, 14, 15], # Does not start with a value that has 0x80 set [1, 2, 3, 14, 15, 0xF0, 1, 2, 3]] expected = [# Original: [[0xF0, 1, 2, 3], [0xF0, 4, 5, 6], [0xF1, 7, 8], [0xF2, 9, 10, 11, 12, 13], [0xF0, 14], [0xF1, 15]], # Single entry: [[0xF0, 1, 2, 3]], # empty [], # No values with 0x80 set [], # Does not start with a value that has 0x80 set [[0xF0, 1, 2, 3]]] def gengroups0(seq): group = None for val in seq: if val & 0x80: if group: yield group group = [] try: group.append(val) except AttributeError: pass if group: yield group def getgroups0(seq): groups = [] group = None for val in seq: if val & 0x80: if group: groups.append(group) group = [] try: group.append(val) except AttributeError: pass if group: groups.append(group) return groups def gengroups1(seq): idxs = [i for i,v in enumerate(seq) if v&0x80] for i,j in zip(idxs,idxs[1:]+[None]): yield seq[i:j] def getgroups1(seq): idxs = [i for i,v in enumerate(seq) if v&0x80] return [seq[i:j] for i,j in zip(idxs,idxs[1:]+[None])] # Similar to the partition method on strings def partition(seq,f=None): if f is None: f = lambda x:x for i,v in enumerate(seq): if f(v): return seq[:i],[seq[i]],seq[i+1:] return seq,[],[] def rpartition(seq, f=None): if f is None: f = lambda x:x for i,v in zip(range(len(seq)-1,-1,-1),seq[::-1]): if f(v): return seq[:i],[seq[i]],seq[i+1:] return ([],[],seq) def gengroups2(seq): while seq: seq, key, val = rpartition(seq, lambda x: x&0x80) if key and val: yield key+val def getgroups2(seq): groups = [] while seq: seq, key, val = rpartition(seq, lambda x: x&0x80) if key and val: groups.append(key+val) return groups def getgroups3(seq): groups = [] for i in seq: if 0x80 & i: groups.append([i]) else: groups[-1].append(i) return [x for x in groups if x] seq = seqs[0] if __name__ == "__main__": from timeit import Timer import __main__ for i in range(4): fname = "getgroups"+str(i) f = getattr(__main__,fname) print fname for i,(s,e) in enumerate(zip(seqs,expected)): print "test %d:"%i, try: if f(s) == e: print "pass" else: print "fail" except: print "error" t = Timer(fname+'(seq)', 'from __main__ import seq,'+fname) print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/ 100000) print Output from running the above: getgroups0 test 0: pass test 1: pass test 2: pass test 3: pass test 4: pass 14.85 usec/pass getgroups1 test 0: pass test 1: pass test 2: pass test 3: pass test 4: pass 13.81 usec/pass getgroups2 test 0: fail test 1: pass test 2: pass test 3: pass test 4: pass 56.38 usec/pass getgroups3 test 0: pass test 1: pass test 2: pass test 3: error test 4: error 16.23 usec/pass `getgropus2' fails test 0 because it produces a reversed list. That can easily be fixed by re-reversing the output before returning. But, since it is by far the slowest method, I didn't bother. `getgroups3' is a method I got from another post in this thread, just for comparison. >From my benchmarks it looks like getgroups1 is the winner. I didn't scour the thread to test all the methods however. From stargaming at gmail.com Fri Jul 13 13:56:21 2007 From: stargaming at gmail.com (Stargaming) Date: Fri, 13 Jul 2007 19:56:21 +0200 Subject: NoneType object not iterable In-Reply-To: References: Message-ID: <4697bcc6$0$25761$9b622d9e@news.freenet.de> tom at finland.com schrieb: > Hi! > My code is > > > db = {} > > > >> def display(): >> keyList = db.keys() >> sortedList = keyList.sort() >> for name in sortedList: >> line = 'Name: %s, Number: %s' % (name, db[name]) >> print line.replace('\r', '') > > > And it gives following error: > >> for name in sortedList: >> TypeError: 'NoneType' object is not iterable > > > How can sortedList variable turn into NoneType? I just don't get it... It does not turn into something. The `sort()` method just works "in place", i. e. it will mutate the list it has been called with. It returns None (because there is no other sensible return value). For you, that means: You don't have to distinguish between keyList and sortedList. Just call ``.sort()`` on keyList and it will just work. HTH, Stargaming P.S. same information is in the docs: http://docs.python.org/lib/typesseq-mutable.html From malaclypse2 at gmail.com Tue Jul 31 17:11:04 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 31 Jul 2007 17:11:04 -0400 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: <16651e80707311411s2543a01ya14e493b65011fd6@mail.gmail.com> On 7/31/07, 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') Using the csv module gets you most of the way there. For instance: >>> import csv >>> text = r'abc "xy z" "1 2 3" "a \" x"' >>> reader = csv.reader([text], delimiter=" ", escapechar='\\') >>> for row in reader: print row ['abc', 'xy z', '', '1 2 3', '', 'a " x'] >>> That does leave you with empty elements where you had double spaces between items though. you could fix that with something like: >>> for row in reader: row = [element for element in row if element != ''] print row ['abc', 'xy z', '1 2 3', 'a " x'] >>> The CSV module can handle lots of delimited data other that quote and comma delimited. See the docs at: http://docs.python.org/lib/module-csv.html and PEP 305: http://www.python.org/dev/peps/pep-0305/ -- Jerry From bj_666 at gmx.net Thu Jul 26 13:15:30 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 26 Jul 2007 17:15:30 GMT Subject: is_iterable function. References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> <5uNpi.36822$G23.3430@newsreading01.news.tds.net> Message-ID: <5gs35iF3gbvuoU1@mid.uni-berlin.de> On Thu, 26 Jul 2007 15:02:39 +0000, Neil Cerutti wrote: > Based on the discussions in this thread (thanks all for your > thoughts), I'm settling for: > > def is_iterable(obj): > try: > iter(obj).next() > return True > except TypeError: > return False > except KeyError: > return False > > The call to iter will fail for objects that don't support the > iterator protocol, and the call to next will fail for a > (hopefully large) subset of the objects that don't support the > sequence protocol. And the `next()` consumes an element if `obj` is not "re-iterable". Ciao, Marc 'BlackJack' Rintsch From tchur at optushome.com.au Wed Jul 18 22:52:35 2007 From: tchur at optushome.com.au (Tim Churches) Date: Thu, 19 Jul 2007 12:52:35 +1000 Subject: how to implementation latent semantic indexing in python.. In-Reply-To: <1i1gnc8.1yuwax3eieex3N%aleax@mac.com> References: <1184803885.142218.152490@g12g2000prg.googlegroups.com> <1i1gnc8.1yuwax3eieex3N%aleax@mac.com> Message-ID: <469ED1F3.7060508@optushome.com.au> Alex Martelli wrote: > Tim Churches wrote: > >> malkarouri wrote: >>> On 13 Jul, 17:18, 78ncp wrote: >>>> hi... >>>> how to implementation algorithm latent semantic indexing in python >>>> programming...?? >>> Of course you are aware that LSA is patented.. >> There is a US patent on it, sealed in 1989, but is it patented in any >> other countries? There is no such thing as a "global patent" - patents >> only cover the country which issues them. There is a global patent >> application process (the Patent Co-operation Treaty), but that just >> establishes a priority date for the invention in each country, but the >> inventor still needs to file patent applications and have them approved >> (sealed) is each and every country. Did Bellcore do that back in the 1980s? > > Aren't patents supposed to last 17 years, anyway? A patent granted in > 1989 should have expired in 2006, I believe (though IANAL, so...). I thought that in the US utility patents (as opposed to plant and circuit design patents) lasted for 20 years from the filing date, which was 15th Sept 1988 for the patent in question (http://www.google.com/patents?vid=USPAT4839853 ). But IANAL either. Tim C From steve at holdenweb.com Sun Jul 8 20:34:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 08 Jul 2007 20:34:40 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xvecumrte.fsf@ruckus.brouhaha.com> References: <5dveb4F360un0U1@mid.individual.net> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steven D'Aprano writes: >> As far as I can see, the only difference is that the list comp variable >> isn't explicitly created with a statement of the form "name = value". Why >> is that a problem? > > I don't know that listcomp vars are worse problem than other vars; > however there is an easy workaround for the listcomp vars so I use it. > If there was a way to restrict the scope of other local vars (I gave > examples from other languages of how this can be done), I'd use that too. Maybe we just have different styles, and I naturally tend to write in smaller scopes than you do. 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 rokadvertising at googlemail.com Wed Jul 4 08:55:47 2007 From: rokadvertising at googlemail.com (rokadvertising at googlemail.com) Date: Wed, 04 Jul 2007 05:55:47 -0700 Subject: issues with htmlparser.getpos In-Reply-To: <1183553248.891042.324870@57g2000hsv.googlegroups.com> References: <1183548847.515341.293540@q69g2000hsb.googlegroups.com> <1183553248.891042.324870@57g2000hsv.googlegroups.com> Message-ID: <1183553747.399656.213410@k79g2000hse.googlegroups.com> On Jul 4, 1:47 pm, rokadvertis... at googlemail.com wrote: > Steve, > > thanks for reply > > there are newlines present, it looks like the files in question are > from a mac, (my text editor tells me they are UTF8 & use CR for > marking newlines) > > Cheers d0h, f = open(this_file,"U") ^^^^ \ this fixed it cheers anyway ;) From jeff at jmcneil.net Wed Jul 25 21:18:15 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 25 Jul 2007 21:18:15 -0400 Subject: Why PHP is so much more popular for web-development In-Reply-To: References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <82d28c40707251158ibae2f9u70889f01ac45a9f6@mail.gmail.com> Message-ID: <82d28c40707251818h1315fc4bq4e55478dbea7a105@mail.gmail.com> On 7/25/07, Steve Holden wrote: > Jeff McNeil wrote: > > Unfortunately, I also find that PHP programmers are usually more > > plentiful than their Python counterparts. When thinking of staffing > > an organization, it's common to target a skill set that's cheaper to > > employ and easier to replace down the road if need be. > > > Right, that's why hospitals are replacing their surgeons with butchers. > There are so many more of them available. It's only cutting meat, after all. > I prefer Python by a long shot, but I'm confident there are a lot of shops making the PHP vs. Python decision every day and this is up there on the list of PHP's benefits. Of the 10 guys I've interviewed in the past two months, I think one had Python experience. In digging a bit deeper, it turns out he got that installing Anaconda packages. > > Also, larger hosting shops are hesitant to run things such as TG and > > Rails that require an additional server process. The name of the game > > is density. Sure, it may be easy to manage and run a TG project, but > > it's a pain to set one up on a shared hosting server. > > > Virtualization will solve that problem. It will help, sure. I run a few things in a FreeBSD VPS right now, actually. I really like the freedom it brings. The problem again goes back to density, though. I work for one of the large web hosting firms. When talking straight shared hosting, we can put well over 50,000 web sites on a cluster of servers. On our VPS products? That number drops down to about 1,000 on the same hardware configuration. If we start talking about hardware virtualization, divide by ten again. The technology is getting there, but it's still just not feasible to hit the same scale with virtualization that one can hit when building a standard shared hosting platform. All of that said, we *do* offer Python on our products. We just don't provide additional support for things such as TurboGears, Zope, or Django. All of our provisioning and management infrastructure is in Python as well. > > > Lastly, I personally think it has something to do with the fact that > > so many of the popular, free, web applications are PHP based. It's > > easy for the average Web Administrator to get started with your > > standard PHP package. From there, picking up the language is the next > > logical step. > > > There's some justice to 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 ------------- > > -- > http://mail.python.org/mailman/listinfo/python-list > From tsuraan at gmail.com Thu Jul 26 20:59:00 2007 From: tsuraan at gmail.com (tsuraan) Date: Thu, 26 Jul 2007 19:59:00 -0500 Subject: generating objects of a type from a name. In-Reply-To: <1185495706.034366.58180@k79g2000hse.googlegroups.com> References: <1185495706.034366.58180@k79g2000hse.googlegroups.com> Message-ID: <84fb38e30707261759v519565b3k4314d2ded78f77f@mail.gmail.com> I'm not sure what a visual object is, but to create an instance of an object whose name is known, you can use "eval": >>> oname = 'list' >>> obj = eval(oname)() >>> obj [] >>> type(obj) Hope that helps! On 26/07/07, chris.lyon at spritenote.co.uk wrote: > I'm trying to generate visual python objects from django objects and > therefore have objects called 'Ring' and 'Cylinder' as django objects > and I want to create objects of those names in visual. > I can cludge it in varius ways by using dir and lots of if lookups but > is there a way of doing this that allows the name to generate a > visual object of the appropriate name or fail nicely if the visual > object doesn't exist? > > -- > http://mail.python.org/mailman/listinfo/python-list > From nazgul at jsbsystems.com Sat Jul 28 21:24:03 2007 From: nazgul at jsbsystems.com (nazgul) Date: Sat, 28 Jul 2007 20:24:03 -0500 Subject: Compiling 2.5.1 on OpenBSD 4.1 Message-ID: Hi all, In my prev post, I indicated I was using 2.5.1 on one box and 2.5p3 on the OpenBSD box. I'm trying to build 2.5.1 on OpenBSD and I get this: Modules/posixmodule.c:5701: error: `lstat' undeclared (first use in this function) I browsed the source and don't understand why I'm getting it. I'm not a configure expert, but I did figure out that pyconfig.h has these set: #define HAVE_LSTAT 1 #define HAVE_SYS_STAT_H 1 #define HAVE_SYS_TYPES_H 1 and that posixmodule.c includes sys/stat.h, sys/types.h (per the lstat manpage) as well as declaring lstat outright. I'm stumped. Any suggestions? ./configure was run with no options. TIA, nazgul From axjacob at comcast.net Mon Jul 9 13:44:05 2007 From: axjacob at comcast.net (axjacob at comcast.net) Date: Mon, 09 Jul 2007 17:44:05 +0000 Subject: Htmllib help Message-ID: <070920071744.26449.469273E50006DBE30000675122007510900D010C0E06A10407020E@comcast.net> Thank you. The NullWriter worked perfectly. I will certainly look at HTMLParser. -------------- Original message ---------------------- From: "Gabriel Genellina" > En Fri, 06 Jul 2007 03:44:20 -0300, escribi?: > > > Thats right I don't need the output any where so I don't need to use the > > writer. I can remove it wowever will the formater work since it needs > > writer? Maybe I can use the Null writer? > > Exactly. Look at the HTMLParser module too; depending on your needs, it > may be easier to use. > > > -------------- Original message ---------------------- > > From: "Gabriel Genellina" > >> En Thu, 05 Jul 2007 20:23:08 -0300, escribi?: > >> > > >> > Even though I don't use any print statements, the htmllib seems to be > >> > throwing parts of the html page on to the standard out(my screen in > >> this > >> > case). Is there a way to disable the output? > >> > > >> > import htmllib > >> > w = formatter.DumbWriter() > >> > >> Change the above line. From > >> http://docs.python.org/lib/writer-impls.html: > >> "class DumbWriter([file[, maxcol = 72]]) > >> Simple writer class which writes output on the file object passed in as > >> file or, if file is omitted, on standard output." > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list From ptmcg at austin.rr.com Mon Jul 2 19:28:58 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 02 Jul 2007 16:28:58 -0700 Subject: Pretty Scheme, ??? Python In-Reply-To: <_Ddii.36114$G23.10348@newsreading01.news.tds.net> References: <46895e12$0$5078$ba4acef3@news.orange.fr> <_Ddii.36114$G23.10348@newsreading01.news.tds.net> Message-ID: <1183418938.911025.55340@w5g2000hsg.googlegroups.com> On Jul 2, 3:56 pm, Neil Cerutti wrote: > On 2007-07-02, Laurent Pointal wrote: > > > Neil Cerutti wrote: > >> How can I make the Python more idiomatic Python? > > > Have you taken a look at pyparsing ? > > Yes, I have it. PyParsing has, well, so many convenience features > they seem to shout down whatever the core features are, and I > don't know quite how to get started as a result. > > Hardest of all was modifying a working PyParsing program. > > As a result, I've found writing my own recursive descent parsers > much easier. > > I'm probably wrong, though. ;) > > -- > Neil Cerutti from pyparsing import * """ Neil - Ok, here is the step-by-step, beginning with your posted BNF. (Based on your test cases, I think the '{}'s are really supposed to be '()'s.) ; ::= ; ; | { + } ; | { - } ; | {with { } } ; | The most basic building blocks in pyparsing are Literal and Word. With these, you compose "compound" elements using And and MatchFirst, which are bound to the operators '+' and '|' (on occasion, Or is required, bound to operator '^', but not for this simple parser). Since you have a recursive grammar, you will also need Forward. Whitespace is skipped implicitly. Only slightly more advanced is the Group class, which will impart hierarchy and structure to the results - otherwise, everything just comes out as one flat list of tokens. You may be able to remove these in the final parser, depending on your results after steps 1 and 2 in the "left for the student" part below, but they are here to help show structure of the parsed tokens. As convenience functions go, I think the most common are oneOf and delimitedList. oneOf might be useful here if you want to express id as a single-char variable; otherwise, just use Word(alphas). At this point you should be able to write a parser for this WAE grammar. Like the following 9-liner: """ LPAR = Literal("(").suppress() RPAR = Literal(")").suppress() wae = Forward() num = Word(nums) id = oneOf( list(alphas) ) addwae = Group( LPAR + "+" + wae + wae + RPAR ) subwae = Group( LPAR + "-" + wae + wae + RPAR ) withwae = Group( LPAR + "with" + LPAR + id + wae + RPAR + wae + RPAR ) wae << (addwae | subwae | withwae | num | id) tests = """\ 3 (+ 3 4) (with (x (+ 5 5)) (+ x x))""".splitlines() for t in tests: print t waeTree = wae.parseString(t) print waeTree.asList() print """ If you extract and run this script, here are the results: 3 ['3'] (+ 3 4) [['+', '3', '4']] (with (x (+ 5 5)) (+ x x)) [['with', 'x', ['+', '5', '5'], ['+', 'x', 'x']]] Left as an exercise for the student: 1. Define classes NumWAE, IdWAE, AddWAE, SubWAE, and WithWAE whose __init__ methods take a ParseResults object named tokens (which you can treat as a list of tokens), and each with a calc() method to evaluate them accordingly. 2. Hook each class to the appropriate WAE class using setParseAction. Hint: here is one done for you: num.setParseAction(NumWAE) 3. Modify the test loop to insert an evaluation of the parsed tree. Extra credit: why is id last in the set of alternatives defined for the wae expression? -- Paul """ From escalation746 at yahoo.com Sun Jul 22 22:03:22 2007 From: escalation746 at yahoo.com (escalation746) Date: Sun, 22 Jul 2007 19:03:22 -0700 Subject: custom plugin architecture: how to see parent namespace? In-Reply-To: <1185148311.431968.148520@m3g2000hsh.googlegroups.com> References: <1185113192.049692.258310@k79g2000hse.googlegroups.com> <1185148311.431968.148520@m3g2000hsh.googlegroups.com> Message-ID: <1185156202.232114.319300@n60g2000hse.googlegroups.com> I have updated documentation for this on my blog, diagrammes modernes. Surf: http://diagrammes-modernes.blogspot.com/ From stephenhorne100 at aol.com Fri Jul 27 06:57:41 2007 From: stephenhorne100 at aol.com (Ninereeds) Date: Fri, 27 Jul 2007 03:57:41 -0700 Subject: Compile python with Mingw In-Reply-To: References: Message-ID: <1185533861.522783.268580@o61g2000hsh.googlegroups.com> fdu.xiaojf at gmail.com wrote: > I don't have VS2003, so I think I may compile both pymol > and python with mingw. Sorry I can't help with mingw, but Microsoft has released a free version of VC2005, which should be binary compatible with VC2003, I'd have thought. Of course that means going through the Windows validation, and the downloads pretty big, plus you may need the platform SDK too. From orsenthil at users.sourceforge.net Thu Jul 5 23:48:12 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Fri, 6 Jul 2007 09:18:12 +0530 Subject: urllib to cache 301 redirections? Message-ID: <20070706034811.GA3331@gmail.com> Hi, There is an Open Tracker item against urllib2 library python.org/sf/735515 which states that. urllib / urllib2 should cache the results of 301 (permanent) redirections. This shouldn't break anything, since it's just an internal optimisation from one point of view -- but it's also what the RFC (2616, section 10.3.2, first para) says SHOULD happen. I am trying to understand, what does it mean. Should the original url be avaiable to the user upon request as urllib automatically calls the redirect_request and provides the redirected url only? I am not completely getting what "cache - redirection" implies and what should be done with the urllib2 module. Any pointers? Thanks, -- O.R.Senthil Kumaran http://uthcode.sarovar.org From horpner at yahoo.com Thu Jul 26 16:27:28 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 26 Jul 2007 20:27:28 GMT Subject: pyparser and recursion problem References: <1185479408.520124.40670@k79g2000hse.googlegroups.com> Message-ID: On 2007-07-26, pyscottishguy at hotmail.com wrote: > Using pyparser, I'm trying to parse a string like this: > >:Start: first SECOND THIRD :SECOND: second1 | second2 :THIRD: third1 | > FOURTH :FOURTH: fourth1 | fourth2 > > I want the parser to do the following: > 1) Get the text for the :Start: label e.g ('first SECOND THIRD') > 2) Do nothing with the lower-case words e.g ('first') > 3) For each upper-case word find the corresponding entries, and > replace the word > with these entries (the '|' indicates separate records) > e.g. for 'SECOND', replace the word with ("second1", "second2") > 4 Do this recursively, because each item in '3' can have upper-case > words > > I can do this - but not within pyparser. I had to write a > recursive function to do it. I would like to do it within > pyparser however. pyparser is a great parser, but out of the box it only parses. To get it to convert a text file into a new form you'll have to write most of the conversion code yourself, and merely hook it into pyparser. The critical step you're missing (and that I missed until my third try) is the setParseAction method, with which you can monkey around with the resulting parse tree. On the other hand, since you got it working without pyparsing, probably you're problem doesn't need pyparsing. Hopefully I'll have time to help you a bit more later, or Paul MaGuire will swoop down in his pyparsing powered super-suit. ;) -- Neil Cerutti From jstroud at mbi.ucla.edu Tue Jul 31 15:29:16 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 31 Jul 2007 12:29:16 -0700 Subject: Encryption recommendation In-Reply-To: References: Message-ID: JS wrote: > Can someone help me find the proper way to do AES encryption/decryption > using Python? > > Thanks! > > Use pycrypto. You can roll it into a standalone program for any major OS. See . Don't attempt to write your own AES implementation for production software. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From gagsl-py2 at yahoo.com.ar Thu Jul 12 21:19:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Jul 2007 22:19:48 -0300 Subject: MaildirMessage References: <1184287592.509355.310110@g4g2000hsf.googlegroups.com> Message-ID: En Thu, 12 Jul 2007 21:46:32 -0300, Tzury escribi?: > I am getting the following error when trying to iterate in a message > in a Maildir directory. > please help. > >>>> from mailbox import Maildir, MaildirMessage >>>> mbox = Maildir('path/to/mailbox', create = False, factory = >>>> MaildirMessage) >>>> for msg in mbox: > ... for m in msg: > ... print m > ... > Traceback (most recent call last): > File "", line 2, in > File "email/message.py", line 286, in __getitem__ > File "email/message.py", line 352, in get > AttributeError: 'int' object has no attribute 'lower' msg is an instance of MaildirMessage (subclass of Message) - it has no specific iterator, so "for m in msg" tries to use the sequence protocol, starting at 0; that is, tries to get msg[0]. Message objects support the mapping protocol, and msg[0] tries to find a *header* 0, converting the name 0 to lowercase, and fails miserably. Try with: for msg in mbox: print msg or read the MaildirMessage (and Message) docs to see the ways you can handle it. -- Gabriel Genellina From rcdailey at gmail.com Fri Jul 13 10:53:41 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 13 Jul 2007 14:53:41 -0000 Subject: Function parameter type safety? In-Reply-To: References: <1184277163.803229.318660@g4g2000hsf.googlegroups.com> Message-ID: <1184338421.695360.227030@g4g2000hsf.googlegroups.com> Good replies. I'm in the process of learning Python. I'm a native C++ programmer, so you can see how the question relates. There's a lot of cool things C++ allowed you to do with type-checking, such as function overloading. With templates + type checking, I can create a STD version of ifstream/ ofstream in Python. However, I found it isn't possible since Python mainly works with strings in file data instead of bytes. To write a number 400000 to a file in python would take 6 bytes instead of 4, for example. Anyway, I just wanted to explain why I was asking about type checking. There's other measures I'm willing to take to get my job done. Thanks guys. From http Mon Jul 30 19:28:44 2007 From: http (Paul Rubin) Date: 30 Jul 2007 16:28:44 -0700 Subject: What is the "functional" way of doing this? References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> Message-ID: <7xvec1qxn7.fsf@ruckus.brouhaha.com> beginner writes: > 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. If you're trying to learn functional programming, maybe you should use a functional language like Haskell or Scheme. But anyway you might be thinking of something like: def f(n): def mseq(n): while n > 0: n,a = divmod(n, 26) yield a return list(mseq(n)) The above is not really "functional", but it's a reasonably natural Python style, at least for me. From bdesth.quelquechose at free.quelquepart.fr Sun Jul 1 00:15:01 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 01 Jul 2007 06:15:01 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <5engo8F38jdgaU1@mid.uni-berlin.de> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <5engo8F38jdgaU1@mid.uni-berlin.de> Message-ID: <4686b9b0$0$27140$426a74cc@news.free.fr> Diez B. Roggisch a ?crit : >> >> wrt/ proofs of correctness, I'll just point to the spectacular failure >> of Ariane, which was caused by a *runtime* type error in a system >> programmed in ADA - one of the languages with the most psychorigid >> declarative static type systems. > > > That's simply not true. The problem hadn't to do with typing - it was a > overflow due to larger input quantities. cf below. > It had been shown for the > Ariane 4 that this overrun could never happen - by whatever thechnique, > operational or denotational semanticse, I don't know. IIRC it was in the specs. > For the ariane 5, these input constraints didn't hold, which caused the > unexpected runtime error to occur. """ Because of the different flight path, a data conversion from a 64-bit floating point to 16-bit signed integer value caused a hardware exception (more specifically, an arithmetic overflow, as the floating point number had a value too large to be represented by a 16-bit signed integer). """ As far as I'm concerned, it surely qualifies as a runtime type error - "data conversion from a floating point to a 16-bit signed int" should not be allowed when unsafe, isn't it ? """ Efficiency considerations had led to the disabling of the software handler (in Ada code) for this error trap. """ Which implies that even in ADA, runtime type errors are in fact expected - else there would be no handler for such a case. The root of the problem is - of course - not technical but human. As you said, no one cared to write the appropriate unit tests to ensure this module - specified for Ariane 4 - could be reused 'as is' for Ariane 5. But what, how could an ADA module not be correct if it compiles - the ADA type system is here to "prove the absence of certain bugs", isn't it ?-) From jstroud at mbi.ucla.edu Mon Jul 23 03:56:05 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 23 Jul 2007 00:56:05 -0700 Subject: Sort lines in a text file In-Reply-To: References: <1185073397.821811.143260@k79g2000hse.googlegroups.com> Message-ID: Daniel wrote: > On Sun, 22 Jul 2007 06:03:17 +0300, leegold wrote: >> say I have a text file: >> >> zz3 uaa4a ss 7 uu >> zz 3 zzzz66 ppazz9 >> aaaaaaaaa00000zz0 >> >> I want to sort the text file. I want the key to be the number after >> the two "zz". Or I guess a string of two zz then a number....So >> that's 3, 9, 0 >> >> I'm trying to say that I want to sort lines in a file based on a >> regular expression. How could I do that in Python? I'm limited to >> Python 2.1, I can't add any 2nd party newer tools. >> >> Thanks >> Lee G. >> > > Shouldn't it be 3, 6, 9, 0 I'm guessing that the 6 comes after 4 z's and not 2 z's in line 2 so it is ignored. From gagsl-py2 at yahoo.com.ar Sat Jul 14 23:46:27 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 15 Jul 2007 00:46:27 -0300 Subject: defaultdicts pickling References: Message-ID: En Sat, 14 Jul 2007 13:03:01 -0300, Yoav Goldberg escribi?: > I need to have a dictionary of dictionaries of numbers, and I would like > the > dictionaries to be defaultdicts, because it makes the code much nicer > (I want to be able to do: d['foo']['bar']+=1 ). > > So naturally, I used: > > d = defaultdict(lambda :defaultdict(int)) > > It works great, but now I can not pickle it. > > I could ofcourse used a real function and not a lambda, but this would > make > things (a) somewhat slower and (b) a bit ugly. (a) AFAIK, lambdas are true functions, just without name, nor docstrings, nor decorator support, and they only allow expressions. But the execution time should be similar: from collections import defaultdict def test_lambda(): d = defaultdict(lambda: defaultdict(int)) for i in range(100): for j in range(100): d[i%7][j%7] += 1 def test_func(): def func(): return defaultdict(int) d = defaultdict(func) for i in range(100): for j in range(100): d[i%7][j%7] += 1 C:\TEMP>python -m timeit -s "from lf import test_lambda" "test_lambda()" 10 loops, best of 3: 80.3 msec per loop C:\TEMP>python -m timeit -s "from lf import test_func" "test_func()" 10 loops, best of 3: 79.6 msec per loop (the difference being less than the time variation I get, so it has no significance) (b) I don't consider a one-line function so much ugly, but ugliness is subjective, so I won't comment further. > Is there another way of achieving the same behaviour, that allow for > pickling? If you insist: Convert the defaultdict into a plain dict before pickling: plain_dict = dict(d) and again into a defaultdict when unpickling: d=defaultdict(...); d.update(unpickled_dict) -- Gabriel Genellina From steven.bethard at gmail.com Thu Jul 19 01:07:34 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 18 Jul 2007 23:07:34 -0600 Subject: how to implementation latent semantic indexing in python.. In-Reply-To: <1184803885.142218.152490@g12g2000prg.googlegroups.com> References: <1184803885.142218.152490@g12g2000prg.googlegroups.com> Message-ID: 78ncp wrote: > how to implementation algorithm latent semantic indexing in python > programming...?? malkarouri wrote: > IIRC, there was some explanation of Latent Semantic Analysis (with > Python code) in an IEEE ReadyNotes document called "Introduction to > Python for Artificial Intelligence". It wasn't free I am afraid. > > Of course you are aware that LSA is patented.. So don't do LSA. Do a singular value decomposition of a term by document matrix. ;-) Or better yet, try something else, like Independent Component Analysis (ICA) which many people find to work better. I'm always hoping to see a paper that shows that LSA works better than a simple cosine measure, but somehow the vast majority of LSA papers never do that basic comparison... ;-) STeVe From sean at horse101.com Fri Jul 13 16:08:18 2007 From: sean at horse101.com (Sean) Date: Fri, 13 Jul 2007 16:08:18 -0400 Subject: help reading cookie values Message-ID: <4b0a34b50707131308p4d260b9fg2bf23ecf4c2e1f72@mail.gmail.com> I am trying to read a cookie I set but I am not sure if I really set it correctly or I am not reading it correctly. I was given the following instructions to set the cookie. It appears to be working because in Firefox browser I see the cookie listed for my domain > you set a cookie in a pythonscript like: > context.REQUEST.RESPONSE.setCookie('cookie_name', 'some value', > expires=(DateTime() + 365).toZone('GMT').rfc822(), path='/') > I have been searching everywhere to find information on reading the cookie value that I set. I used the following code I found which returns 'no cookiez' in spite of the fact that I see the cookie in my browser's cookie listing. I must be doing something wrong in the way I am testing for its existence import Cookie import os thiscookie = Cookie.SimpleCookie() if 'HTTP_COOKIE' in os.environ: #if os.environ.has_key('HTTP_COOKIE'): I tried this way also thiscookie.load(os.environ['HTTP_COOKIE']) a_code = thiscookie['my_cookie'].value return a_code else: return 'no cookiez' From memracom at yahoo.com Sun Jul 22 17:12:27 2007 From: memracom at yahoo.com (memracom at yahoo.com) Date: Sun, 22 Jul 2007 14:12:27 -0700 Subject: URL parsing for the hard cases In-Reply-To: References: Message-ID: <1185138747.707836.69740@n2g2000hse.googlegroups.com> On 22 Jul, 18:56, John Nagle wrote: > Is there something available that will parse the "netloc" field as > returned by URLparse, including all the hard cases? The "netloc" field > can potentially contain a port number and a numeric IP address. The > IP address may take many forms, including an IPv6 address. > > I'm parsing URLs used by hostile sites, and the wierd cases come up > all too frequently. I assume that when you say "netloc" you are referring to the second field returned by the urlparse module. If this netloc contains an IPv6 address then it will also contain square brackets. The colons inside the [] belong to the IPv6 address and the single possible colon outside the brackets belongs to the port number. Of course, you might want to try to help people who do not follow the RFCs and failed to wrap the IPv6 address in square brackets. In that case, try...expect comes in handy. You can try to parse an IPv6 address and if it fails because of too many segments, then fallback to some other behaviour. The worst case is a URL like http://2001::123:4567:abcd:8080/something. Does the 8080 refer to a port number or part of the IPv6 address. If I had to support non-bracketed IPv6 addresses, then I would interpret this as http://[2001::123:4567:abcd]:8080/something. RFC3986 is the reference for correct URL formats. Once you eliminate IPv6 addresses, parsing is simple. Is there a colon? Then there is a port number. Does the left over have any characters not in [0123456789.]? Then it is a name, not an IPv4 address. --Michael Dillon From bbxx789_05ss at yahoo.com Sun Jul 1 05:43:01 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 01 Jul 2007 02:43:01 -0700 Subject: os.path.isfile() In-Reply-To: References: <1183281482.668177.142470@c77g2000hse.googlegroups.com> Message-ID: <1183282981.430848.243520@k29g2000hsd.googlegroups.com> On Jul 1, 3:36 am, Duncan Booth wrote: > 7stud wrote: > > Here is a program to print out the files in a directory: > > > ----------- > > import os > > > myfiles = os.listdir("../") > > print myfiles > > > for afile in myfiles: > > print afile > > if os.path.isfile(afile): > > print afile, "___file" > > if os.path.isdir(afile): > > print afile, "___dir" > > print > > ------------ > > > Here is what's in the directory: > > > ---------- > > $ ls -al ../ > > > total 2576 > > drwxr-xr-x 8 nnn nnn 272 Jul 1 03:03 . > > drwxr-xr-x 25 nnn nnn 850 Jul 1 01:34 .. > > -rw-r--r-- 1 nnn nnn 6148 Jul 1 03:02 .DS_Store > > -rw-r--r-- 1 nnn nnn 1300000 Jun 27 14:02 aaa.txt > > drwxr-xr-x 55 nnn nnn 1870 Jul 1 03:09 dir1 > > -rwxrwxrwx 1 nnn nnn 263 Jun 27 22:40 mytest.py > > -rw-r--r-- 1 nnn nnn 0 Mar 4 16:15 scratch.txt > > -rw-r--r-- 1 nnn nnn 275 Apr 11 03:40 xmlFile.xml > > ------------ > > Yes, but what does 'ls -al .' show you? You didn't put any kind of path in > your calls to isfile/isdir, so you are checking for the existence of > files/directories called '.DS_Store' etc. in the *current* directory, not > the one above. From your output I'd guess you have .DS_Store and aaa.txt > files but the other names are not duplicated. Thanks. From bob at mellowood.ca Fri Jul 13 12:24:57 2007 From: bob at mellowood.ca (bvdp) Date: Fri, 13 Jul 2007 09:24:57 -0700 Subject: Circular import problem In-Reply-To: References: <1184294176.550267.119980@n60g2000hse.googlegroups.com> Message-ID: <1184343897.111992.107880@g4g2000hsf.googlegroups.com> > Seehttp://effbot.org/zone/import-confusion.htm > Try to move the circular references later in the code (maybe inside a > function, when it is required), or much better, refactor it so there is no > circularity. > > -- > Gabriel Genellina Yes, thanks. I'd read that page before posting. Helpful. But, I still don't understand how python can access a function in a file I have NOT included. In this case, to get things to work, I DO NOT "import MMA.grooves" but later in the module I access a function with "xx=MMA.grooves.somefunc()" and it finds the function, and works just fine. It shouldn't work. I have tried to delay the import, and that does work. But, from a stylistic view I really to like to have all my imports at the top of the module. Maybe some old assembler/C habits on my part. From lachlan.gunn at internode.on.net Thu Jul 12 02:59:27 2007 From: lachlan.gunn at internode.on.net (Lachlan Gunn) Date: Thu, 12 Jul 2007 06:59:27 -0000 Subject: Anonymous Classes Message-ID: <139bkaf7m30iu49@corp.supernews.com> Hello. I have a library (SQLObject) that stores data as class variables. I would like to set a class variable in a certain context, specific to a certain instance of an object. This would require some sort of anonymous class. I have attempted to use the following code to set the connection string: | class SQLStorage: | def __init__(self, c, debug = False): | config = StorageConfiguration(c) | | connection = sqlobject.connectionForURI(config.databaseString) | if debug: | connection.debug = True | | # I don't know whether this is right. My belief is that we can | # subclass each table and use _connection on them. | class newDatum(DatumTable): | _connection = connection | | class newMetadatum(MetadatumTable): | _connection = connection | | class newChecksum(ChecksumTable): | _connection = connection | | self.__SQLDatum = newDatum | self.__SQLMetadatum = newMetadatum | self.__SQLChecksum = newChecksum This does not work; Python complains that the classes already exist when SQLObject is instantiated for a second time. This has led me to try instantiating a subclass using DatumTable.__class__ and friends, but this requires setting a class name, which, again, limits me to a single instance. I *could* have a counter that appends a number to each class name, but that's a fairly ugly solution; is it possible to create an anonymous class in Python? Thanks, Lachlan. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 13 03:37:31 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 13 Jul 2007 09:37:31 +0200 Subject: Class decorators do not inherit properly In-Reply-To: References: Message-ID: <46972b93$0$11779$426a74cc@news.free.fr> Lee Harr a ?crit : >> Traceback (most recent call last): >> File "/Users/chris/Projects/CMR/closed.py", line 132, in >> class M0(MetropolisHastings): >> File "/Users/chris/Projects/CMR/closed.py", line 173, in M0 >> @_add_to_post >> NameError: name '_add_to_post' is not defined >> >> yet, when I look at the dict of the subclass (here called M0), I see the >> decorator method: >> > > > I think the term "class decorator" is going to eventually > mean something other than what you are doing here. I'd > avoid the term for now. > > > When you decorate a class method, > the function you use > needs to be defined before the method definition. This is true whatever you are decorating - class method, static method, instance method, function. And FWIW, the term "class method" has a definite meaning in Python. > Using a class method to decorate another class method is > going to be tricky. The way I usually do it is to create > a separate function outside of the class definition for > the decorator function. The problem is then that this function cannot easily access the class object - which is what the OP want. > > You're going to have to show us the actual code you are > having trouble with, or else (probably more useful, really) > try to put together a minimal example of what you are > trying to do and show us that code. +1 on this From brotherjenos at gmail.com Thu Jul 26 21:20:30 2007 From: brotherjenos at gmail.com (Walker Lindley) Date: Thu, 26 Jul 2007 18:20:30 -0700 Subject: How to tell when a socket is closed on the other end? In-Reply-To: <46A852F5.8000907@jayloden.com> References: <1185371863.622473.205010@19g2000hsx.googlegroups.com> <46A852F5.8000907@jayloden.com> Message-ID: <9c8d48280707261820p3ac6702l8ea3e08e34b026fe@mail.gmail.com> The easiest way I've found is to just surround every socket-related thing you do with try/except. the except statement is something like "except socket.error, err_info". then the err_info variable will have a tuple containing the BSD socket error number and the text of the error. You can reference this with BSD socket information or just do trail and error to see which exceptions you get when the client-side closes versus when the server side closes. I'm not actually sure which they are, but I know the networked program I'm working with uses this method to detect when a socket I'm doing some operation on has been closed. I hope that helps some. -Walker On 7/26/07, Jay Loden wrote: > > Roy Smith wrote: > > In article <1185371863.622473.205010 at 19g2000hsx.googlegroups.com>, > > billiejoex wrote: > > > >> Hi there. > >> I'm setting up test suite for a project of mine. > >> >From test suite, acting as a client, I'd like to know, in certain > >> situations, if the socket is closed on the other end or not. > >> I noticed that I can "detect" such state if a call to socket.read() > >> returns 0 but it seems a little poor to me. :-\ > >> Is there a reliable way to test such socket 'state'? > > > > This isn't really a Python question, it's a Berkeley Socket API > question. > > You don't say, but I assume you're talking about a TCP (i.e. SOCKSTREAM) > > connection? > > > > The answer is you can use the select() system call to detect > "exceptional > > conditions" on a socket. Python's select module provides this > > functionality, but to understand how to use it, you need to study the > > underlying API. > > Thanks for the interesting information and suggestion of using select(). > You are correct that this is actually mostly a socket API question but > pertains to Python since the code is all Python's socket and asyncore > modules. It might help to step back and explain the original problem. The > goal of this portion of the test suite we are writing for the project is to > determine if a remote server is behaving properly by closing a socket from > the server side based on a client-side command. > > Really what's needed is a way to make sure the socket gets closed, and > preferably determine if it was closed from the remote end as expected. Do > you know if this is possible to determine from the client side > reliably/accurately? Would select()'s exceptional condition flag actually > indicate whether or not the root cause of the condition was a socket closed > by the remote peer? I've read through the select's manpage and I can't seem > to find a reference that indicates what the possible values are for the I/O > descriptor sets returned by select. Is there another man page, or a place in > the header file for select I can look? > > Thanks for your help, > > -Jay > -- > http://mail.python.org/mailman/listinfo/python-list > -- 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: From bignose+hates-spam at benfinney.id.au Sat Jul 14 20:50:39 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 15 Jul 2007 10:50:39 +1000 Subject: MaildirMessage References: <1184287592.509355.310110@g4g2000hsf.googlegroups.com> <874pk8kedo.fsf@benfinney.id.au> <87vecniw4u.fsf@benfinney.id.au> Message-ID: <87abtyij6o.fsf@benfinney.id.au> Steve Holden writes: > What do you actually think > > .... for m in msg: > .... print m > > should do? Why do you believe that what you think it should do would > be a natural choice? I think it odd for a Message to support the mapping protocol. However, since that's what is announced, then I expect it to actually support the mapping protocol, which in my expectation includes iterating over the keys. -- \ "One of the most important things you learn from the internet | `\ is that there is no 'them' out there. It's just an awful lot of | _o__) 'us'." -- Douglas Adams | Ben Finney From matt at tplus1.com Thu Jul 19 11:35:44 2007 From: matt at tplus1.com (Matthew Wilson) Date: Thu, 19 Jul 2007 15:35:44 GMT Subject: Itertools question: how to call a function n times? Message-ID: I want to write a function that each time it gets called, it returns a random choice of 1 to 5 words from a list of words. I can write this easily using for loops and random.choice(wordlist) and random.randint(1, 5). But I want to know how to do this using itertools, since I don't like manually doing stuff like: phrase = list() for i in random.randint(1, 5): phrase.append(random.choice(wordlist)) It just seems slow. All advice welcome. TIA Matt -- A better way of running series of SAS programs: http://tplus1.com/wilsonwiki/SasAndMakefiles From tim.arnold at sas.com Mon Jul 30 10:16:22 2007 From: tim.arnold at sas.com (Tim Arnold) Date: Mon, 30 Jul 2007 10:16:22 -0400 Subject: encode/decode misunderstanding References: <5h3ih4F3il4p1U1@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in message news:5h3ih4F3il4p1U1 at mid.uni-berlin.de... > Tim Arnold schrieb: >> Hi, I'm beginning to understand the encode/decode string methods, but I'd >> like confirmation that I'm still thinking in the right direction: >> >> I have a file of latin1 encoded text. Let's say I put one line of that >> file into a string variable 'tocline', as follows: >> tocline = 'Ficha Datos de p\xe9rdida AND acci\xf3n' >> >> import codecs >> tocFile = codecs.open('mytoc.htm','wb',encoding='utf8',errors='replace') >> tocline = tocline.decode('latin1','replace') >> tocFile.write(tocline) >> tocFile.close() >> >> What I think is that tocFile is wrapped to insure that anything written >> to it is in utf8 >> I decode the latin1 string into python's internal unicode encoding and >> that gets written out as utf8. >> >> Questions: >> what exactly is the tocline when it's read in with that \xe9 and \xed in >> the string? A latin1 encoded string? > > Yes. A simple, pure byte-string, that happens to contain bytes which under > the latin1-encoding are "correct". > >> Is my method the right way to write such a line out to a file with utf8 >> encoding? > > Yes. > >> If I read in the latin1 file using >> codecs.open(filename,encoding='latin1') and write out the utf8 file by >> opening with >> codecs.open(othername,encoding='utf8'), would I no longer have a >> problem -- I could just read in latin1 and write out utf8 with no more >> worries about encoding? > > As long as you don't mix bytestrings and only use unicode-objects, you > should be fine, yes. > > Diez wow, I was thinking correctly about encoding! time for a beer! Diez, thanks very much for confirming my thoughts. --Tim Arnold From jarausch at igpm.rwth-aachen.de Wed Jul 11 07:29:40 2007 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Wed, 11 Jul 2007 13:29:40 +0200 Subject: pattern match ! In-Reply-To: <1184125206.034047.175340@n60g2000hse.googlegroups.com> References: <1184125206.034047.175340@n60g2000hse.googlegroups.com> Message-ID: <4694BF24.1050706@igpm.rwth-aachen.de> hari.siri74 at gmail.com wrote: > Extract the application name with version from an RPM string like > hpsmh-1.1.1.2-0-RHEL3-Linux.RPM, i require to extract hpsmh-1.1.1.2-0 > from above string. Sometimes the RPM string may be hpsmh-1.1.1.2-RHEL3- > Linux.RPM. > Have a try with import re P=re.compile(r'(\w+(?:[-.]\d+)+)-RHEL3-Linux\.RPM') S="hpsmh-1.1.1.2-0-RHEL3-Linux.RPM" PO= P.match(S) if PO : print PO.group(1) -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From bbxx789_05ss at yahoo.com Mon Jul 30 04:21:40 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 30 Jul 2007 01:21:40 -0700 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1185778723.073491.32680@l70g2000hse.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> <1184458002.961657.267830@x35g2000prf.googlegroups.com> <1184466882.446791.127670@x35g2000prf.googlegroups.com> <1185658013.859359.47700@57g2000hsv.googlegroups.com> <1185703671.241103.124780@g12g2000prg.googlegroups.com> <1185727058.306635.203130@b79g2000hse.googlegroups.com> <1185751725.882668.269850@i13g2000prf.googlegroups.com> <1185776482.804291.301200@g4g2000hsf.googlegroups.com> <1185778723.073491.32680@l70g2000hse.googlegroups.com> Message-ID: <1185783700.467877.155180@22g2000hsm.googlegroups.com> The Testing section of the mod_python manual says to add the following to httpd.conf(with my directory structure): AddHandler mod_python .py PythonHandler mptest PythonDebug On and your tutorial says to add this to httpd.conf: --- AllowOverride FileInfo Replace "/some/directory" with the absolute pathname to the directory in which the ".htaccess" file is located. ------- and the mod_python Testing section also cryptically refers to that addition, so is there any reason why you can't combine them into: AllowOverride FileInfo AddHandler mod_python .py PythonHandler mptest PythonDebug On It seems to work for me. I deleted the .htaccess file out of the ../ modPythonPages/ directory, I made that change to httpd.conf, I restarted apache, and mptest.py displays the proper message. From exarkun at divmod.com Thu Jul 19 09:09:08 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 19 Jul 2007 09:09:08 -0400 Subject: UDP broadcast over a specific interface In-Reply-To: <1184848322.796960.121950@q75g2000hsh.googlegroups.com> Message-ID: <20070719130908.4947.503943403.divmod.quotient.13371@ohm> On Thu, 19 Jul 2007 12:32:02 -0000, "Larry.Martell at gmail.com" wrote: >I am trying to send UDP broadcast packets over a specific interface >and I >am having trouble specifying the interface: > >host='192.168.28.255' >sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) >sock.bind(('',0)) >sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) >sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, >socket.inet_aton(host)) > >socket.error: (49, "Can't assign requested address") > >What am I doing wrong? How can I force my broadcast packets to go out >a specific interface? IP_MULTICAST_IF is for multicast UDP, which doesn't have anything to do with broadcast UDP. Try just doing this, instead: host='192.168.28.255' sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((host,0)) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) You shouldn't need to mess with anything beyond that. Jean-Paul From aleax at mac.com Mon Jul 16 00:02:28 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 15 Jul 2007 21:02:28 -0700 Subject: Accessing Python variables in an extension module References: <1184553584.757696.92630@g4g2000hsf.googlegroups.com> Message-ID: <1i1b7zw.64m7g071sk32N%aleax@mac.com> MD wrote: > Hi, > > I would like to access "variables" defined in my Python program in > a C module extension for Python. Is this possible? I looked at the > Python C API reference but didn't find anything there that could help > me. If they're global variables of a certain module XYZ, your C code may "import" XZY (or look it up in the C API equivalent of the sys.modules dict) and get those variables as attributes of object XYZ. Is that what you mean by ``variables defined in your Python program''...? Alex From ChrisEdgemon at gmail.com Mon Jul 9 15:57:14 2007 From: ChrisEdgemon at gmail.com (ChrisEdgemon at gmail.com) Date: Mon, 09 Jul 2007 19:57:14 -0000 Subject: Comparing modified elements in Sets Message-ID: <1184011034.839268.116730@r34g2000hsd.googlegroups.com> I've got a set with contents like: [filename1.mp3, filename2.mp3, filename3.mp3, ...] I've got another set with contents like [filename1.ogg, filename3.ogg, ...] And another set with contents like [filename1, filename 2, ...] I'd like to be able to compare set 1 with set 2 and have it match filename1 and filename3, or compare set 1 with 3 and get back filename1, filename2. etc. Is there a way for me to do this inside the compare function, rather than having to make duplicate copies of each set? From bdesth.quelquechose at free.quelquepart.fr Thu Jul 19 00:51:29 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 19 Jul 2007 06:51:29 +0200 Subject: class C: vs class C(object): In-Reply-To: <1184945347.195877.319000@n60g2000hse.googlegroups.com> References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> <469f1557$0$26759$426a74cc@news.free.fr> <46a082ed$0$431$426a74cc@news.free.fr> <1184945347.195877.319000@n60g2000hse.googlegroups.com> Message-ID: <46a21414$0$19525$426a74cc@news.free.fr> George Sakkis a ?crit : > On Jul 20, 5:40 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > >>Aahz a ?crit : >> >> >>>In article <469f1557$0$26759$426a7... at news.free.fr>, >>>Bruno Desthuilliers wrote: >>> >>>>To make a long story short: Python 2.2 introduced a new object model >>>>which is more coherent and more powerful than the original one. The old >>>>one was kept so far for compatibility reasons, but there's absolutely no >>>>reason to use it no more since "new-style" classes can do anything >>>>"Classic" classes did and much more. IOW, don't even bother with >>>>old-style classes. >> >>>And I'll make my usual knee-jerk response disagreeing with this. For >>>more info, search groups.google.com. >> >>And you'll still make it harder for newcomers to understand why a lot of >>things don't work correctly with their classes. How helpful... >> >>Aahz, the object model switch happened *years* ago, and it's quite clear >>that old style classes have been kept so far for compatibility reasons >>only. It's obvious that one doesn't gain *anything* - except compat with >>years-old pre-2.2 versions of Python - using old-style classes. So *why* >>on earth are you still *advocating* the use of old style classes ?????? > > > FWIW, I am not advocating old style classes and I rarely (if ever) use > them in new code, but I occasionally miss the following feature, which > by the way disproves the assertion that "new-style classes can do > anything Classic classes did": > > class Classic: pass > class NewStyle(object):pass > > for o in Classic(),NewStyle(): > o.__str__ = lambda: 'Special method overriding works on > instances!' > print '%s object: %s' % (o.__class__.__name__, o) > Good point. There are effectively a couple of things that did work with the old object model and don't with the new one. OTOH, and while I tend to make heavy use of Python's dynamism and advanced features, I never had the need to dynamically override special methods on a per-instance basis yet. Not to say this is useless, just that it's probably enough of a corner case to justify the design choice (YMMV of course). From claird at lairds.us Wed Jul 25 09:30:47 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 25 Jul 2007 13:30:47 +0000 Subject: Closures / Blocks in Python References: <1185289112.771239.200260@n60g2000hse.googlegroups.com> <1185291146.753573.280420@n60g2000hse.googlegroups.com> Message-ID: <7tvjn4-qas.ln1@lairds.us> In article <1185291146.753573.280420 at n60g2000hse.googlegroups.com>, Jason wrote: . [good detail] . . >If you can't find a way of doing what you want with iterators, >comprehensions, or lambda, consider writing a little function. Heck, . . . "[C]onsider writing a little function", indeed; that's a crucial summary. From a Ruby or Lisp perspective, this proliferation of named functions is clumsy and unsightly; Pythoneers see small def-s as opportunities to clarify. I've come to suspect both sides are right. The marvelous thing is that, taken as a whole, each of Python, Ruby, ... *works*, and admits a strong, effec- tive style. Moreover, they share enough conceptually that it's not hard for speakers of one to understand the others. As has already been proposed in this thread, though, good Ruby and good Python will always look different. From danmcleran at yahoo.com Mon Jul 16 18:52:13 2007 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: Mon, 16 Jul 2007 15:52:13 -0700 Subject: Break up list into groups In-Reply-To: <1184622966.15828.27.camel@blackwidow.nbk> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> <1184621479.15828.23.camel@blackwidow.nbk> <1184622966.15828.27.camel@blackwidow.nbk> Message-ID: <1184626333.854075.115670@o11g2000prd.googlegroups.com> On Jul 16, 3:56 pm, marduk wrote: > On Mon, 2007-07-16 at 16:31 -0500, marduk wrote: > > Assuming you meant '0xF0' instead of '0x80'.... do you mean any value > > >=240 starts a new group? If so: No, I meant 0x80. 0x80 is only the most significant bit of the 0xF0 value. Every time this bit is set indicates the start of a new group. Anyway, I like this algorithm better than mine, less code. I've modified yours to make the fn a parameter: def splitIntoGroups(data, fn): groups = [] current = [] for i in data: if fn(i): current = [] groups.append(current) current.append(i) return groups print splitIntoGroups(l, lambda x : x & 0x80) From jjl at pobox.com Sat Jul 14 06:49:56 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 14 Jul 2007 10:49:56 GMT Subject: help reading cookie values References: <1184358595.508448.291700@q75g2000hsh.googlegroups.com> Message-ID: <87wsx3z2cr.fsf@pobox.com> kyosohma at gmail.com writes: > On Jul 13, 3:08 pm, Sean wrote: >> I am trying to read a cookie I set but I am not sure if I really set >> it correctly or I am not reading it correctly. I was given the >> following instructions to set the cookie. It appears to be working >> because in Firefox browser I see the cookie listed for my domain [...snip cookie-sending and -receiving code...] > This site looks like it has some good information on Cookie handling > (see "cookielib and ClientCookie Example" section: > http://www.voidspace.org.uk/python/recipebook.shtml No, he doesn't want that -- that's for web clients, not web servers. Wild guess: are you sending a domain attribute in your cookie (sniff the HTTP traffic to find out, see below)? Try not doing that. The cookie-receiving code above looks correct (I don't know about the sending code, because I don't know what framework you're using, and don't want to read that framework's code). Remember that things like the cookie's domain and path have to match HTTP request's domain and path for cookies to be *returned* by the browser to the server. Simply having been *accepted* by the browser is not enough. The rules are are fairly complicated, so KISS. You can use a network sniffer like wireshark or tcpdump to record exactly what Set-Cookie: and Cookie: headers are being sent, and compare with the domain name, port, HTTP path and URL scheme (https/http) of the HTTP request that your browser is making. If you still can't figure it out, post those things here (change the domain name if you must, but keep the form of everything strictly unchanged). Or simplify your situation to make it easier to understand. Another source of help would be the mailing list for the web framework you're using. John From steve at holdenweb.com Sat Jul 21 16:31:38 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 21 Jul 2007 16:31:38 -0400 Subject: problem with exec In-Reply-To: References: Message-ID: ...:::JA:::... wrote: > Hello, > > After my program read and translate this code: > > koristi os,sys; > ispisi 'bok kaj ima'; > > into the: > > import os,sys; > print 'bok kaj ima'; > > and when it run this code with "exec", I always get error like this, but I > still dont't know what is a problem: > > Traceback (most recent call last): > File "C:\Python24\Lib\site-packages\VL\__init__.py", line 188, in > kompajlati > kompajlati_proces() > File "C:\Python24\Lib\site-packages\VL\__init__.py", line 183, in > kompajlati_proces > h2=Konzola() > File "C:\Python24\Lib\site-packages\VL\__init__.py", line 158, in __init__ > k=kod(ZTextCtrl.GetLabel()) > File "C:\Python24\Lib\site-packages\VL\__init__.py", line 83, in kod > exec(str_ngh) > File "", line 1 > import os ,sys ; > ^ > SyntaxError: invalid syntax > This is almost certainly because the code contains embedded carriage returns: >>> code = """import os,sys;\nprint 'bok kaj ima';""" >>> exec code bok kaj ima >>> code = """import os,sys;\r\nprint 'bok kaj ima';""" >>> exec code Traceback (most recent call last): File "", line 1, in File "", line 1 import os,sys; ^ SyntaxError: invalid syntax >>> > PS: How can I change when user write script with my program to he don't need > aspirate the lines of his source code > e.g. > import os,sys > n=90 > if n==90:print "OK" > else:print "No" > > I'm afraid I don't understand this question. If you are talking about the indentation of the code, if you don't want indentation you will have to use braces - { and } - to indicate the nesting structure of your program. 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 jarausch at igpm.rwth-aachen.de Tue Jul 3 06:31:34 2007 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Tue, 03 Jul 2007 12:31:34 +0200 Subject: restructuredtext latin1 encoding (FAQ?) In-Reply-To: <5eum6fF39v66mU1@mid.uni-berlin.de> References: <5eulnmF3ates7U1@mid.dfncis.de> <5eum6fF39v66mU1@mid.uni-berlin.de> Message-ID: <468A2586.4060107@igpm.rwth-aachen.de> Marc 'BlackJack' Rintsch wrote: > On Tue, 03 Jul 2007 12:12:04 +0200, Helmut Jarausch wrote: > >> Is there a way to write documents with the reST tools using the Latin1 >> encoding? > > Yes of course there is. Just write the documents in Latin-1 encoding. > Take a look at the charset command line options if Latin-1 is not the > default encoding used by your operating system. > Many thanks! Is there also a way to tell it dugui.py ? Helmut. -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From adrian_p_smith at yahoo.com Tue Jul 3 11:14:32 2007 From: adrian_p_smith at yahoo.com (Adrian Smith) Date: Tue, 03 Jul 2007 08:14:32 -0700 Subject: mysteries of urllib/urllib2 In-Reply-To: <1183472702.932557.108600@n2g2000hse.googlegroups.com> References: <1183470239.153444.244700@j4g2000prf.googlegroups.com> <1183472702.932557.108600@n2g2000hse.googlegroups.com> Message-ID: <1183475672.295922.47600@e9g2000prf.googlegroups.com> On Jul 3, 11:25 pm, Ben Cartwright wrote: > On Jul 3, 9:43 am, Adrian Smith wrote: > > > The following (pinched > > from Dive Into Python) seems to work perfectly in Idle, but > > falls at the final hurdle when run as a cgi script - can > > anyone suggest anything I may have overlooked? > > > request = urllib2.Request(some_URL) > > request.add_header('User-Agent', 'some_plausible_string') > > opener = urllib2.build_opener() > > data = opener.open(request).read() > > Most likely the account that cgi script is running as does not > have permissions to access the net. Check the traceback to be > sure. Put this at the top of your cgi script: > > import cgitb; cgitb.enable() Well, it worked with urllib (resulting in a G**gle 403 your-client- does-not-have-permission-to-get-urlX page), so I think it must have some access. Apparently there's a way to change the user-agent string by subclassing urllib's URLopener class, but that's beyond my comfort zone at present. From greg at cosc.canterbury.ac.nz Tue Jul 10 05:04:05 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 10 Jul 2007 21:04:05 +1200 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <1183576255.668414.256990@q69g2000hsb.googlegroups.com> <5f31fvF3asl6lU1@mid.individual.net> <1183665370.643503.157060@m36g2000hse.googlegroups.com> Message-ID: <5fh0imF3cjte7U1@mid.individual.net> Ilya Zakharevich wrote: > In pedantic mode: negative timestamps make sense with Big Bang as the > epoch as well. (AFAIU, the current way of thinking is that it was > "just too hot" before the big bang, it is not that "there was > nothing".) If Stephen Hawking is right, the shape of the universe is such that there isn't any time "before" the big bang at all. It's like asking what's north of the North Pole. Of course, this may have been replaced with some other equally bizarre idea by now... Another thought: If the cosmologists ever decide if and when the Big Crunch is going to happen, we may be able to figure out once and for all how many bits we need in the timestamp. -- Greg From tn.pablo at gmail.com Sat Jul 21 01:44:37 2007 From: tn.pablo at gmail.com (Pablo Torres) Date: Fri, 20 Jul 2007 22:44:37 -0700 Subject: Permutations with generators In-Reply-To: <1184996537.069416.211730@g4g2000hsf.googlegroups.com> References: <1184996537.069416.211730@g4g2000hsf.googlegroups.com> Message-ID: <1184996677.873535.134520@n2g2000hse.googlegroups.com> Just a quick P.S: This WOULD NOT work with strings, because of seq.insert() In very other aspect, I'm still lost. From crcarleRemoveThis at BOGUSsandia.gov Fri Jul 13 16:34:20 2007 From: crcarleRemoveThis at BOGUSsandia.gov (Chris Carlen) Date: Fri, 13 Jul 2007 13:34:20 -0700 Subject: Can a low-level programmer learn OOP? In-Reply-To: <1184349621.481612.210100@d55g2000hsg.googlegroups.com> References: <1184349549.484402.214860@o61g2000hsh.googlegroups.com> <1184349621.481612.210100@d55g2000hsg.googlegroups.com> Message-ID: Simon Hibbs wrote: > Sorry, here's the tutorial link: > > http://hetland.org/writing/instant-python.html > > > Simon Hibbs Thanks Simon. Actually, that's the tutorial that I've started with. Your comments are encouraging. I'll keep learning. -- Good day! ________________________________________ Christopher R. Carlen Principal Laser&Electronics Technologist Sandia National Laboratories CA USA crcarleRemoveThis at BOGUSsandia.gov NOTE, delete texts: "RemoveThis" and "BOGUS" from email address to reply. From mail at microcorp.co.za Wed Jul 18 02:43:05 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 18 Jul 2007 08:43:05 +0200 Subject: Best method for inter process communications References: <1184606522.541918.18870@22g2000hsm.googlegroups.com> <5g3ca2F3dv5s2U1@mid.uni-berlin.de> Message-ID: <012f01c7c90b$98987520$03000080@hendrik> "Marc 'BlackJack' Rintsch" wrote: On Tue, 17 Jul 2007 08:08:45 +0200, Hendrik van Rooyen wrote: > I heard a rumour once that a "hello world" string takes something like > 10k bytes in XMLRPC - have never bothered to find out if its BS... Just try it out: In [8]: import xmlrpclib In [9]: a = xmlrpclib.dumps(('hello world',)) In [10]: len(a) Out[10]: 80 In [11]: print a hello world Even with some additional boilerplate like XML declaration etc. there is still a little bit room until 10 kB are reached. :-) LOL - so one could say it was a bit of an exaggeration... Thanks - Hendrik From aisaac at american.edu Thu Jul 12 20:37:45 2007 From: aisaac at american.edu (Alan Isaac) Date: Fri, 13 Jul 2007 00:37:45 GMT Subject: bool behavior in Python 3000? In-Reply-To: <46961f33$0$90263$14726298@news.sunsite.dk> References: <46961f33$0$90263$14726298@news.sunsite.dk> Message-ID: > Alan Isaac skrev: >>http://www.python.org/dev/peps/pep-0285/ Nis J?rgensen wrote: > You forgot to quote this bit: [4)] Actually not. That is a different point. Ben seems bothered by this, but not me. I do not mind that True+1 is 2. I won't do it, but I do not object to it being possible. I do not like that True+True is 2. I do not like that bool(False-True) is True. I do not like that True and False are assignable, which clearly begs for bugs to pass unseen. >>> True, False = False, True >>> print True, False False True Who can like that???? I also generally agree with Steve, whose points keep being twisted beyond recognition. Also, tah is right about my underlying interest in arrays of bools (and more specifically, boolean matrices). I think Python 3000 is the right time to reconsider the "ideal world" that Guido mentions in PEP 285. Cheers, Alan Isaac From camronstone at gmail.com Mon Jul 30 15:39:28 2007 From: camronstone at gmail.com (Camron S) Date: Mon, 30 Jul 2007 12:39:28 -0700 Subject: =?utf-8?B?4pa6V2F0Y2ggU2F0ZWxsaXRlIENoYW5uZWxzIG9uIHlvdXIgUEMgLSBGUkVFIeKXhA==?= Message-ID: <1185824368.831647.140570@i13g2000prf.googlegroups.com> Finally Available! Who Else Wants to Watch Satellite TV On Your Computer Without Paying Monthly Fees... FOR FREE? For the very first time, Satellite TV is available on your computer with our "Cutting-Edge" Software! It's as Easy as 1...2...3... 1. Download our TVonPCPro software 2. Click on the channel you want to watch 3. Enjoy Satellite TV on your PC It's That Simple!! For More Details:http://tvfun.xt.cx From samwyse at gmail.com Thu Jul 12 08:27:11 2007 From: samwyse at gmail.com (samwyse) Date: Thu, 12 Jul 2007 12:27:11 -0000 Subject: allow scripts to use .pth files? In-Reply-To: <1184242814.390394.324200@n60g2000hse.googlegroups.com> References: <1183899193.766331.13210@22g2000hsm.googlegroups.com> <1183928022.719873.49470@i38g2000prf.googlegroups.com> <1184241309.629557.226820@w3g2000hsg.googlegroups.com> <1184242814.390394.324200@n60g2000hse.googlegroups.com> Message-ID: <1184243231.339269.159360@o61g2000hsh.googlegroups.com> On Jul 12, 7:20 am, John Machin wrote: > On Jul 12, 9:55 pm, samwyse wrote: > > > On Jul 8, 3:53 pm, John Machin wrote: > > > > I got the impression that the OP was suggesting that the interpreter > > > look in the directory in which it found the script. > > [...] > > > I got the impression that the problem was that the package was not > > > only not on sys.path but also not in the same directory as the script > > > that wanted to import it. Otherwise the OP's script.p?h file need only > > > contain ".\n" (or the path to the directory in which it resided!!), > > > and I doubt that he was proposing something so silly. > > > And as I'm sure you realize, those two impression slightly contradict > > each other. > > Your sureness is misplaced. Please explain. Oops, you're right. See my other post. From erexsha at gmail.com Wed Jul 18 15:14:16 2007 From: erexsha at gmail.com (Arash Arfaee) Date: Wed, 18 Jul 2007 12:14:16 -0700 Subject: Fast powerset function In-Reply-To: <1184393237.783461.210680@o61g2000hsh.googlegroups.com> References: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> <1184393237.783461.210680@o61g2000hsh.googlegroups.com> Message-ID: <266557d0707181214u56d41890p66613a0a9122c19e@mail.gmail.com> Hi All With your help I found lots of good method and algorithm. Also I found out if I exchange all for loop with while loop it make the program much faster and also it consumes less memory (almost half!) Just wanna thank you all. Cheers, Arash On 7/13/07, Mark Dickinson wrote: > > If you don't care about the order of the results, you can use a Gray > code (http://en.wikipedia.org/wiki/Gray_code): this has the advantage > of only adding or removing a single element to get from one subset to > the next. > > def powerset(s): > d = dict(zip( > (1< (set([e]) for e in s) > )) > > subset = set() > yield subset > for i in range(1, 1< subset = subset ^ d[i & -i] > yield subset > > >>> list(powerset('abc')) > [set([]), set(['a']), set(['a', 'b']), set(['b']), set(['c', 'b']), > set(['a', 'c', 'b']), set(['a', 'c']), set(['c'])] > > If you're using the subsets as they appear and don't need to store > them all at once, then it's significantly faster (on my machine) if > you replace the line subset = subset ^ d[i & -i] with an in-place > update: subset ^= d[i & -i]. > > Mark > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Fri Jul 13 10:07:43 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 13 Jul 2007 14:07:43 GMT Subject: variable naming query References: <1184236383.691966.56530@w3g2000hsg.googlegroups.com> <87lkdlkda7.fsf@benfinney.id.au> Message-ID: On 2007-07-12, Ben Finney wrote: >> self.__myvariable > > Indicates to the reader that the attribute '__myvariable' is > not available by that name outside the object, and name > mangling is automatically done to discourage its use from > outside the object. >From _Python Reference Manual (2.3.2) Reserved Classes of Identifiers: __* Class-private names. Names in this category, when used within the context of a class definition, are re-written to use a mangled form to help avoid name clashes between ``private'' attributes of base and derived classes. Further, from the _Python Tutorial (9.6) Private Variables_: (Buglet: derivation of a class with the same name as the base class makes use of private variables of the base class possible.) In other words, it's a misfeature that's best avoided. -- Neil Cerutti From markacy at gmail.com Mon Jul 16 11:02:25 2007 From: markacy at gmail.com (markacy) Date: Mon, 16 Jul 2007 08:02:25 -0700 Subject: running a Delphi part from Python ? In-Reply-To: <47dce$469b3a07$d443bb3a$26795@news.speedlinq.nl> References: <889c1$469b275c$d443bb3a$2876@news.speedlinq.nl> <469b2b65$0$21672$426a74cc@news.free.fr> <86c61$469b30d1$d443bb3a$15805@news.speedlinq.nl> <469b3530$0$26995$426a74cc@news.free.fr> <47dce$469b3a07$d443bb3a$26795@news.speedlinq.nl> Message-ID: <1184598145.577779.209070@w3g2000hsg.googlegroups.com> On 16 Lip, 11:33, Stef Mientki wrote: > tool69 wrote: > > Stef Mientki a ?crit : > > >> AFAIK, Scintilla is a code editor. > >> What I need looks more like ms-word, > >> handling lists, tables, images, formulas. > > >> thanks, > >> Stef Mientki > > > So you'll need the RichTextCtrl > > >http://www.wxpython.org/docs/api/wx.richtext.RichTextCtrl-class.html > > > See a sample in the demo under "Recent Additions". > > Well it's better, > - it has lists > - it has images, but no image editing, > It doesn't have > - drag & drop > - tables, > - formula editing, > - screen capture, > - links > - embedded code > - CSS > - .... > so unfortunately it's not yet sufficient :-( > > thanks, > Stef Mientki Of course You can always write one, that's succicient for Your needs, and make it available under GPL. ;-) Cheers, Marek From Xin.Zheng at jpl.nasa.gov Tue Jul 10 19:52:58 2007 From: Xin.Zheng at jpl.nasa.gov (Jason Zheng) Date: Tue, 10 Jul 2007 16:52:58 -0700 Subject: os.wait() losing child? Message-ID: This may be a silly question but is possible for os.wait() to lose track of child processes? I'm running Python 2.4.4 on Linux kernel 2.6.20 (i686), gcc4.1.1, and glibc-2.5. Here's what happened in my situation. I first created a few child processes with Popen, then in a while(True) loop wait on any of the child process to exit, then restart a child process: import os from subprocess import Popen pids = {} for i in xrange(3): p = Popen('sleep 1', shell=True, cwd='/home/user', stdout=file(os.devnull,'w')) pids[p.pid] = i while (True): pid = os.wait() i = pids[pid] del pids[pid] print "Child Process %d terminated, restarting" % i if (someCondition): break p = Popen('sleep 1', shell=True, cwd='/home/user', stdout=file(os.devnull,'w')) pids[p.pid] = i As I started to run this program, soon I discovered that some of the processes stopped showing up, and eventually os.wait() will give an error saying that there's no more child process to wait on. Can anyone tell me what I did wrong? From samfeltus at gmail.com Fri Jul 27 15:30:17 2007 From: samfeltus at gmail.com (SamFeltus) Date: Fri, 27 Jul 2007 12:30:17 -0700 Subject: Why PHP is so much more popular for web-development In-Reply-To: <46a8fdc1$0$4193$426a74cc@news.free.fr> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> <46a7b908$0$32130$426a34cc@news.free.fr> <1185453726.559470.122480@x40g2000prg.googlegroups.com> <1185473668.099991.240670@19g2000hsx.googlegroups.com> <46a8fdc1$0$4193$426a74cc@news.free.fr> Message-ID: <1185564617.709468.216630@l70g2000hse.googlegroups.com> I don't suggest Python is unconcerned with the casual user and the end user, only that this is where PHP's community excels. Learnig both as a newbie, I actually found PHP more confusing and difficult than Python. Programming in PHP reminds me of a game of trivial pursuit. Once you know a little Python, you can often guess how something new is going to be before you see it. From duncan.booth at invalid.invalid Mon Jul 2 06:52:42 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Jul 2007 10:52:42 GMT Subject: Bug in Python class static variable? References: <1183372758.251109.34550@z28g2000prd.googlegroups.com> Message-ID: Bruza wrote: > I am trying to define a class static variable. But the value of the > static variable seems to be only defined inside the file that the > class is declared. See the code below. When I run "python w.py", I > got: When you run "python w.py" the *script* w.py is loaded as the module __main__. Importing a module called 'w' creates a new module which is unrelated to __main__. If you want access to variables defined in the main script then you need to import __main__. Don't use 'from module import *': The import statements are executed when the interpreter reaches them in the source. Even if you fix your code to import from __main__, the values you try to import from __main__ won't exist when the import statement executes: the first 'from a import *' will load and execute all of module 'a', but when that executes 'from __main__ import *' it just imports names defined in the main script *before* a was imported. In general, don't try to do this: put all your classes into modules and just put minimal startup code into a script. From p.lavarre at ieee.org Tue Jul 10 13:06:41 2007 From: p.lavarre at ieee.org (p.lavarre at ieee.org) Date: Tue, 10 Jul 2007 10:06:41 -0700 Subject: Abort trap - Fatal Python error: GC object already tracked Message-ID: <1184087201.821731.45600@x35g2000prf.googlegroups.com> Is this interesting Python output? $ gc-object-already-tracked.py ********************************************************************** File "/Users/admin/Desktop/lxio/gc-object-already-tracked.py", line 770, in __main__.REDACTED Failed example: nqzhexes(self.send()) Expected: '... [redacted] ...'z Got: '... [redacted] ...' Fatal Python error: GC object already tracked Abort trap $ $ /usr/bin/env python --version Python 2.5.1 $ uname Darwin $ I can just avoid it, I don't need to solve it, but tell me I can help by solving it, and I'll look more closely. I can't just share all this source with you - I wrote a simulation for pay under c*nfidentiality - but if I find I can throw away most of the source and still produce the error, I could share that. From half.italian at gmail.com Sun Jul 8 21:09:56 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Mon, 09 Jul 2007 01:09:56 -0000 Subject: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc) In-Reply-To: <1183939608.088756.178320@m37g2000prh.googlegroups.com> References: <1183939608.088756.178320@m37g2000prh.googlegroups.com> Message-ID: <1183943396.388099.22040@a26g2000pre.googlegroups.com> On Jul 8, 5:06 pm, socialanxi... at gmail.com wrote: > i hope someone here can help me. > > basically, me and my friend have a summer project. > > in this project, we need something that would basically function as a > blender. we know we'll need to buy a motor that spins, but what we're > having trouble with is figuring out how to program it. we want to be > able to control the speed of the motor. how would we accomplish this? > > i'm new to all of this, so i'm having a hard time wrapping my mind > around how it'd be possible to program one of those things :\ > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then > turn the other direction. > > would you program it the same way you would on a personal computer > (via c, python, etc)? This might be interesting to you. http://www.makingthings.com/ ~Sean From mformetalhead at yahoo.de Wed Jul 18 19:50:14 2007 From: mformetalhead at yahoo.de (Mathias K.) Date: Thu, 19 Jul 2007 01:50:14 +0200 Subject: Running Python with XAMPP Message-ID: Hello everyone! I just installed Python 2.5 and i want to use Python to build websites. I could load mod_python successfully with Apache but i fail to let the .py-files to be executed! In /htdocs/python i got my test file: [code=python.py] from mod_python import apache def index(req): req.content_type = "text/html" req.write("") req.write("

    Python is running with mod_python...

    ") return apache.OK [/code] And then i got the following code in my httpd.conf: [code] AddHandler mod_python .py pythonHandler index pythonDebug On [/code] But when i type "http://localhost/python/python.py" it won't execute! My browser just shows me the source code. :-( Please, can anyone tell me what i have to do? Thanks in advance! ~ Mathias From afriere at yahoo.co.uk Sun Jul 15 22:24:59 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Sun, 15 Jul 2007 19:24:59 -0700 Subject: pattern match ! In-Reply-To: <4694BF24.1050706@igpm.rwth-aachen.de> References: <1184125206.034047.175340@n60g2000hse.googlegroups.com> <4694BF24.1050706@igpm.rwth-aachen.de> Message-ID: <1184552699.167329.49760@i38g2000prf.googlegroups.com> On Jul 11, 9:29 pm, Helmut Jarausch wrote: > import re > P=re.compile(r'(\w+(?:[-.]\d+)+)-RHEL3-Linux\.RPM') > S="hpsmh-1.1.1.2-0-RHEL3-Linux.RPM" > PO= P.match(S) > if PO : > print PO.group(1) Isn't a regexp overkill here when this will do: head = filename[:filename.index('-RHEL3')] Of course if you need to make it more generic (as in Jay's solution below), re is the way to go. From kyosohma at gmail.com Fri Jul 6 14:34:27 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 06 Jul 2007 18:34:27 -0000 Subject: Restarting a Python Application In-Reply-To: <1183500027.659730.211790@d30g2000prg.googlegroups.com> References: <1183498045.092504.229250@m36g2000hse.googlegroups.com> <1183500027.659730.211790@d30g2000prg.googlegroups.com> Message-ID: <1183746867.097492.134570@m36g2000hse.googlegroups.com> On Jul 3, 5:00 pm, Matimus wrote: > On Jul 3, 2:27 pm, kyoso... at gmail.com wrote: > > > > > Hi, > > > I packaged up an application I am developing into an executable. In > > the application, it has user configurable options. I would like a way > > to restart the application so that the new options the user chooses > > can be applied. Firefox can restart itself. Does anyone know how to > > accomplish this in Python? > > > Here is what I tried: > > > > > > exePath = os.path.join(os.getcwd(), 'myprogram.exe') > > subprocess.Popen(exePath) > > sys.exit() > > > > > > This didn't work. It closed the program, but another instance did not > > appear. > > > Tips would be appreciated. > > > Mike > > You could package your program into a function or class and just > restart that. > > [code] > # global flag for restart. > do_restart = False > > def main(args=None): > # program code > # set do_restart and return to restart > > if __name__ == "__main__": > retval = main() > while do_restart: > retval = main() > sys.exit(retval) > > [/code] Actually I am using wxPython for a GUI front-end. Thus, it is already in a class. I am not sure how to apply your idea to a program that is already running in an infinite event loop. Mike From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 27 03:46:14 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 27 Jul 2007 09:46:14 +0200 Subject: generating objects of a type from a name. In-Reply-To: <1185521023.517719.32320@d55g2000hsg.googlegroups.com> References: <1185495706.034366.58180@k79g2000hse.googlegroups.com> <1185521023.517719.32320@d55g2000hsg.googlegroups.com> Message-ID: <46a9a2ae$0$2993$426a74cc@news.free.fr> chris.lyon at spritenote.co.uk a ?crit : > On Jul 27, 1:59 am, tsuraan wrote: >> I'm not sure what a visual object is, but to create an instance of an >> object whose name is known, you can use "eval": >> >>>>> oname = 'list' >>>>> obj = eval(oname)() >>>>> obj >> [] >>>>> type(obj) >> >> >> Hope that helps! >> (snip) > Thanks for that. > > That's the answer. > Nope. That's a Q&D workaround for a lack of knowledge of Python's namespaces and lookup rules. The idiomatic solution is top use getattr() on the module defining the class: import visual clsname = 'sphere' cls = getattr(visual, clsname, None) if cls is None: print >> sys.stderr, "could not find %s in visual" else: a = cls() HTH From danb_83 at yahoo.com Mon Jul 16 20:04:08 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Mon, 16 Jul 2007 17:04:08 -0700 Subject: Semantics of file.close() In-Reply-To: <1184628945.314844.53300@k79g2000hse.googlegroups.com> References: <1184628945.314844.53300@k79g2000hse.googlegroups.com> Message-ID: <1184630648.012679.36210@g37g2000prf.googlegroups.com> On Jul 16, 6:35 pm, seerdec... at gmail.com wrote: > Hello, > > I'm a Python beginner and I'm trying to open, write and close a file > in a > correct manner. I've RTFM, RTFS, and I've read this thread:http://groups.google.ca/group/comp.lang.python/browse_thread/thread/7... > > I still cannot figure out the semantic of file.close(). As far as I > can > tell it is undocumented. It's documented. Not necessarily very well, but it's documented. Type help(file.close) at the interactive prompt. close(...) close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for further I/O operations. close() may be called more than once without error. Some kinds of file objects (for example, opened by popen()) may return an exit status upon closing. > How do I ensure that the close() methods in my finally clause do not > throw an exception? def quiet_close(fp): """Close a file, silently ignoring errors.""" try: fp.close() except IOError: pass From bj_666 at gmx.net Tue Jul 31 15:41:48 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 31 Jul 2007 19:41:48 GMT Subject: encode() question References: <1185900791.595830.21290@d55g2000hsg.googlegroups.com> <1185903926.955444.43620@22g2000hsm.googlegroups.com> Message-ID: <5h9hjsF3j641tU3@mid.uni-berlin.de> On Tue, 31 Jul 2007 10:45:26 -0700, 7stud wrote: > On Jul 31, 11:18 am, "Gabriel Genellina" > wrote: >> str.decode and unicode.encode should NOT exist, or at least issue a >> warning (IMHO). >> > > Yes, that sounds like a good idea. It sounds like horrible idea as those are the ones that are really needed. One could argue about `str.encode` and `unicode.decode`. But there are at least uses for `str.encode` like 'sting-escape', 'hex', 'bz2', 'base64' etc. Ciao, Marc 'BlackJack' Rintsch From jeffober at gmail.com Wed Jul 25 12:35:17 2007 From: jeffober at gmail.com (Jeff) Date: Wed, 25 Jul 2007 16:35:17 -0000 Subject: Closures / Blocks in Python In-Reply-To: References: <1185289112.771239.200260@n60g2000hse.googlegroups.com> <1185291146.753573.280420@n60g2000hse.googlegroups.com> <7tvjn4-qas.ln1@lairds.us> <1185374700.256479.228560@b79g2000hse.googlegroups.com> Message-ID: <1185381317.863430.194610@q75g2000hsh.googlegroups.com> True, and I should have known better than to not have thoroughly tested code I post to Usenet :). That being said, it was intended as a fast example of how a generator operates for someone coming from Ruby. From jayharvard1 at gmail.com Mon Jul 16 14:57:50 2007 From: jayharvard1 at gmail.com (jayharvard1 at gmail.com) Date: Mon, 16 Jul 2007 18:57:50 -0000 Subject: Binary blobs to jpeg Message-ID: <1184612270.455699.254560@r34g2000hsd.googlegroups.com> Hello All. I'm trying to create jpegs out of data that is stored in a binary blob format in an RDBMS (MS Access). I've tried writing the jpeg directly: while not rs.EOF: op = file(imgdir + "\\" + pic,"w") print >> op, rs.Fields[3].Value ##where rs.Fields[3].Value is the data in the blob from Access. When I try to write out this file, the jpeg doesn't turn out. Strangely, some of the colors partially render. You can see some outlines and backgrounds, but the full picture doesn't show. Most jpegs, however, show nothing (in an windows preview). I then tried opening the image with PIL.Image, with something like this: cmd.CommandText = sql rs=cmd.Execute()[0] while not rs.EOF: im = Image.open(StringIO.StringIO(rs.Fields[3].Value)) im.save("c:/projects/temp.jpg", 'JPEG', quality=90,progressive=1) This is the error I get, I believe at the Image.open() call: Traceback (most recent call last): File "", line 97, in run File "C:\Python25\Lib\bdb.py", line 366, in run exec cmd in globals, locals File "C:\Projects\scripts\main.py", line 25, in xdb.doImageTbl(db) File "C:\Projects\scripts\thunder.py", line 86, in doImageTbl im = Image.open(StringIO.StringIO(rs.Fields[3].Value)) File "C:\Python25\lib\site-packages\PIL\Image.py", line 1916, in open raise IOError("cannot identify image file") IOError: cannot identify image file For a little further information, I was able to accomplish this task in C#/.Net. A direct write to a file stream produced the exact jpeg image. So I know the data is not corrupt. I would like to avoid using the C#/.Net solution if possible. Any ideas what I'm doing wrong? Any help would be greatly appreciated. BTW, I'm using Python 2.5 and PIL 1.1.6 on a WinXp box. Thanks, jeh From kw at codebykevin.com Sun Jul 15 11:10:41 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sun, 15 Jul 2007 11:10:41 -0400 Subject: Python and Tkinter Primer/Tutorial? In-Reply-To: References: Message-ID: <5f852$469a38f6$4275d90a$5576@FUSE.NET> W. Watson wrote: > Is there a primer out there on these two items? I have the Python > tutorial, but would like either a Tkinter tutorial/primer to supplement > it, or a primer/tutorial that addresses both. Maybe there's even an > O'Reilly book on both? These are good resources: http://www.pythonware.com/library/tkinter/introduction/index.htm http://www.python.org/doc/life-preserver/ http://www.ferg.org/thinking_in_tkinter/index.html http://infohost.nmt.edu/tcc/help/lang/python/tkinter.html -- Kevin Walzer Code by Kevin http://www.codebykevin.com From martin at v.loewis.de Sat Jul 21 14:40:22 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 21 Jul 2007 20:40:22 +0200 Subject: Interpreting os.lstat() In-Reply-To: <+FB*rrjQr@news.chiark.greenend.org.uk> References: <1184806559.224636.266500@e9g2000prf.googlegroups.com> <46a057e8$0$19051$9b622d9e@news.freenet.de> <46A12C88.7070403@v.loewis.de> <+FB*rrjQr@news.chiark.greenend.org.uk> Message-ID: <46A25316.9000301@v.loewis.de> > Absolutely, which is why I consider it foolish for the OP to be > trying to deduce the meaning of os.stat by looking at the output > of the stat program, rather than studying the man page for the > stat system call. Ah, ok. I missed that the OP had brought stat(1) into the discussion. Now it's all clear. Martin From gggg.iiiii at gmail.com Mon Jul 23 21:03:19 2007 From: gggg.iiiii at gmail.com (G) Date: Mon, 23 Jul 2007 21:03:19 -0400 Subject: Subclassing int Message-ID: <4a7f84ac0707231803x7083a688kc91965a5d78e679@mail.gmail.com> Hi, I am trying to subclass int to allow a constructor to accept None. I am trying the following class INT(int): def __init__(self, x): if x is None: return None else: int.__init__(x) b = INT(x=None) When i run the previous code i get the following error: b = INT(x=None) TypeError: int() argument must be a string or a number, not 'NoneType'. Do you guys know why the if statement is not evaluated? Thanks for your help -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Tue Jul 3 09:48:47 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 03 Jul 2007 13:48:47 GMT Subject: what is wrong with that r"\" References: Message-ID: On 2007-07-03, alf wrote: > question without words: > > >>> r"\" > File "", line 1 > r"\" > ^ > SyntaxError: EOL while scanning single-quoted string > >>> r"\ " > '\\ ' >From the Python Language Reference 2.4.1 String Literals: When an "r" or "R" prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string. For example, the string literal r"\n" consists of two characters: a backslash and a lowercase "n". String quotes can be escaped with a backslash, but the backslash remains in the string; for example, r"\"" is a valid string literal consisting of two characters: a backslash and a double quote; r"\" is not a valid string literal (even a raw string cannot end in an odd number of backslashes). Specifically, a raw string cannot end in a single backslash (since the backslash would escape the following quote character). Note also that a single backslash followed by a newline is interpreted as those two characters as part of the string, not as a line continuation. -- Neil Cerutti Ask about our plans for owning your home --sign at mortgage company From thomas.bugzilla at gmx.net Wed Jul 18 06:16:39 2007 From: thomas.bugzilla at gmx.net (Thomas) Date: Wed, 18 Jul 2007 12:16:39 +0200 Subject: XL-RPC Recipe Message-ID: Hi list! I'm struggling with a recipe from the Python Cookbook (2nd ed.) concerning XML-RPC. It's recipe 15.2 "Serving XML-RPC Requests", and since I thought it's a popular book some other folks might have discovered (and probably solved) the same issue. The recipe provides server and client code, and I get an error when trying the following client request: print server.python_string.join(['I', 'like it!'], " don't ") (In the server code the string name space is mapped into the 'python_string' member with "import string; self.python_string = string"). The error report says: xmlrpclib.Fault: :method "python_string.join" is not supported'> This happens with all the string methods in StringFunctions.python_string. Is there a general issue with mapping name spaces into an RPC object? Or am I missing a major point here? I tried all of this on a fairly up-to-date Linux with a stock Python 2.5 (also tried with WinXP/cygwin/Python2.5.1 and with a Stackless 2.5.1, always with same outcome, so I don't believe it's an issue of a local installation). Any hints? =Thomas From bignose+hates-spam at benfinney.id.au Mon Jul 9 19:59:04 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 10 Jul 2007 09:59:04 +1000 Subject: Broken MUA interactions References: <1183498045.092504.229250@m36g2000hse.googlegroups.com> <94ccbe710707071511o3beee718wc12f15082b3c6e18@mail.gmail.com> <87vecvmqw5.fsf_-_@benfinney.id.au> <4866bea60707090648v772e81d2r261e8d927310591c@mail.gmail.com> Message-ID: <87d4z1m8mv.fsf@benfinney.id.au> "Chris Mellon" writes: > On 7/9/07, Gabriel Genellina wrote: > > No, it's not correct to modify Reply-To. Some reasons: > > http://www.unicom.com/pw/reply-to-harmful.html > > None of those are reasons, they're opinions and weary old excuses. They're old, but not weary, because they're now supported by the internet message standards, which spell out exactly what Reply-To and List-Post are for. Reply-To, if used, is to be set by the message author. Since a message transport system may only add fields to the header, not arbitrarily modify existing fields, Reply-To can't be munged. List-Post is to be used to give the email address for posting messages to the mailing list. Please, let's stop arguing what's already been decided. Every behaviour you ask for is already supported by the existing standards. The "common case" you speak of is fully supported by the unambiguous List-Post field. If your MUA is not using the information, provided in every message from the mailing list, to do what you want, don't ask mailing list admmministrators to accomodate your broken MUA. -- \ "Pinky, are you pondering what I'm pondering?" "I think so, | `\ Brain, but culottes have a tendency to ride up so." -- _Pinky | _o__) and The Brain_ | Ben Finney From george.sakkis at gmail.com Fri Jul 13 21:24:29 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Sat, 14 Jul 2007 01:24:29 -0000 Subject: Function parameter type safety? In-Reply-To: <1184277163.803229.318660@g4g2000hsf.googlegroups.com> References: <1184277163.803229.318660@g4g2000hsf.googlegroups.com> Message-ID: <1184376269.675070.35860@d55g2000hsg.googlegroups.com> On Jul 12, 5:52 pm, Robert Dailey wrote: > Hi, > > Is there a way to force a specific parameter in a function to be a > specific type? Yes; have a look at typecheck (http://oakwinter.com/code/typecheck/) and FormEncode (http://formencode.org/Validator.html). George From jeremy+complangpython at jeremysanders.net Mon Jul 16 11:14:11 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 16 Jul 2007 16:14:11 +0100 Subject: questions about functions inside a function References: Message-ID: fdu.xiaojf at gmail.com wrote: > What I want is, the value of i should be bounded to the anonymous > function. And the output should like this: ... > How to achieve this? This doesn't answer your question (others have), but another (perhaps clearer) way to do such things is something like class MyFunc(object): """A function object.""" def __init__(self, val): self.val = val def __call__(self): """Return value squared""" return self.val**2 a = [] for i in range(4): a.append(MyFunc(i)) for f in a: f() Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From ptmcg at austin.rr.com Tue Jul 3 12:30:02 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Tue, 03 Jul 2007 09:30:02 -0700 Subject: Pretty Scheme, ??? Python In-Reply-To: References: <46895e12$0$5078$ba4acef3@news.orange.fr> <_Ddii.36114$G23.10348@newsreading01.news.tds.net> <1183418938.911025.55340@w5g2000hsg.googlegroups.com> <1183469909.444902.147310@57g2000hsv.googlegroups.com> Message-ID: <1183480202.655654.100160@k29g2000hsd.googlegroups.com> On Jul 3, 11:08 am, Neil Cerutti wrote: > > C:\WINNT\system32\cmd.exe /c python wae.py > ********************************************************************** > File "wae.py", line 6, in __main__ > Failed example: > parse('(+ 3 45)') > Exception raised: > Traceback (most recent call last): > File "c:\edconn32\python25\lib\doctest.py", line 1212, in __run > compileflags, 1) in test.globs > File "", line 1, in > parse('(+ 3 45)') > File "wae.py", line 122, in parse > return (wae + StringEnd()).parseString(s).asList()[0] > File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 906, in p > arseString > loc, tokens = self._parse( instring.expandtabs(), 0 ) > File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 784, in _ > parseNoCache > loc,tokens = self.parseImpl( instring, preloc, doActions ) > File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 1961, in > parseImpl > loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPr > eParse=False ) > File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 784, in _ > parseNoCache > loc,tokens = self.parseImpl( instring, preloc, doActions ) > File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 2204, in > parseImpl > return self.expr._parse( instring, loc, doActions, callPreParse=False ) > File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 784, in _ > parseNoCache > loc,tokens = self.parseImpl( instring, preloc, doActions ) > File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 2070, in > parseImpl > ret = e._parse( instring, loc, doActions ) > File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 810, in _ > parseNoCache > tokens = fn( instring, tokensStart, retTokens ) > File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 658, in t > mp > return f(t) > File "wae.py", line 118, in > binop.setParseAction(lambda t: BinOp(t.op, t.lhs, t.rhs)) > File "wae.py", line 73, in __init__ > '-': (operator.sub, 'Sub')}[op] > KeyError: '' > ********************************************************************** > > op ought to be '+' or '-'. In fact, testing showed than none of > the result names for binop are being set correctly. > > -- > Neil Cerutti > The word "genius" isn't applicable in football. A genius is a guy like Norman > Einstein. --Joe Theisman I think the problem is with your Groups, that they are wrapping the ParseResults into a single-element list. Try either of the following (but not both!): 1. Remove Group from the definitions of binop and with_. binop = ( LPAR + oneOf("+ -").setResultsName('op') + wae.setResultsName('lhs') + wae.setResultsName('rhs') + RPAR ) with_ = ( LPAR + "with" + LPAR + id_.setResultsName('bound_id') + wae.setResultsName('named_expr') + RPAR + wae.setResultsName('bound_body') + RPAR ) 2. Change the parse actions to deref the 0'th element of t for binop and with_. num.setParseAction(lambda t: Num(int(t.number))) id_.setParseAction(lambda t: Id(t.name)) binop.setParseAction(lambda t: BinOp(t[0].op, t[0].lhs, t[0].rhs)) with_.setParseAction(lambda t: With(t[0].bound_id, t[0].named_expr, t[0].bound_body)) As a troubleshooting measure, you can also create an explicit method, and then decorate it with pyparsing's built-in @traceParseAction decorator. @traceParseAction def test(t): return BinOp(t.op,t.lhs,t.rhs) This should print out information on the arguments being passed to test, and the results being returned. -- Paul From tunuyan-house at hotmail.com Mon Jul 16 18:31:30 2007 From: tunuyan-house at hotmail.com (Natalia) Date: Mon, 16 Jul 2007 15:31:30 -0700 Subject: www.cerocom.com Message-ID: <1184625090.021836.250170@k79g2000hse.googlegroups.com> ...................................... www.cerocom.com ...................................... You will be able to ask yourself: Is Internet a good investment for my company? So that an investment would have to do I of this type? Really is going to serve to me to have a Web site? So that to be in Internet? See some of the main advantages have a Web site: ? Increase the productivity and to generate more businesses with the implementation of collaboration rofe and integration maximizing the value of Internet and networks IP. ? Offer solutions of Internet, integration and collaboration in accordance with our clients, anyone is their size or trains, to rofesional r to integrate their applications, to fortify their present position in the market or to impel their growth, assuring trustworthiness, discharge rofesional qualification, and customized service. I invite it to cross the Web site and interiorice of the services available. www.cerocom.com Contact: Commercial direction: Viamonte 783 Piso 3? Capital Federal (C1053ABO) Bs. As. Argentina Tel/Fax: (54.11) 4322.1201 Celular: (54-9-11) (15) 5006.4384 Mail: cerocom at cerocom.com Web Site: www.cerocom.com From duncan.booth at invalid.invalid Mon Jul 16 14:02:33 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Jul 2007 18:02:33 GMT Subject: The ** operator ambiguous? References: <1184607614.904143.219330@w3g2000hsg.googlegroups.com> Message-ID: Robert Dailey wrote: > However, I have no idea what the > ** operator is here. I know that when you specify ** as a parameter in > a function definition, it represents a dictionary of parameters passed > in. However, in this example it is NOT being used in a function > definition. It is being used when passing variables into a function. > Can someone explain what this means? I looked in the documentation but > I couldn't find anything. > It is in the documentation. Look in the reference manual section "5.3.4 Calls" (http://docs.python.org/ref/calls.html): > If the syntax "*expression" appears in the function call, "expression" > must evaluate to a sequence. Elements from this sequence are treated > as if they were additional positional arguments; if there are > postional arguments x1,...,xN , and "expression" evaluates to a > sequence y1,...,yM, this is equivalent to a call with M+N positional > arguments x1,...,xN,y1,...,yM. > > A consequence of this is that although the "*expression" syntax > appears after any keyword arguments, it is processed before the > keyword arguments (and the "**expression" argument, if any - see > below). So: > >>>> def f(a, b): > ... print a, b > ... >>>> f(b=1, *(2,)) > 2 1 >>>> f(a=1, *(2,)) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: f() got multiple values for keyword argument 'a' >>>> f(1, *(2,)) > 1 2 > > It is unusual for both keyword arguments and the "*expression" syntax > to be used in the same call, so in practice this confusion does not > arise. > > If the syntax "**expression" appears in the function call, > "expression" must evaluate to a (subclass of) dictionary, the contents > of which are treated as additional keyword arguments. In the case of a > keyword appearing in both "expression" and as an explicit keyword > argument, a TypeError exception is raised. From davefowler at gmail.com Fri Jul 20 14:45:47 2007 From: davefowler at gmail.com (godavemon) Date: Fri, 20 Jul 2007 18:45:47 -0000 Subject: path error In-Reply-To: <1184956953.317214.69370@i38g2000prf.googlegroups.com> References: <1184956953.317214.69370@i38g2000prf.googlegroups.com> Message-ID: <1184957147.140331.74420@i38g2000prf.googlegroups.com> On Jul 20, 11:42 am, godavemon wrote: > I'm on an intel macbook using OS X 10.4 and for some reason my path is > being interpreted incorrectly. See the example: > > dave at jared3-jared$ pwd > /Users/dave/til/jared <----- dirname = jared > dave at jared3-jared$ python > ...>>> import os > >>> os.path.abspath('') > > '/Users/dave/til/Jared' <----- dirname = Jared > > python is capitalizing my jared directory. It has worked for a long > time but suddenly doesn't. I'm working on the project over SVN, could > it be some kind of incompatibility with someone who submitted using > windows or something? Any solutions for this? Also my python version is Python 2.4.4 (#1, Oct 18 2006, 10:34:39) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. From horpner at yahoo.com Fri Jul 27 05:34:17 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 27 Jul 2007 09:34:17 GMT Subject: adding a docstring to an instancemethod References: <1185361537.733690.238280@k79g2000hse.googlegroups.com> <1185438522.978804.118010@19g2000hsx.googlegroups.com> <1185472092.427646.266270@g4g2000hsf.googlegroups.com> Message-ID: On 2007-07-27, Gabriel Genellina wrote: > En Thu, 26 Jul 2007 14:48:12 -0300, jelle > escribi?: > >> Hi Gabriella, >> thanks for pointing me in the right direction: > > Twice in a week... I'll have to revise my own masculinity... The trumpet shall sound! -- Neil Cerutti From stargaming at gmail.com Wed Jul 25 11:19:40 2007 From: stargaming at gmail.com (Stargaming) Date: 25 Jul 2007 15:19:40 GMT Subject: Flatten a list/tuple and Call a function with tuples References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> Message-ID: <46a76a0c$0$1471$9b622d9e@news.freenet.de> On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote: > Hi, > > I am wondering how do I 'flatten' a list or a tuple? For example, I'd > like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4]. A recursive function, always yielding the first element of the list, could do the job. See the ASPN Python Cookbook for a few implementations. http://aspn.activestate.com/ASPN/search? query=flatten§ion=PYTHONCKBK&type=Subsection > Another question is how do I pass a tuple or list of all the aurgements > of a function to the function. For example, I have all the arguments of > a function in a tuple a=(1,2,3). Then I want to pass each item in the > tuple to a function f so that I make a function call f(1,2,3). In perl > it is a given, but in python, I haven't figured out a way to do it. > (Maybe apply? but it is deprecated?) >>> def foo(a, b, c): print a, b, c ... >>> t = (1, 2, 3) >>> foo(*t) 1 2 3 Have a look at the official tutorial, 4.7.4 http://www.python.org/doc/ current/tut/node6.html#SECTION006740000000000000000 > Thanks, > cg HTH, Stargaming From aisaac at american.edu Wed Jul 11 02:52:30 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 11 Jul 2007 06:52:30 GMT Subject: bool behavior in Python 3000? In-Reply-To: <5ficedF3cram2U1@mid.individual.net> References: <5ficedF3cram2U1@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Is there any type named "bool" in standard Python? >>> type(True) Cheers, Alan Isaac From martin at v.loewis.de Tue Jul 17 00:59:07 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 17 Jul 2007 06:59:07 +0200 Subject: Implementaion of random.shuffle In-Reply-To: References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> <87d4ys9z46.fsf@mulj.homelinux.net> Message-ID: <469C4C9B.5020605@v.loewis.de> >> 2**19937 being a really huge number, it's impossible to exhaust the >> Mersenne twister by running it in sequence. > > "Impossible"? Unfeasible. Regards, Martin From stargaming at gmail.com Wed Jul 11 04:06:30 2007 From: stargaming at gmail.com (Stargaming) Date: Wed, 11 Jul 2007 10:06:30 +0200 Subject: bool behavior in Python 3000? In-Reply-To: References: <5ficp9F3cram2U2@mid.individual.net> <469472f4$0$1293$9b622d9e@news.freenet.de> Message-ID: <46948f89$0$13141$9b622d9e@news.freenet.de> Alan Isaac schrieb: > Stargaming wrote: > >> I think Bjoern just wanted to point out that all those binary boolean >> operators already work *perfectly*. > > > >>>> bool(False-True) > > True > > But reread Steven. > > Cheers, > Alan Isaac What would you expect this operation to return then? The * and + operations described in the previously mentioned document (http://en.wikipedia.org/wiki/Two-element_Boolean_algebra) work as you'd expect them to do, if you explicitly state "hey, this should be a boolean algebra operation". And that's okay in my opinion. If you could describe what's wrong about that result, we could probably help better. Steven just suggests another (IMO totally unrelated) implementation of bool types. A point that Bjoern does not even touch here. Besides, his implementations fails at the * operation. Bjoern does not (sorry, if I say anything wrong, Bjoern) say the current behaviour is right or wrong. He just says that you can make Python aware of boolean algrebra utilizing `bool()` easily. bool-ly, Stargaming From cito at online.de Thu Jul 5 21:20:13 2007 From: cito at online.de (Christoph Zwerschke) Date: Fri, 06 Jul 2007 03:20:13 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: <1183673210.409169.51830@n2g2000hse.googlegroups.com> References: <1183668029.470160.218230@q69g2000hsb.googlegroups.com> <1183673210.409169.51830@n2g2000hse.googlegroups.com> Message-ID: Alex Popescu wrote: > Probably the simplest solution would be to create a new exception and > wrapping the old one and the additional info. Unfortunately, this > may have a huge impact on 3rd party code that was catching the > original exception. So, I think you should create an utility > factory-like function that is either creating a new exception > instance as the one caught and with the additional information, Right, I have gone with that (see the example with the PoliteException class somewhere below). > or an utility that knows how to modify the caught exception according > to its type. I guess you mean something like this (simplified): except Exception, e: if getattr(e, 'reason'): e.reason += "sorry" else: e.message += "sorry" The problem is that these attribute names are not standardized and can change between Python versions. Not even "args" is sure, and if a class has "message" it does not mean that it is displayed. Therefore I think the first approach is better. > In the first case you will need somehow to tell to the new instance > exception the real stack trace, because by simply raising > a new one the original stack trace may get lost. Yes, but thats a different problem that is easy to solve. -- Chris From eviltabbycat at gmail.com Mon Jul 2 09:12:07 2007 From: eviltabbycat at gmail.com (evil tabby cat) Date: Mon, 02 Jul 2007 13:12:07 -0000 Subject: python svn pre-commit hook Message-ID: <1183381927.511963.115070@i13g2000prf.googlegroups.com> This is a python script which is fired off from a batchfile pre- commit.bat on Windows2000 server. Everything I've read says that it should work & each part does work when tested individually. But when it runs within subversion this statement always ends with this log_msg being an empty string. log_msg = os.popen(log_cmd, 'r').readline().rstrip('\n') Help. :-) rem pre-commit.bat c:\python23\python c:\repository\hooks\check-comments.py %1 %2 if errorlevel 1 goto :ERROR exit 0 :ERROR echo Error found in commit 1>&2 exit 1 #check-comments.py import sys, os, string, re SVNLOOK='c:\\subversion\\bin\\svnlook.exe' # return true or false if this passed string is a valid comment def check(comment): #define regular expression p = re.compile('\A[iI][sS][sS][uU][eE] \d+ - \w+') return (p.match(comment) != None) #returns false if doesn't match def result(r): if r == 1: sys.stderr.write ("Comments must have the format of 'Issue X - Comment text' where X is the issue number.") sys.exit(r) def main(repos, txn): log_cmd = '%s log -t "%s" "%s"' % (SVNLOOK, txn, repos) log_msg = os.popen(log_cmd, 'r').readline().rstrip('\n') if check(log_msg): result(0) else: result(1) if __name__ == '__main__': if len(sys.argv) < 3: sys.stderr.write("Usage: %s REPOS TXN\n" % (sys.argv[0])) else: main(sys.argv[1], sys.argv[2]) From aahz at pythoncraft.com Tue Jul 31 15:10:11 2007 From: aahz at pythoncraft.com (Aahz) Date: 31 Jul 2007 12:10:11 -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> Message-ID: In article <1i23wyk.avc945i4dwsiN%aleax at mac.com>, Alex Martelli 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). Ayup. My current job didn't even bother asking for references, largely because my boss knew me from the Python community. -- 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 mccredie at gmail.com Thu Jul 19 19:56:59 2007 From: mccredie at gmail.com (Matt McCredie) Date: Thu, 19 Jul 2007 16:56:59 -0700 Subject: Efficiently removing duplicate rows from a 2-dimensional Numeric array In-Reply-To: <76EEE12626B7A84EBACE67EC513AE53D060F8CE9@WIN-MSG-20.wingroup.windeploy.ntdev.microsoft.com> References: <76EEE12626B7A84EBACE67EC513AE53D060F8CE9@WIN-MSG-20.wingroup.windeploy.ntdev.microsoft.com> Message-ID: <9e95df10707191656y6c7b641dm8318f09ca23ff34@mail.gmail.com> Could you use a set of tuples? >>> set([(1,2),(1,3),(1,2),(2,3)]) set([(1, 2), (1, 3), (2, 3)]) Matt On 7/19/07, Alex Mont wrote: > > I have a 2-dimensional Numeric array with the shape (2,N) and I want to > remove all duplicate rows from the array. For example if I start out with: > > [[1,2], > > [1,3], > > [1,2], > > [2,3]] > > > > I want to end up with > > [[1,2], > > [1,3], > > [2,3]]. > > > > (Order of the rows doesn't matter, although order of the two elements in > each row does.) > > > > The problem is that I can't find any way of doing this that is efficient > with large data sets (in the data set I am using, N > 1000000) > > The normal method of removing duplicates by putting the elements into a > dictionary and then reading off the keys doesn't work directly because the > keys ? rows of Python arrays ? aren't hashable. > > The best I have been able to do so far is: > > > > def remove_duplicates(x): > > d = {} > > for (a,b) in x: > > d[(a,b)] = (a,b) > > return array(x.values()) > > > > According to the profiler the loop takes about 7 seconds and the call to > array() 10 seconds with N=1,700,000. > > > > Is there a faster way to do this using Numeric? > > > > -Alex Mont > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From rng at li.ru Fri Jul 20 09:17:43 2007 From: rng at li.ru (Hendrickson Osmond) Date: Fri, 20 Jul 2007 08:17:43 -0500 Subject: No subject Message-ID: <46A0B5F7.7070302@mitutoyo.com.sg> -------------- next part -------------- A non-text attachment was scrubbed... Name: cheque.pdf Type: application/pdf Size: 4600 bytes Desc: not available URL: From skpatel20 at gmail.com Wed Jul 18 03:05:15 2007 From: skpatel20 at gmail.com (Sanjay) Date: Wed, 18 Jul 2007 00:05:15 -0700 Subject: Posted messages not appearing in this group Message-ID: <1184742315.618696.202600@z24g2000prh.googlegroups.com> Hi All, I tried posting in this group twice since last week, but the messages did not appear in the forum. Don't know why. Trying this message again... Sanjay From steve at holdenweb.com Fri Jul 13 20:42:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Jul 2007 20:42:41 -0400 Subject: A Python newbie ask a simple question In-Reply-To: <82d28c40707131151u5171b36emb08cc5269bdb5109@mail.gmail.com> References: <1184351716.298630.80670@z28g2000prd.googlegroups.com> <82d28c40707131151u5171b36emb08cc5269bdb5109@mail.gmail.com> Message-ID: Jeff McNeil wrote: > The raw_input built-in returns a string. The '[0]' subscript returns > the first character in the user supplied response as strings support > indexing. > > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> mystr = "asdf" >>>> mystr[0] > 'a' > >>>> raw_input("Another one, please: ")[0] > Another one, please: ASDF > 'A' > > -Jeff > > On 7/13/07, xing93111 at gmail.com wrote: >> what does the statement "choice = raw_input(prompt)[0]" mean? I don't >> know why there is a '[0]' in the statement. >> Of course it's not a very good way to handle input from a "defensive programming" point of view, since it fails and raises an exception when the user hits return: >>> a = raw_input("Bzzzt:")[0] Bzzzt: Traceback (most recent call last): File "", line 1, in IndexError: string index out of range >>> The best way to learn Python is to spend time typing it in to an interactive interpreter session. 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 gggg.iiiii at gmail.com Tue Jul 31 14:57:47 2007 From: gggg.iiiii at gmail.com (G) Date: Tue, 31 Jul 2007 14:57:47 -0400 Subject: With Statement Contexts and Context Managers Message-ID: <4a7f84ac0707311157s5cdd770fw96acaed00785bc73@mail.gmail.com> Hi, Could somebody please point me to a good resource to read about the contexts, context managers, and with_statement Best Rgd, G. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rts.cts at gmail.com Tue Jul 10 14:03:20 2007 From: rts.cts at gmail.com (Daryl) Date: Tue, 10 Jul 2007 18:03:20 -0000 Subject: C Extension Seg Faults Message-ID: <1184090600.764290.160210@d30g2000prg.googlegroups.com> I'm having trouble tracking down some segmentation faults with a C extension. I can see where it's failing but don't know how to fix it. Basically, my python programme builds a pair of large tuples of tuples. I want to unpack these tuples and process them. The code in question looks something like: ... snip ... SizeN = PyTuple_Size(PlacementN); SizeP = PyTuple_Size(PlacementP); for(ixN = 0; ixN < SizeN; ixN++) { LenN = (int) PyTuple_Size(PyList_GetItem(PlacementN, ixN)); for(Count = 0; Count < LenN; Count++) *(GatesN+Count) = (int) PyInt_AsLong(PyTuple_GetItem(PyTuple_GetItem(PyList_GetItem(PlacementN, ixN), Count), GATE)); for(ixP = 0; ixP < SizeP; ixP++) { printf("I feel lucky (%d)...", ixP); fflush(stdout); LenP = (int) PyTuple_Size(PyList_GetItem(PlacementP, ixP)); printf("Ta-Da!\n"); fflush(stdout); for(Count = 0; Count < LenP; Count++) *(GatesP+Count) = (int) PyInt_AsLong(PyTuple_GetItem(PyTuple_GetItem(PyList_GetItem(PlacementP, ixP), Count), GATE)); [ MUCH PROCESSING ] ... snip ... The inner loop runs a few hundred times (263) then fails with a segmentation fault. I've trolled through the documentation online and in the various .h files but can't seem to find anything. Anybody have an idea what really obvious foolish thing I'm doing? Thanks, -Daryl From kw at codebykevin.com Mon Jul 9 17:08:20 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 09 Jul 2007 17:08:20 -0400 Subject: Choosing Tkinter over wxPython... Message-ID: <3e384$4692a3c4$4275d90a$11745@FUSE.NET> I've spent some time playing with both, and while wxPython is nice, Tkinter just seems to fit my head better, and with appropriate selection of widgets and interface design, seems to yield up perfectly usable GUI's. Can anyone else who finds Tkinter better for them than wxPython (or the other toolkits) explain why it works for them? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From hniksic at xemacs.org Tue Jul 17 17:48:40 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Tue, 17 Jul 2007 23:48:40 +0200 Subject: Semantics of file.close() References: <1184628945.314844.53300@k79g2000hse.googlegroups.com> Message-ID: <87veciem6f.fsf@mulj.homelinux.net> "Evan Klitzke" writes: > You should take a look at the man pages for close(2) and write(2) (not > fclose). Generally you will only get an error in C if you try to close > a file that isn't open. In Python you don't even have to worry about > that -- if you close a regular file object more than once no exception > will be thrown, _unless_ you are using os.close(), which mimics the C > behavior. If you are out of space, in C you will get an error returned > by the call to write (even if the data isn't actually flushed to disk > yet by the kernel). I'm pretty sure Python mimics this behavior, so an > exception would be called on the write, not on the close operation. But the writes are buffered, and close causes the buffer to be flushed. file.close can throw an exception just like fclose, but it will still ensure that the file is closed. > > How do I ensure that the close() methods in my finally clause do > > not throw an exception? In the general case, you can't. Preferably you'd want to make sure that both files are closed: try: f1 = file(...) try: f2 = file(...) ... do something with f1 and f2 ... finally: f2.close() finally: f1.close() Now file.close would be called on both files regardless of where an exception occurs. If you use Python 2.5, this would be a good use case for the "nested" function from the contextlib module, which allow you to write the above more elegantly: from __future__ import with_statement from contextlib import nested with nested(file(...), file(...)) as (f1, f2): ... do something with f1 and f2 ... Finally, most of this applies to files open for writing, where Python is forced to flush the cache on close. If the file is opened for reading, you can assume that the exception will not be raised (and you can safely ignore it with `try: f.close() except IOError: pass' if you want to be sure; after all, you can't lose data when closing a file open for reading). From gagsl-py2 at yahoo.com.ar Mon Jul 30 01:01:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 30 Jul 2007 02:01:19 -0300 Subject: problems with logging module References: <1185744598.663382.126920@19g2000hsx.googlegroups.com> Message-ID: En Sun, 29 Jul 2007 18:29:58 -0300, Alia Khouri escribi?: > I've been struggling with the logging module in the stdlib which seems > to me rather counter-intuitive: > > For some reason it refuses to recognize configuration options when > they are set inside a class so I have had to initialize logging and > set the configuration options in the global scope of my module with > logging.basicConfig. That looks very strange. > Here's what I did within the class setup method: Do you mean in its __init__ method? Are you sure an instance of that class is actually created? > self.log = logging.getLogger() > > # format > log_format= self.local.format If you are saying that, later, using self.local.format is different that using log_format, that's hard to believe (unless self/local/format are insane objects...) > self.log gets initialized but the formatting options do not get > recognized... this is a pain... To see what's going on, try using this old-fashioned debug technique: a few print statements. -- Gabriel Genellina From maravera at prodigy.net Wed Jul 11 19:42:43 2007 From: maravera at prodigy.net (Michael Angelo Ravera) Date: Wed, 11 Jul 2007 16:42:43 -0700 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <1182544384.709759.235300@o11g2000prd.googlegroups.com> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: <1184197363.256796.39820@k79g2000hse.googlegroups.com> On Jun 22, 1:33 pm, James Harris wrote: > I have a requirement to store timestamps in a database. Simple enough > you might think but finding a suitably general format is not easy. The > specifics are > > 1) subsecond resolution - milliseconds or, preferably, more detailed > 2) not bounded by Unix timestamp 2038 limit > 3) readable in Java > 4) writable portably in Perl which seems to mean that 64-bit values > are out > 5) readable and writable in Python > 6) storable in a free database - Postgresql/MySQL > > The formats provided by the two database systems are such as 8-byte or > 12-byte values which, even if I could get Perl to work with I guess it > would be messy. Keeping to 32-bit values should give me portability > and be easy enough to work with without obscuring the program logic. > Since 32 bits of microseconds is less than 50 days I have to store two > 32-bit values. How to split them? The option I favour at the moment is > to split days and parts of days like this: > > a) store, as a 32-bit number, days since a virtual year zero (there is > no year zero in common era time Common_Era>). This allows over five million years plus and minus. > Still not completely general, I know. > b) store parts of days as another 32-bit value. Its range would have > to go to 86401 seconds - the number of seconds in a leap day. This > means each 'tick' would be around 21 microseconds. For regularity I > could make the ticks 25 microseconds so there would be 40,000 in a > second and 3,456,000,000 in a day; and, finally, the counter could > tick about 5 hours into the next day if not caught. > > Any thoughts on a better way to do this? (Please reply-all. Thanks). The best timestamp of which I am aware is microseconds since the calendarical convergence back in 4713 BCE. This is the format used on the old Tandem systems. Tandem chose to begin days at midnight, so with some small tweaking, you can calculate the Julian day (by adding 12 hours) also, but you can choose to begin them at noon (as the official Julian day does). It is easily represented in 64 bits and won't overflow until well past 10000 CE. It also has the advantage of making for easy easy time arithmetic and for reasonable conversion into any native format with resolution no better than about 10 nanoseconds. You have to be careful, if your resolution is better than that (you might overflow a 64-bit number if you try to go to your native format by multiplying first), but it is quite useful. The magic number for Unix-32 format is 210866760000000000 (or that divided by 1000 or 1000000 depending upon which way you go) From tenax.raccoon at gmail.com Thu Jul 5 18:30:23 2007 From: tenax.raccoon at gmail.com (Jason) Date: Thu, 05 Jul 2007 15:30:23 -0700 Subject: The best platform and editor for Python In-Reply-To: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> Message-ID: <1183674623.700441.47650@g4g2000hsf.googlegroups.com> On Jul 1, 1:10 pm, kimiraikkonen wrote: > Hi, > For experienced with Pyhton users, which developing software and > enviroment would you suggest for Pyhton programming? Compiler+Editor > +Debugger. That would depend on what platform(s) you would be developing on, what development environments you were used to, and so forth. I personally enjoy working in Eclipse with the PyDev plugin. Other people love Emacs. I know folk who you'll only pry their vim editors from their cold, dead fingers. For people dipping their toes into the Python pool, I recommend using Idle. It comes with Python itself, and has a built-in debugger (see the Debug menu), syntax highlighting, and other goodies. It's certainly enough to write your programs in. Quite frankly, you can use Windows Notepad to write your Python programs. Python itself is just a language. There is no single environment that Python ties to itself tightly. The basic debugger, PDB, is built in as a Python module, so you can use Python to debug itself. Most of the IDE's that provide debuggers are merely placing a nice wrapper over the python debugger. To develop very short programs, I often start Python on my command line and fiddle away. > Also what are your suggestions for beginners of Pyhton programming? Don't worry about making GUI programs at first. GUIs are present in every operating system, but they are an additional level of complexity. Get the language down, first, then head into the world of graphical user interfaces. Start programming. See "Dive Into Python"[1]. Check out the Beginner's section of the Python Wiki[2]. The hardest part about learning to programming is learning to structure your thoughts into a coherent series of logical units. The rest is just code, and code is easy. It's the damn thinking that's so hard. Get familiar with the Python documentation. If you are under Windows, the Python docs are installed with Python in Microsoft's Compiled Help format, so you can browse them via the contents, look things up in the index, and search via the search tab. Remember that the built-in stuff, like lists and dictionaries, are documented in the Python Library Reference [3], while most of the modules are documented in the Global Modules [4] document. It's huge, but if you want to know what Python has, it's almost always in there. If you have a question, look for the solution by Googling this newsgroup or the web in general. If you still can't find a solution, ask around in here. Give plenty of detail, such the exact error messages if one occurred, and the minimum amount of working code that causes or demonstrates the problem. You may get twenty different answers sometimes (like for your question here), but that's twenty answers or perspectives that you may not have known before you asked. --Jason [1] http://www.diveintopython.org/ [2] http://wiki.python.org/moin/BeginnersGuide [3] http://docs.python.org/lib/lib.html [4] http://docs.python.org/modindex.html From the.mindstorm.mailinglist at gmail.com Sun Jul 15 12:07:36 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Sun, 15 Jul 2007 09:07:36 -0700 Subject: Getting values out of a CSV In-Reply-To: References: <1184295593.638409.22910@22g2000hsm.googlegroups.com> <1184476688.405321.122740@m3g2000hsh.googlegroups.com> Message-ID: <1184515656.978094.264440@q75g2000hsh.googlegroups.com> On Jul 15, 3:00 pm, Steve Holden wrote: > Alex Popescu wrote: > > On Jul 14, 5:55 am, "Gabriel Genellina" > > wrote: > >> So, as always, one should measure in each specific case if optimization is > >> worth the pain [...]. > > > I hope I am somehow misreading the above sentence :-). IMO synonim > > language contructs > > should result in the same performance or at least have clear/ > > documented performance. > > That's a fine opinion, how would you enforce it? Should we go throught > he interpreter slowing down the faster to each pair of alternative > constructs? ;-) It's inevitable there'll be differences in execution > time between equivalent constructs, and in that case you have to test to > find the better in your specific situation. > > The real issue here is that in 95% or more of the source of most > programs speed/performance isn't that much of an issue anyway. > > > I don't think we really want to see in code something like: > > > if threshold: > > do_it_with_list_function > > else: > > do_it_with_list_comprehension > > This would most certainly be a premature optimization which, as has been > repeated many times on this list, is the root of much evil in > programming. As Gabriel mentioned, you only need to do it if it's "worth > the pain", which in most case it won't be. It isn't worth spending even > five minutes to shave a minute off the performance of a ten-minute > program that is only run once a week, for example. > > Ultimately we have to be pragmatic: circumstances alter cases, and it's > usually not worth spending the time to improve execution speed except > for the most critical parts (the innermost nested loops) of production > programs. > > 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 fully agree with you (I am a newbie only to Python and not to programming ;-)). My point was that this thread may be misleading to newbies, because it is discussing corner cases performance of the 2 equivalent language constructs, while it should most probably be about the fact that the 2 solutions are equivalent and the only difference is probably readability (or maybe something like: list function is prefered when there are no additional constraints on the list comprehension construct). bests, ./alex -- .w( the_mindstorm )p. From jjl at pobox.com Sat Jul 28 07:12:47 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 28 Jul 2007 11:12:47 GMT Subject: slow emails References: Message-ID: <87ps2ceq8g.fsf@pobox.com> Gabriel Dragffy writes: > Whenever I post to this list my email invariably takes ages to show > up - perhaps two days or so. Often times not at all. Why is this? > > I am subscribed to Ubuntu mail list which is also high traffic, and > my posts show up there within minutes. No idea, but you could try posting through Google Groups or gmane.org instead. The latter is a newsfeed, so you need a newsreader program to post using that (to find the gmane newsgroup for python-list, click on "Lists" on the gmane.org front page, and type python-list in the search box). John From attn.steven.kuo at gmail.com Wed Jul 11 23:20:56 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 12 Jul 2007 03:20:56 -0000 Subject: Where does str class represent its data? In-Reply-To: <1184196082.903895.176020@n60g2000hse.googlegroups.com> References: <1184196082.903895.176020@n60g2000hse.googlegroups.com> Message-ID: <1184210456.968677.110110@n60g2000hse.googlegroups.com> On Jul 11, 4:21 pm, ChrisEdge... at gmail.com wrote: > I'd like to implement a subclass of string that works like this: > > >>>m = MyString('mail') > >>>m == 'fail' > True > >>>m == 'mail' > False > >>>m in ['fail', hail'] > > True > > My best attempt for something like this is: > > class MyString(str): > def __init__(self, seq): > if self == self.clean(seq): pass > else: self = MyString(self.clean(seq)) > > def clean(self, seq): > seq = seq.replace("m", "f") > > but this doesn't work. Nothing gets changed. > What about subclassing str and redefining __eq__: >>> class MyString(str): ... def __eq__(self, other): ... return not str.__eq__(self, other) ... >>> m = MyString('mail') >>> m == 'fail' True >>> m == 'mail' False >>> m in ['fail', 'hail'] True -- Hope this helps, Steven From gnewsg at gmail.com Wed Jul 11 13:48:07 2007 From: gnewsg at gmail.com (billiejoex) Date: Wed, 11 Jul 2007 10:48:07 -0700 Subject: asyncore and OOB data In-Reply-To: <1184172867.420979.215300@q75g2000hsh.googlegroups.com> References: <1184172867.420979.215300@q75g2000hsh.googlegroups.com> Message-ID: <1184176087.223106.52830@r34g2000hsd.googlegroups.com> If it could be useful I attach the complete server application I used for doing tests: < code > import asyncore, asynchat, socket, os class Handler(asynchat.async_chat): def __init__(self, sock_obj): asynchat.async_chat.__init__(self, conn=sock_obj) self.remote_ip, self.remote_port = self.socket.getpeername() self.in_buffer = "" self.out_buffer = "" self.set_terminator("\r\n") def handle_expt(self): print "OOB data arrived" data = self.socket.recv(1024, socket.MSG_OOB) print tuple(data) def collect_incoming_data(self, data): self.in_buffer += data def found_terminator(self): print self.in_buffer self.in_buffer = '' def handle_error(self): raise class Server(asyncore.dispatcher): def __init__(self): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) if os.name == 'posix': self.set_reuse_addr() self.bind(('', 21)) self.listen(5) def handle_accept(self): sock_obj, addr = self.accept() Handler(sock_obj) def handle_error(self): raise Server() asyncore.loop(timeout=1) From cai.haibin at gmail.com Mon Jul 23 10:18:29 2007 From: cai.haibin at gmail.com (james_027) Date: Mon, 23 Jul 2007 14:18:29 -0000 Subject: decorators tutorials In-Reply-To: <877iorkz80.fsf@benfinney.id.au> References: <1185178383.499234.299850@z24g2000prh.googlegroups.com> <1185180112.321457.73170@n2g2000hse.googlegroups.com> <1185183257.471106.318070@x35g2000prf.googlegroups.com> <877iorkz80.fsf@benfinney.id.au> Message-ID: <1185200309.234308.152290@z24g2000prh.googlegroups.com> Hi, > > def check_login(func): > > def _check_login(*args): > > print "I am decorator" > > return func(*args) > > return _check_login > > > @check_login > > def method2(input): > > print "I am method TWO. Input %s" % input > > That looks okay. What is unclear? > It just look complicated than using a simple function like this def check_login(msg): #... def my_func(toto, tata): #... #call it like this check_login('msg') my_func('toto', 'tata') I hope I could be able to understand clearly the decorators and use it to it efficiently Thanks james From montyphyton at gmail.com Fri Jul 20 19:34:34 2007 From: montyphyton at gmail.com (montyphyton at gmail.com) Date: Fri, 20 Jul 2007 16:34:34 -0700 Subject: Sorting dict keys In-Reply-To: References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> Message-ID: <1184974474.000773.15370@k79g2000hse.googlegroups.com> On 21 srp, 00:47, Duncan Smith wrote: > montyphy... at gmail.com wrote: > > Consider the following: > > >>>>a = {1:2, 3:4, 2:5} > > > Say that i want to get the keys of a, sorted. First thing I tried: > > >>>>b = a.keys().sort() > >>>>print b > > > None > > > Doesn't work. Probably because I am actually trying to sort the keys > > of the dictionary without copying them first. If that is the case, > > fine. Next thing I do: > > >>>>b = a.keys() > >>>>b.sort() > > > [1, 2, 3] > > > Works fine, but I would really like it if I could somehow do it in one > > line. As the problem seems to be copying the object, i try the > > following: > > >>>>import copy > >>>>b = copy.copy(a.keys()).sort() > >>>>print b > > > None > > > Hmmm, why doesn't it work? Also, > > >>>>b = copy.deepcopy(a.keys()).sort() > >>>>print b > > > None > > > (not that I thought that deepcopy will work since shallow didn't, I > > understand the difference :) ) > > Obviously, I am missing something here. What am I thinking wrong? Why > > doesn't copying the object work? > > Thanks for all the help > > sort() sorts a list in place and returns None. For a one-liner: > > >>> a = {1:2, 3:4, 2:5} > >>> b = sorted(a.keys()) > >>> b > > [1, 2, 3] > > Duncan Thanks, this is what I was looking for. I know that .sort() sorts the list in-place (the snippet I posted was written in a hurry, not pasted -- I apologise for that). In fact, this is exactly what puzzles me. copy.copy returns a new object: >>> copy.copy(a.keys()) [1,2,3] Then why doesn't copy.copy(a.keys()).sort() work?? Thanks to everyone who replied! From kar1107 at gmail.com Mon Jul 16 20:10:07 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Mon, 16 Jul 2007 17:10:07 -0700 Subject: In a dynamic language, why % operator asks user for type info? Message-ID: <1184631007.920803.147790@j4g2000prf.googlegroups.com> Hi, The string format operator, %, provides a functionality similar to the snprintf function in C. In C, the function does not know the type of each of the argument and hence relies on the embedded % specifier to guide itself while retrieving args. In python, the language already provides ways to know the type of an object. So in output = '%d foo %d bar" % (foo_count, bar_count), why we need to use %d? I'm thinking some general common placeholder, say %x (currently it's hex..) could be used. output = '%x foo %x bar" % (foo_count, bar_count). Since % by definition is string formatting, the operator should be able to infer how to convert each of the argument into strings. If the above is the case, we could've avoided all those exceptions that happen when a %d is specified but say a string is passed. Thanks, Karthik From luke.hoersten at gmail.com Mon Jul 2 17:37:47 2007 From: luke.hoersten at gmail.com (luke.hoersten at gmail.com) Date: Mon, 02 Jul 2007 21:37:47 -0000 Subject: Correct abstraction for TK Message-ID: <1183412267.513714.183800@q75g2000hsh.googlegroups.com> I'm looking for a good example of how to correctly abstract TK code from the rest of my program. I want to just get some user info and then get 4 values from the GUI. Right now I've written it OOP per the examples on python.org but it doesn't seem to be meshing very well with the rest of my project. Can anyone suggest some examples so that I can get more ideas? Thanks, Luke From hide1713 at gmail.com Thu Jul 5 21:43:41 2007 From: hide1713 at gmail.com (hide1713 at gmail.com) Date: Fri, 06 Jul 2007 01:43:41 -0000 Subject: Question about Making a Diskless Python Enviroment Message-ID: <1183686221.742642.131490@j4g2000prf.googlegroups.com> Hi everyone We are making a disk less workstation environment which support python.We use PXE DHCP TFTP to boot up disk less system.There are three choices as i know to set up a python environment for diskless system. First Solution, Use a initrd image with everything inside as the root file system.Diskless computer boots up with a kernel and this rootfs image.If everything goes fine.We could use python in the ram disk.In my situation,Target computers have 2G memory and 100M network,so the we don't need to worry about the size of initrd image.MY QUESTIONS are what files and libraries do i need to put into initrd image.Is there any How-to file to help me install python into a initrd image or any available initrd image with python installed . Second Solution.Use a small initrd to boot up the system and use NFS to mount those directories on Diskless server.I guess we could use / etc/fstab file to make it.Though we boot up the system form network ,we need to mount its local hard disk to directory tree.MY QUESTION ARE How to mount local devices in a diskless system?Is that done by kernel automatically or i have to configure it in fstab? Third Solution.Use NFS ROOT file system to boot up .In this solution.We don't need initrd any more.What we are going to do is recompile the kernel and build those important modules inside.It is weird that my kernel couldn't get ip form dhcp server(it can use a static ip form kernel command line).I notice that pxe could get ip form dhcp so it must be something wrong with the Kernel.We stop here. The three solution above are all i could think about. Any idea about my questions is welcomed Thanks Best Regard From bgporter at acm.org Tue Jul 31 14:17:14 2007 From: bgporter at acm.org (Brett g Porter) Date: Tue, 31 Jul 2007 14:17:14 -0400 Subject: Iteration over strings In-Reply-To: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> Message-ID: <46AF7CAA.7040703@acm.org> Robert Dailey wrote: > Hi, > > 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. > The thing that you need to remember is that strings in Python never change (and nothing ever changes that). Any time that you start out thinking "I need to change this string' you need to immediately translate that thought into "I need to create a new string with some changes made to this string". String objects can already do what you're trying to do here: >>> str = "C:\\somepath\\folder\\file.txt" >>> str 'C:\\somepath\\folder\\file.txt' >>> str2 = str.replace('\\', '/') >>> str2 'C:/somepath/folder/file.txt' >>> str 'C:\\somepath\\folder\\file.txt' replace() returns a new string with all instances of the 1st subsstring replaced with the second substring -- note that the original string 'str' is unmodified. Also note that if this is your actual use case, the standard lib also contains a function os.path.normpath() that does all the correct manipulations to correctly normalize file paths on the current platform. From roy at panix.com Wed Jul 4 22:12:46 2007 From: roy at panix.com (Roy Smith) Date: Wed, 04 Jul 2007 22:12:46 -0400 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: ames Harris wrote: > I have a requirement to store timestamps in a database. Simple enough > you might think but finding a suitably general format is not easy. The > specifics are > > 1) subsecond resolution - milliseconds or, preferably, more detailed > 2) not bounded by Unix timestamp 2038 limit > 3) readable in Java > 4) writable portably in Perl which seems to mean that 64-bit values > are out > 5) readable and writable in Python > 6) storable in a free database - Postgresql/MySQL Astronomers use Julian Date (http://en.wikipedia.org/wiki/Julian_date) for calculations like this. It's a widely used format and highly portable. I'm sure there are libraries to deal with it in all the languages you mention (and more). Ask on sci.astro for more information. From samfeltus at gmail.com Sat Jul 14 02:03:13 2007 From: samfeltus at gmail.com (SamFeltus) Date: Fri, 13 Jul 2007 23:03:13 -0700 Subject: TurboGears on Summer Madness Message-ID: <1184392993.088226.239150@q75g2000hsh.googlegroups.com> Here is a new style of SonomaSunshine page, edited and created with TurboGears. It's a bloated file, but it's comical. Note - Links with words stay on page,links without words are random links to other sites. Visiting Monkey City first is recommended. As always, LIVE FROM LA!!! http://samfeltus.com/as3/summer_madness_on_tg.html Sam the Gardener http://samfeltus.com/site_index.htm From matt at vazor.com Tue Jul 3 20:16:55 2007 From: matt at vazor.com (Matt) Date: Tue, 03 Jul 2007 17:16:55 -0700 Subject: converting datetime object in UTC to local time Message-ID: <1183508215.142322.282550@i38g2000prf.googlegroups.com> Hi all, So a lot of digging on doing this and still not a fabulous solution: import time # this takes the last_modified_date naive datetime, converts it to a # UTC timetuple, converts that to a timestamp (seconds since the # epoch), subtracts the timezone offset (in seconds), and then converts # that back into a timetuple... Must be an easier way... mytime = time.localtime(time.mktime(last_modified_date.utctimetuple()) - time.timezone) lm_date_str = time.strftime("%m/%d/%Y %I:%M %p %Z", mytime) last_modified_date is a naive datetime.datetime object A previous version gave me something like: mytime = datetime.datetime.fromtimestamp(time.mktime(last_modified_date.utctimetuple()) - time.timezone) lm_date_str = mytime.strftime("%m/%d/%Y %I:%M %p %Z") But this gave me no timezone since the datetime object is still naive. And I'm going from a datetime to a timetuple to a timestamp back to a datetime... All this seems like a lot of monkeying around to do something that should be simple -- is there a simple way to do this without requiring some other module? thx Matt From bignose+hates-spam at benfinney.id.au Thu Jul 12 08:30:34 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 12 Jul 2007 22:30:34 +1000 Subject: 2**2**2**2**2 wrong? Bug? References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> <1184173446.779276.250530@k79g2000hse.googlegroups.com> <1184182757.797808.206480@d55g2000hsg.googlegroups.com> Message-ID: <87ps2xkdn9.fsf@benfinney.id.au> "Gabriel Genellina" writes: > "Which is the largest number that can be written with only 3 > digits?" Some people stop at 999, others try 99**9 and 9**99, and > the winner is 9**9**9 Since exponentiation is (I think?) the highest-order function we understand for writing *only* digits on the page, then yes, your answer is right, if no other mathematical notation is allowed. Since others seem to be reading "only 3 digits" as "3 digits plus other well-defined mathematical notation", here's the best answer given those criteria: -- \ "I stayed up all night playing poker with tarot cards. I got a | `\ full house and four people died." -- Steven Wright | _o__) | Ben Finney From dmacdonald95 at gmail.com Mon Jul 2 19:04:36 2007 From: dmacdonald95 at gmail.com (Dustin MacDonald) Date: Mon, 02 Jul 2007 16:04:36 -0700 Subject: Probably simple syntax error In-Reply-To: References: <1183351228.878746.233430@o61g2000hsh.googlegroups.com> <1183352843.803263.82140@57g2000hsv.googlegroups.com> Message-ID: <1183417476.394762.285190@w5g2000hsg.googlegroups.com> Ah. Thank you everyone. Sorry for not replying earlier, real life got in the way :) Gerry Herron, Tim Delaney, Mark Peters: Thank you. Switching from parentheses to square brackets fixed the code, and yes, Tim, you were right. It was a list I was working with. And thanks for those links Tim. John Machin: Thank you for all the pointers/code fixes there. They'll help alot. Ptn: I was unaware of that period added, Thanks, I'll have to watch out for it. :) And Cameron: Ah, yes. It does reduce the confusion. I do know that square brackets are used for *creating* a dictionary (blah = ["A", "B", "C"], so I figured the same would apply to accessing it (which is why for my list, which I created with parenthesis I assumed I accessed with parenthesis). Thank you =] ~Dustin From info at thegrantinstitute.com Mon Jul 30 07:43:45 2007 From: info at thegrantinstitute.com (Anthony Jones) Date: 30 Jul 2007 04:43:45 -0700 Subject: Professional Grant Proposal Writing Workshop (September 2007: Simon Fraser University) Message-ID: <20070730044345.F4094988126221DD@thegrantinstitute.com> An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Tue Jul 3 03:25:04 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Jul 2007 07:25:04 GMT Subject: Python compilation ?? References: <20070702202448.4947.2088004513.divmod.quotient.6059@ohm> Message-ID: Steve Holden wrote: > Absolutely. I should, of course, have said that only imported modules > have the results of the compilation stored as a .pyc file. > > One must presume this is to save the file write time during development > when the program is almost always different fro the last time you ran it. Or possibly to save disc space if you have a lot of scripts. I think it is a reasonable compromise: if you are running a script it seems unlikely that you will notice the additional time to compile one script on top of the time to load the interpreter, but if your script imports a few hundred other modules the time to compile them is definitely noticeable. From newsgroups at nospam.demon.co.uk Tue Jul 3 10:10:10 2007 From: newsgroups at nospam.demon.co.uk (Douglas Woodrow) Date: Tue, 3 Jul 2007 15:10:10 +0100 Subject: Programming Idiomatic Code References: <468a0768$0$14120$426a74cc@news.free.fr> Message-ID: On Tue, 3 Jul 2007 10:19:07, Nathan Harmston wrote > >i m in the UK and dont have the experience but hey 10 minutes of >programming python beats 12 hours of programming in Clipper-derived >unreadable drivel (you dont know how much I appreciate Python atm). "Clipper-derived unreadable drivel" I'm intrigued, what language are you working in? Clipper v5 was a pretty impressive development language for 1990 - with code blocks, a flexible pre-processor, garbage collection, exception handling, decent speed and an API to allow easy integration with routines written in c. It doesn't have to be unreadable at all (unless it's written by someone who thinks it is dBase). -- Doug Woodrow From steve at holdenweb.com Tue Jul 31 23:05:56 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 31 Jul 2007 23:05:56 -0400 Subject: Reload after an exception, not possible ? In-Reply-To: References: Message-ID: Steve Holden wrote: [...] > The solution? Don't assign to JAL_simulation_file, and the function will > use the local instead. > Sorry, that last "local" should have been "global". 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 Jul 16 18:18:01 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 16 Jul 2007 15:18:01 -0700 Subject: zipfile 2GB problems? In-Reply-To: <1184612398.359979.28900@d55g2000hsg.googlegroups.com> References: <1184474112.081258.111490@n60g2000hse.googlegroups.com> <1184525970.082235.238200@q75g2000hsh.googlegroups.com> <1184528949.751377.5620@g4g2000hsf.googlegroups.com> <1184612398.359979.28900@d55g2000hsg.googlegroups.com> Message-ID: <1184624281.169803.9300@j4g2000prf.googlegroups.com> On Jul 17, 4:59 am, xamdam wrote: > On Jul 15, 5:39 pm, Steve Holden wrote: > > > > > xamdam wrote: > > >>> Additional info: my file is from a data provider, do not know what > > >>> they used to compress it. Previous files worked ok, this one is the > > >>> 1st over 2GB. Winzip has no problem with it. > > >> It could be you are using a Python with an in-built limit of 2GB on file > > >> size. What happens if you open the file, seek past the 2GB point and > > >> then try and read data? > > > > Steve, > > > I used is_zipfile function, which from does exactly that from a quick > > > read - goes to the end, reads expected string. It worked fine. Tried > > > regular Windows 2.4.4 and 2.5.1, same result. > > > Fine, if it isn't file size limitations I suspect you need to post some > > code and a traceback so we can get better insight into exactly what the > > problem is. > > It's failing in the ZipFile constructor, which ends up throwing > > zipfile(2.4.3).py:291> raise BadZipfile, "Bad magic number for file > header" Suggestion 1: RTEDManual Manual says: """ 12.4.1 ZipFile Objects class ZipFile( file[, mode[, compression[, allowZip64]]]) [snip] If allowZip64 is True zipfile will create ZIP files that use the ZIP64 extensions when the zipfile is larger than 2 GB. If it is false (the default) zipfile will raise an exception when the ZIP file would require ZIP64 extensions. ZIP64 extensions are disabled by default because the default zip and unzip commands on Unix (the InfoZIP utilities) don't support these extensions. """ It's vague about whether allowZip64=True is needed for reading -- have you tried it? Suggestion 2: RTEDCode. At the line you quoted, it is checking the first 4 bytes of the file for a signature: 'PK\x03\x04' Do this: print repr(open('yourfile.zip', 'rb').read(4)) Tell us what you find. Suggestion 3: RTEDWordsOfWisdomOfSteveHolden. IOW supply the *WHOLE* EDing traceback. HTH, John From mccredie at gmail.com Sat Jul 7 13:28:32 2007 From: mccredie at gmail.com (Matimus) Date: Sat, 07 Jul 2007 17:28:32 -0000 Subject: Restarting a Python Application In-Reply-To: <1183746867.097492.134570@m36g2000hse.googlegroups.com> References: <1183498045.092504.229250@m36g2000hse.googlegroups.com> <1183500027.659730.211790@d30g2000prg.googlegroups.com> <1183746867.097492.134570@m36g2000hse.googlegroups.com> Message-ID: <1183829312.478457.93060@g37g2000prf.googlegroups.com> > Actually I am using wxPython for a GUI front-end. Thus, it is already > in a class. I am not sure how to apply your idea to a program that is > already running in an infinite event loop. I don't know wxPython, but I was able to grab an example program and adapt it to do what I think you are asking for. Something like this: [code] #! /usr/bin/env python from wxPython import wx ID_EXIT = 101 ID_RST = 102 class MyFrame(wx.wxFrame): def __init__(self, parent, ID, title): wx.wxFrame.__init__(self, parent, ID, title, wx.wxDefaultPosition, wx.wxSize(200, 150)) self.CreateStatusBar() self.SetStatusText("This is the statusbar") menu = wx.wxMenu() menu.Append(ID_EXIT, "E&xit", "Terminate the program") menu.Append(ID_RST, "&Restart", "Restart the program") menuBar = wx.wxMenuBar() menuBar.Append(menu, "&File"); self.SetMenuBar(menuBar) wx.EVT_MENU(self, ID_EXIT, self.TimeToQuit) wx.EVT_MENU(self, ID_RST, self.TimeToRestart) def TimeToQuit(self, e): self.Close(wx.true) def TimeToRestart(self, e): global restart restart = True self.TimeToQuit(e) class MyApp(wx.wxApp): def OnInit(self): global restart restart = False frame = MyFrame(wx.NULL, -1, "Hello from wxPython") frame.Show(wx.true) self.SetTopWindow(frame) return wx.true if __name__ == "__main__": MyApp(0).MainLoop() while restart: MyApp(0).MainLoop() [/code] From hide1713 at gmail.com Mon Jul 16 11:29:58 2007 From: hide1713 at gmail.com (hide1713 at gmail.com) Date: Mon, 16 Jul 2007 15:29:58 -0000 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: <1184599798.147096.32240@e9g2000prf.googlegroups.com> You are lucky.Our project is a cross-platform cluster computer managment system this system can run on both windows and Linux http://pluster.gf.cs.hit.edu.cn/ I tell you how we solve this problems > > 1. How to most easily learn to write simple PC GUI programs that will > send data to remote embedded devices via serial comms, and perhaps > incorporate some basic (x,y) type graphics display and manipulation > (simple drawing program). Data may result from user GUI input, or from > parsing a text config file. Solution need not be efficient in machine > resource utilization. Emphasis is on quickness with which programmer > can learn and implement solution. We use tk for GUI and we have a interpreter reads VB form file ".frm" in and display it with tk.You just need to draw forms in VB and save it in frm formate load it in your python file LoadForm("aa.frm") after that you can use button,menu and so on in python We use XMLRPC to conmunicate with remote node.XMLRPC is very cool for you can invoke a function in remote side in the same way you invoke a local method. for example we have an remote object foo foo.bar() #invoke bar() in remote side but XMLRPC is work on network.I'm not sure it can work in serial > 2. Must be cross-platform: Linux + Windows. This factor can have a big > impact on whether it is necessary to learn a new language, or stick with > C. If my platform was only Linux I could just learn GTK and be done > with it. I wouldn't be here in that case. and most important is XMLRPC is cross-platform.you can use a linux for server and windows for client From twisted0n3 at gmail.com Sun Jul 8 15:46:37 2007 From: twisted0n3 at gmail.com (Twisted) Date: Sun, 08 Jul 2007 19:46:37 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1183883315.265068.61600@n60g2000hse.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1183841277.333384.188950@g4g2000hsf.googlegroups.com> <1183856442.027967.272530@g4g2000hsf.googlegroups.com> <1183883315.265068.61600@n60g2000hse.googlegroups.com> Message-ID: <1183923997.160960.3080@q75g2000hsh.googlegroups.com> On Jul 8, 4:28 am, Adriano Varoli Piazza wrote: > b) If you do want to keep an antediluvian copy of emacs -probably > versioned in the negative numbers, for all you've said- please do. Do > be so kind as to send a copy, since it might be quite valuable as an > antique. Judging by the existence of the newsgroup comp.emacs, emacs is indeed considered by some to be a quite valuable antique. Otherwise why on earth would it have an apparently fairly active newsgroup a full seven years into the 21st century? From sjmachin at lexicon.net Sun Jul 22 02:04:56 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 21 Jul 2007 23:04:56 -0700 Subject: Sort lines in a text file In-Reply-To: <1185073397.821811.143260@k79g2000hse.googlegroups.com> References: <1185073397.821811.143260@k79g2000hse.googlegroups.com> Message-ID: <1185084296.913235.97490@x35g2000prf.googlegroups.com> On Jul 22, 1:03 pm, leegold wrote: > say I have a text file: > > zz3 uaa4a ss 7 uu > zz 3 zzzz66 ppazz9 > aaaaaaaaa00000zz0 > > I want to sort the text file. I want the key to be the number after > the two "zz". Or I guess a string of two zz then a number....So > that's 3, 9, 0 > > I'm trying to say that I want to sort lines in a file based on a > regular expression. How could I do that in Python? I'm limited to > Python 2.1, I can't add any 2nd party newer tools. To save anybody who's tempted to write the whole shebang for you, please specify which part(s) of the exercise you are having problems with: (a) reading lines from a file (b) extracting a sort key from a line [presuming "number" means "positive integer"; what do you want to do if multiple lines have the same number? what if no number at all"] (c) creating a list of tuples, where each tuple is (key, line_contents) (d) sorting the list (e) creating the output file from the sorted list. From harelmalka at gmail.com Tue Jul 24 04:10:31 2007 From: harelmalka at gmail.com (Harel) Date: Tue, 24 Jul 2007 08:10:31 -0000 Subject: Trouble with email package In-Reply-To: <87myxwfoap.fsf@wilson.homeunix.com> References: <87r6n8foqd.fsf@wilson.homeunix.com> <87myxwfoap.fsf@wilson.homeunix.com> Message-ID: <1185264631.132295.119800@w3g2000hsg.googlegroups.com> Hi there, What was the solution you found? Could you please post it? I'm having the same problem... ;o( Thanks! Harel On Jul 16, 2:53 pm, Torsten Bronger wrote: > Hall?chen! > > Ingrid Bronger writes: > > [...] > > > The Content-Transfer-Encoding is wrong. Okay (well, not okay but) > > then I added message["Content-Transfer-Encoding"] = "8bit" to my > > code and got > > > Content-Type: text/plain; charset="utf-8" > > MIME-Version: 1.0 > > Content-Transfer-Encoding: base64 > > Content-Transfer-Encoding: 8bit > > > Hall?chen! > > I found the cause of this part of my trouble. > > Tsch?, > Torsten. > > -- > Torsten Bronger, aquisgrana, europa vetus > Jabber ID: bron... at jabber.org > (Seehttp://ime.webhop.orgfor ICQ, MSN, etc.) From gagsl-py2 at yahoo.com.ar Sun Jul 15 00:00:04 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 15 Jul 2007 01:00:04 -0300 Subject: Circular import problem References: <1184294176.550267.119980@n60g2000hse.googlegroups.com> <1184343897.111992.107880@g4g2000hsf.googlegroups.com> <1184435045.834596.97600@o61g2000hsh.googlegroups.com> Message-ID: En Sat, 14 Jul 2007 14:44:05 -0300, bvdp escribi?: >> > But, I still don't understand how python can access a function in a >> > file I have NOT included. In this case, to get things to work, I DO >> > NOT "import MMA.grooves" but later in the module I access a function >> > with "xx=MMA.grooves.somefunc()" and it finds the function, and works >> > just fine. It shouldn't work. > I've just used an empty __init__.py file. I will have to read up a bit > more on packages and see what advantage there is to import in that. __init__.py is executed inside the package's namespace - whatever you import/define there, is available later as packagename.zzz > Which is considered good style? Loading at the top or loading when > needed? I mean, importing at the top of the module is the recommended practice. See http://www.python.org/dev/peps/pep-0008/ I try only to import locally: a) when it is slow and not always needed, and b) when the imported module is unrelated to the main purpose (e.g. import traceback inside some exception handlers). -- Gabriel Genellina From bignose+hates-spam at benfinney.id.au Sat Jul 28 21:36:25 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 29 Jul 2007 11:36:25 +1000 Subject: this must be a stupid question ... References: <849ad$46abb218$d443bb3a$21452@news.speedlinq.nl> Message-ID: <87sl78dm92.fsf@benfinney.id.au> Stef Mientki writes: > but I can;t find the answer ;-) It's not a stupid question, but it is a stupid Subject field. That's easy to fix though: in future, please write a Subject field that actually tells us what the message is about. > If I try to use [the $ symbol] in names, I get a compiler error, Yes, because names have a specific set of characters that must be used: A-Z, a-z, 0-9, and the underscore. > so it probably has some special meaning. That doesn't follow; it just means that character isn't allowed for names. This does have the advantage that, if necessary, it can be used in future (the '@' symbol was recently added to the language, though it didn't have a meaning before). -- \ "The future always arrives too fast, and in the wrong order." | `\ -- Alvin Toffler | _o__) | Ben Finney From fdemmer at gmail.com Wed Jul 4 10:18:48 2007 From: fdemmer at gmail.com (Florian Demmer) Date: Wed, 04 Jul 2007 07:18:48 -0700 Subject: Python 2.5 from source without tcl/tk In-Reply-To: <1183456170.547500.118910@n60g2000hse.googlegroups.com> References: <1183456170.547500.118910@n60g2000hse.googlegroups.com> Message-ID: <1183558728.329672.268650@c77g2000hse.googlegroups.com> ok... cannot get rid of the "INFO: Can't locate Tcl/Tk libs and/or headers". Now same thing but weirder with curses: i do not have ncurses-devel installed. still make trys to compile the curses module. how do i prevent that? imo the configure should have more with/without switches... or do i just miss the point, where to tell it which modules to compile and which not? From pcooke at philc.net Fri Jul 13 10:18:24 2007 From: pcooke at philc.net (PhilC) Date: Fri, 13 Jul 2007 10:18:24 -0400 Subject: Writing a Python manual for Poser 7. Advice required re copyright/license Message-ID: Hi Folks, I'm attempting to write a comprehensive manual explaining how to write Python scripts for the Poser 7 application. All the example scripts, explanatory paragraphs and screen shots will naturally be all my own work. My difficulty is in knowing how I may present the large amount of tabulated data that lists out all the Tkinter functions and their options. I'm familiar with Fredrik Lundh's "An Introduction to Tkinter" at http://effbot.org/tkinterbook/ but would not wish to blindly copy the tables. However there are only so many ways to type:- "background= The background color. The default is system specific." The manual may be published in book form so may not be free. Does anyone have contact information for Mr Lundh in order that I might perhaps send him a draft copy for his comment? Many thanks, PhilC http://www.philc.net From aaron.watters at gmail.com Wed Jul 25 08:16:45 2007 From: aaron.watters at gmail.com (aaron.watters at gmail.com) Date: Wed, 25 Jul 2007 05:16:45 -0700 Subject: renaming an open file in nt like unix? In-Reply-To: References: <1184346880.093826.176350@n2g2000hse.googlegroups.com> Message-ID: <1185365805.724237.11150@19g2000hsx.googlegroups.com> On Jul 13, 2:44 pm, Steve Holden wrote: > Thomas Heller wrote: > > aaron.watt... at gmail.com schrieb:= > > >> ...Do the NT file systems support [renaming an open file] (which I think is > >> standard for POSIX systems)? > > > Yes, you can do that. We implemented something like this to replace > > dlls there are currently in use... > > You do have to be careful though, because sometimes Windows refuses to > let you rename a file because it's in use. At least on my laptop I see Steve's behaviour. fwiw: C:\Documents and Settings\aaron\Desktop>opentest.py rename rename sleeps 1 renamer sleeping 5 now renaming Traceback (most recent call last): File "C:\Documents and Settings\aaron\Desktop\opentest.py", line 69, in renameProcess() File "C:\Documents and Settings\aaron\Desktop\opentest.py", line 31, in rename Process os.rename(firstname, secondname) WindowsError: [Error 13] The process cannot access the file because it is being used by another process So it looks like the answer in general is "no: you can't do that on Windows." Drat! Foiled again. -- Aaron Watters === Is a bear catholic? Does the Pope ...? From robert.kern at gmail.com Tue Jul 3 19:28:40 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 03 Jul 2007 18:28:40 -0500 Subject: Ask for a password with OptParse In-Reply-To: <468AD2B4.6030005@fibertel.com.ar> References: <468AD2B4.6030005@fibertel.com.ar> Message-ID: Mariano Mara wrote: > Hi everyone. > I'm building a script with optparse. One of the parameters will be a > password. > How can I code the optparse to accept/handle/format the password so that > the user does not have to write it in plain/visible text in the terminal? You wouldn't ask for the password with optparse. optparse just parses command-line options. If you must provide a command-line argument to accept a password, then check if the option value is None (i.e. the user did not provide it), then prompt the user using getpass.getpass(). That function will not print the user's input to the screen. -- 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 Fri Jul 13 06:17:22 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 13 Jul 2007 03:17:22 -0700 Subject: Fastest way to convert a byte of integer into a list In-Reply-To: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> Message-ID: <1184321842.921823.317470@k79g2000hse.googlegroups.com> On Jul 12, 5:34 pm, Godzilla wrote: > Hello, > > I'm trying to find a way to convert an integer (8-bits long for > starters) and converting them to a list, e.g.: > > num = 255 > numList = [1,1,1,1,1,1,1,1] > > with the first element of the list being the least significant, so > that i can keep appending to that list without having to worry about > the size of the integer. I need to do this because some of the > function call can return a 2 lots of 32-bit numbers. I have to find a > way to transport this in a list... or is there a better way? Standing on the shoulders of previous posters, I put this together. -- Paul # init list of tuples by byte bytebits = lambda num : [num >> i & 1 for i in range(8)] bytes = [ tuple(bytebits(i)) for i in range(256) ] # use bytes lookup to get bits in a 32-bit integer bits = lambda num : sum((bytes[num >> i & 255] for i in range(0,32,8)), ()) # use base-2 log to find how many bits in an integer of arbitrary length from math import log,ceil log_of_2 = log(2) numBits = lambda num : int(ceil(log(num)/log_of_2)) # expand bits to integers of arbitrary length arbBits = lambda num : sum((bytes[num >> i & 255] for i in range(0,numBits(num),8)),()) print arbBits((1<<34)-1) print arbBits(37) # prints #(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0) #(1, 0, 1, 0, 0, 1, 0, 0) From bblais at bryant.edu Mon Jul 2 09:02:27 2007 From: bblais at bryant.edu (Brian Blais) Date: Mon, 2 Jul 2007 09:02:27 -0400 Subject: good matlab interface In-Reply-To: References: Message-ID: <09ADD5BE-19EF-47E5-BD9A-BFEF16973ED2@bryant.edu> On Jun 30, 2007, at 2:31 AM, felix seltzer wrote: > Does any one know of a good matlab interface? > I would just use scipy or numpy, but i also need to use > the matlab neural network functions. I have tried PyMat, but am > having > a hard time getting it to install correctly. > What problems are you having installing? I had one problem with the terrible matlab license server, which I had to solve by making site- packages world writable, installing pymat as a user, and then removing the world writable flag. Root just didn't have access to matlab on my machine. :P bb From gilbert.fine at gmail.com Mon Jul 30 06:36:33 2007 From: gilbert.fine at gmail.com (Gilbert Fine) Date: Mon, 30 Jul 2007 03:36:33 -0700 Subject: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why? Message-ID: <1185791793.141118.44080@x35g2000prf.googlegroups.com> This is a very strange exception raised from somewhere in our program. I have no idea how this happen. And don't know how to reproduce. It just occurs from time to time. Can anyone give me some suggestion to fix this? Thanks. -- Gilbert From gagsl-py2 at yahoo.com.ar Mon Jul 9 19:45:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Jul 2007 20:45:35 -0300 Subject: execute script in certain directory References: <1184000980.796505.93380@r34g2000hsd.googlegroups.com> Message-ID: En Mon, 09 Jul 2007 14:09:40 -0300, Alex Popescu escribi?: > Interesting. I was wondering about the opposit: being in the parent > dir, how can I run a module from a package. (the current behavior when > running python dir_name\module.py is to consider the dir_name the > current dir and this breaks all imports). I am pretty sure this is > answered somewhere, but I must confess that so far I haven't been able > to find it :-(. python dir_name\module.py does NOT change the current dir. It prepends dir_name to sys.path, if this is what you mean. The short answer is: don't place standalone scripts inside a package; see this thread: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c44c769a72ca69fa/ -- Gabriel Genellina From josiah.carlson at sbcglobal.net Tue Jul 10 02:13:53 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Tue, 10 Jul 2007 06:13:53 GMT Subject: highly einteractive editor for python In-Reply-To: References: Message-ID: Atul Bhingarde wrote: > Does anybody know an editor that facilitates, interactive python > development. Where GUI etc developed will be possible to see in real time > mode. Boa Constructor? wxGlade embedded in some other software (SPE?) XRCed? What do you mean by "real time mode"? - Josiah From ars at iki.fi Sun Jul 29 01:37:03 2007 From: ars at iki.fi (Antti Rasinen) Date: Sun, 29 Jul 2007 08:37:03 +0300 Subject: Events: The Python Way In-Reply-To: <98edab2e0707281634q532284e0t5e6f6a2d3dfa58b4@mail.gmail.com> References: <98edab2e0707281634q532284e0t5e6f6a2d3dfa58b4@mail.gmail.com> Message-ID: On 2007-07-29, at 02:34, David Wilson wrote: > Hi there, > > Python has no built-in way of doing this. You may consider writing > your own class if you like this pattern (I personally do): > > class Event(object): > def __init__(self): > self.subscribers = set() ... > def __isub__(self, subscriber): > self.subscribers.pop(subscriber) > return self A slight typo there. For sets s.pop() returns an arbitrary element and s.remove(x) or s.discard(x) removes the element x from the set s. For the OP: remove raises an exception if x is not in the set, discard does not. -- [ ars at iki.fi <*> Antti Rasinen ] "The music of rebellion makes you wanna rage But it's made by millionaires who are nearly twice your age" From http Thu Jul 12 14:26:22 2007 From: http (Paul Rubin) Date: 12 Jul 2007 11:26:22 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: <7x8x9lwka9.fsf@ruckus.brouhaha.com> Donn Cave writes: > Don't worry - there will be a state transformation monad for you! > > Nature or nurture? it would be interesting to see some identical twin > studies on novice programmers. Since few of us were exposed first > to strictly functional programming, though, you have to wonder. In > its day, goto was of course very well loved. Guy Steele used to describe functional programming -- the evaluation of lambda-calculus without side effects -- as "separation of Church and state", a highly desirable situation ;-). (For non-FP nerds, the above is a pun referring to Alonzo Church, who invented lambda calculus in the 1920's or so). From chrispwd at gmail.com Wed Jul 25 11:46:03 2007 From: chrispwd at gmail.com (chrispwd at gmail.com) Date: Wed, 25 Jul 2007 08:46:03 -0700 Subject: Reading files, splitting on a delimiter and newlines. Message-ID: <1185378363.166434.172190@r34g2000hsd.googlegroups.com> Hello, I have a situation where I have a file that contains text similar to: myValue1 = contents of value1 myValue2 = contents of value2 but with a new line here myValue3 = contents of value3 My first approach was to open the file, use readlines to split the lines on the "=" delimiter into a key/value pair (to be stored in a dict). After processing a couple files I noticed its possible that a newline can be present in the value as shown in myValue2. In this case its not an option to say remove the newlines if its a "multi line" value as the value data needs to stay intact. I'm a bit confused as how to go about getting this to work. Any suggestions on an approach would be greatly appreciated! From josiah.carlson at sbcglobal.net Wed Jul 25 10:59:09 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Wed, 25 Jul 2007 14:59:09 GMT Subject: How to tell when a socket is closed on the other end? In-Reply-To: References: <1185371863.622473.205010@19g2000hsx.googlegroups.com> Message-ID: <1zJpi.40797$Um6.16581@newssvr12.news.prodigy.net> Roy Smith wrote: > In article <1185371863.622473.205010 at 19g2000hsx.googlegroups.com>, > billiejoex wrote: > >> Hi there. >> I'm setting up test suite for a project of mine. >> >From test suite, acting as a client, I'd like to know, in certain >> situations, if the socket is closed on the other end or not. >> I noticed that I can "detect" such state if a call to socket.read() >> returns 0 but it seems a little poor to me. :-\ >> Is there a reliable way to test such socket 'state'? > > This isn't really a Python question, it's a Berkeley Socket API question. > You don't say, but I assume you're talking about a TCP (i.e. SOCKSTREAM) > connection? > > The answer is you can use the select() system call to detect "exceptional > conditions" on a socket. Python's select module provides this > functionality, but to understand how to use it, you need to study the > underlying API. > > On the other hand, socket.read() returning 0 works too. What do you find > "poor" about that? What do you want to know about the connection being > closed that you don't find out by getting 0 back from read()? Sockets don't have a read method unless you have used makefile() or have made them into ssl sockets. They don't return 0, they return empty strings. If they have a timeout, or the reads were somehow interrupted, they can return empty strings without the other end having closed the connection. There are 3 methods of determining if the remote machine has closed/shutdown a socket. You offer one, select.select([], [], [sock], timeout) . The others are to pass that same socket to check whether one can read or write to the socket. If a socket is readable by select, yet a recv() produces zero bytes, then the other end has at least signaled that it is no longer sending (they have performed shutdown(1) or close()). If a socket is writable by select, yet doesn't accept any bytes in send(), then the other end has at least signaled that it is no longer receiving (they have performed shutdown(0) or close()). In many cases, people only care if *both* directions are open, which is why asyncore closes the connection if a send or receive do not produce or consume bytes. - Josiah From tylerca at jeld-wen.com Tue Jul 31 19:09:27 2007 From: tylerca at jeld-wen.com (Azazello) Date: Tue, 31 Jul 2007 23:09:27 -0000 Subject: Process Control Help In-Reply-To: References: <1185808072.695752.20720@z28g2000prd.googlegroups.com> Message-ID: <1185923367.122846.117750@x40g2000prg.googlegroups.com> On Jul 31, 12:45 pm, Walt Leipold wrote: > Azazello wrote: > > > We're looking to run some industrial machinery from a PC. Starting > > with some basic servo controls and IO port reading for something like > > an XYZ table (just X would be a good start!). Now there is some > > existing software out there for PC control but this software is, to my > > understanding, largely unnecessary and "black box". This "black box" > > creates a problem when trying to e.g. control servos and IO with the > > same program. And if we want to include an HMI like a touchscreen, or > > export the machinery's production into a RSS feed, the web of software > > becomes messy and slow. > > > Soo.... > > I need to find some ethernet friendly IO, serial would be fine but but > > it's a leash in many instances. I know some protocols have been > > ported to ethernet, but I am having extreme difficulty figuring out > > what these protocols entail. ModBus/TCP is the one I'd like to > > choose. > > > I know that people have done this kind of software but it > > seems that industrial python remains a bit taboo because of > > proprietary issues... > > 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 > industry evolved, and the kinds of programmers and development teams > that write industrial control packages. > > > If we could consolidate this software into a single, non > > "black-box" package, we could see significant improvements > > in development time. > > 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? > > > Having to program 3 different devices with three > > different languages to control your PLC, Servos, and module X is > > the status quo we face, but it is quite frustrating and limited. > > I share your frustration with the status quo in industrial automation. > On the other hand, I've been brought in to customer sites a number of > time to fix their re-invented wheels, and my advice is not to re-invent > the wheel. > > 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. > > For reasons of quality, long-term supportability, manageability, > insurability, and several other -ilities, the sad facts are: > > * Unless you're a hobbyist, if you want to do machine/motion control, do > it from a PLC. Windows is not reliable, stable, or real-time enough to > be trusted to control moving pieces of hardware, and custom software, > possibly with hand-crafted multithreading, is not as reliable or > predicatable as ladder logic on a PLC. (Look up "Therac 25" for some > reasons why.) Python is a great language, but it depends on the > underlying OS for threading, and has a GIL that can bite you too. 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. > > * 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. > > (Wow, that was a depressing post to write.) > > -- Walt > > "Eddies in the space-time continuum!" > "And this is his sofa, is it?" 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? From zyzhu2000 at gmail.com Fri Jul 27 17:56:50 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 27 Jul 2007 21:56:50 -0000 Subject: Tkinter -- Show Data in an Excel like Read-Only Grid Message-ID: <1185573410.087935.146830@d30g2000prg.googlegroups.com> Hi All, I am really new to Tk and Tkinter. I googled the web but it was not mentioned how to build a data grid with Tkinter. Basically, I want to show an excel like data grid with fixed column and row headers and sortable columns. But the grids can be read-only. Can anyone give some hint on implementing this? Thanks, beginner From Dave.Baum at motorola.com Tue Jul 17 12:32:33 2007 From: Dave.Baum at motorola.com (Dave Baum) Date: Tue, 17 Jul 2007 11:32:33 -0500 Subject: Discover instance variables References: <1184606748.599294.293570@n60g2000hse.googlegroups.com> Message-ID: In article <1184606748.599294.293570 at n60g2000hse.googlegroups.com>, JonathanB wrote: > I can handle the formatting and changing the variable itself, no > problem, but how do I get a list of all the variables in a class > instance? I almost put a list in there called vars and appended all > the variables to it so I could iterate the list, but this sounds like > something useful enough that someone has come up with a better way to > do it than that. It almost looks like self.__dir__() is what I want, > but that returns methods as well, correct? I only want variables, but > I can't think of how to do a list comprehension that would remove the > methods. For simple cases, the object's __dict__ will probably give you what you want. By default, that's where an object's instance variables are stored, and you can just examine the keys, etc: class Foo(object): def __init__(self): self.a = "bar" self.z = "test" self.var = 2 foo = Foo() print foo.__dict__ -> {'a': 'bar', 'var': 2, 'z': 'test'} However, there are lots of ways to bypass using the __dict__ to hold attributes. If the class uses any of these techniques, __dict__ either will not exist or may not be complete. A few of the techniques that come to mind are: * custom __getattr__/__setattr__ methods (or __getattribute__ in a new style class) * descriptors (http://docs.python.org/ref/descriptors.html) * using __slots__ in a new style class Dave From steve at holdenweb.com Sun Jul 15 17:39:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 15 Jul 2007 17:39:20 -0400 Subject: zipfile 2GB problems? In-Reply-To: <1184528949.751377.5620@g4g2000hsf.googlegroups.com> References: <1184474112.081258.111490@n60g2000hse.googlegroups.com> <1184525970.082235.238200@q75g2000hsh.googlegroups.com> <1184528949.751377.5620@g4g2000hsf.googlegroups.com> Message-ID: xamdam wrote: >>> Additional info: my file is from a data provider, do not know what >>> they used to compress it. Previous files worked ok, this one is the >>> 1st over 2GB. Winzip has no problem with it. >> It could be you are using a Python with an in-built limit of 2GB on file >> size. What happens if you open the file, seek past the 2GB point and >> then try and read data? >> > > Steve, > I used is_zipfile function, which from does exactly that from a quick > read - goes to the end, reads expected string. It worked fine. Tried > regular Windows 2.4.4 and 2.5.1, same result. > Fine, if it isn't file size limitations I suspect you need to post some code and a traceback so we can get better insight into exactly what the problem is. 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 bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jul 23 11:46:03 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 23 Jul 2007 17:46:03 +0200 Subject: decorators tutorials In-Reply-To: <1185192282.331334.213730@x35g2000prf.googlegroups.com> References: <1185178383.499234.299850@z24g2000prh.googlegroups.com> <1185180112.321457.73170@n2g2000hse.googlegroups.com> <1185183257.471106.318070@x35g2000prf.googlegroups.com> <46a48245$0$19544$426a34cc@news.free.fr> <1185192282.331334.213730@x35g2000prf.googlegroups.com> Message-ID: <46a4cd39$0$29029$426a34cc@news.free.fr> james_027 a ?crit : > hi bruno, > > That seems to be hard to read at all, or I am just very new to python? or just new to higher order functions ? (ie: functions working on functions). > With that decorator how do I take advantage of it compare when I just > write a function that could do the same as what the decorator did? I > could translate the could from above into ... > > def check_login(msg): > #... > def my_func(toto, tata): > #... > > #call it like this > check_login('msg') > my_func('toto', 'tata') The first (and already very important difference) is that, with your solution, you have to remember to explicitely call check_login before calling my_func, while the decorator will take care of this. This allow to factor out orthogonal behaviours (like permission management, logging etc). Now there are almost endless other possible uses - anything that requires adding metadata to functions (CherryPy's way of flagging request handlers), registering functions for later use (ie: entry points for a plugin system, rule-based dispatch etc), triggering other behaviours before and/or after the function call - possibly bypassing the call to the original function, etc, etc, etc. Note that the important part here is not the @decorator syntax - which is just (nice) syntactic sugar - but the ability to use higher order functions. From steve at holdenweb.com Tue Jul 31 22:51:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 31 Jul 2007 22:51:46 -0400 Subject: Reload after an exception, not possible ? In-Reply-To: References: Message-ID: 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, 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. 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 Jul 24 20:28:30 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 25 Jul 2007 00:28:30 GMT Subject: datetime.time() class - How to pass it a time string? References: <1185297087.998644.53940@r34g2000hsd.googlegroups.com> <87hcntjqu3.fsf@benfinney.id.au> Message-ID: On 2007-07-24, Ben Finney wrote: > Neil Cerutti writes: > >> On 2007-07-24, Robert Dailey wrote: >> > Hi, >> > >> > I have a string in the following format: >> > >> > "00:00:25.886411" >> > >> > I would like to pass this string into the datetime.time() class >> > and have it parse the string and use the values. However, the >> > __init__() method only takes integers (which means I'd be >> > forced to parse the string myself). Does anyone know of a way I >> > can make it use the string? Thanks. >> >> Consult the documentation about time.strptime (to start) and then >> datetime.strptime (which refers back to the time.strptime docs, >> in a rather unfortunate manner). > > Unfortunately 'strptime' also only seems to parse the components as > integers: > > >>> import datetime > >>> time_format = "%H:%M:%S" > >>> time_value = datetime.datetime.strptime("09:45:31.064371", time_format) > Traceback (most recent call last): > File "", line 1, in > File "/usr/lib/python2.5/_strptime.py", line 334, in strptime > data_string[found.end():]) > ValueError: unconverted data remains: .064371 > > The same thing happens with 'time.strptime'. So this isn't yet > a solution for the OP. Bummer. Thanks for the info. I should consult the documentation, too, it seems. ;) -- Neil Cerutti From omari at smileystation.com Tue Jul 17 19:04:59 2007 From: omari at smileystation.com (Omari Norman) Date: Tue, 17 Jul 2007 19:04:59 -0400 Subject: Lookup encoding aliases in Python 2.4 Message-ID: <20070717230459.GB15032@cameron> My program creates new XML files (not through the DOM, but just by simple file.write calls.) It would be nice if said files would be in the default system encoding. So in Python 2.5 I use ENCODING = codecs.lookup(locale.getdefaultlocale()[1]).name locale.getdefaultlocale()[1] sometimes returns a non-canonical encoding name, such as 'UTF8'. This gives the xml.sax parser a fit, so I use codecs.lookup to convert the alias to the canonical encoding name. I then write this encoding in the top line of the XML file. Python 2.4's codecs.lookup works differently--it does not return names. Is there any way to accomplish this in Python 2.4? I went looking through the codecs module in 2.5 to see if I could find a dict with the aliases, to no avail. I suppose the worst-case scenario is that I make a dict myself with common encodings in it (or, just tell people to use Python 2.5.) Thanks, Omari -- Batteries not included; you put it together. From omari at smileystation.com Sun Jul 8 12:01:45 2007 From: omari at smileystation.com (Omari Norman) Date: Sun, 8 Jul 2007 12:01:45 -0400 Subject: Validating XML in Windows Message-ID: <20070708160145.GB9910@cameron> My app needs to validate XML. That's easy enough in Unix. What is the best way to do it in Windows? The most obvious choice would of course be PyXML. However, apparently it is no longer maintained: http://sourceforge.net/project/showfiles.php?group_id=6473 so there are no Windows binaries that work with Python 2.5. Getting other XML libraries like libxml2 also seems to be quite difficult on Windows. Has anyone else dealt with this problem and found a solution? It would even be fine if I could find a free command-line validator that I could invoke with subprocess, but I haven't even had luck with that. Thanks, Omari -- Pay a little now, or pay a lot later. From jstroud at mbi.ucla.edu Wed Jul 18 16:51:56 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 18 Jul 2007 13:51:56 -0700 Subject: Property Descriptor - Public Getter, Private Setter In-Reply-To: <1184771137.140502.187210@e16g2000pri.googlegroups.com> References: <1184771137.140502.187210@e16g2000pri.googlegroups.com> Message-ID: gamehack wrote: > Hi all, > > I was looking around the net to figure out how I can use the > property() descriptor to make a property readable by everyone and only > settable by the class or any derived classes. Thanks. > > Regards, > gh > Congratulations, you have discovered a principal use of properties--to restrict access! But how? By the honor system, of course, and some clever naming techniques and documentation. Below we see all of the essential components. 1. clever naming -- our attribute is prepended with an underscore, signifying its special status as an internal name and will not be exposed to the API. 2. documentation -- we let our users know about the value property 3. properties -- we make a property named value that is exposed to the API, but we don't expose _value as it is not available beyond the class and subclasses implicitly, by virtue of clever naming (see 1) class C(object): """ Instances of this class are endowed with a 'value' property. This property is read-only for users of the API. Have a Nice Day. """ def __init__(self): self._value = None def get_value(self): return self._value value = property(get_value) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From deets at nospam.web.de Mon Jul 9 13:09:03 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jul 2007 19:09:03 +0200 Subject: Python ghost compile In-Reply-To: References: Message-ID: <5ff8diF3bpjp0U1@mid.uni-berlin.de> funtimes at mailinator.com schrieb: > I split a large python (2.5.1) program into three modules. Let's call > them mainmod, submod1, and submod2. mainmod imports submod1 and submod2. > When I make changes to any of these modules, it is not reflected in the > compile. Only if exit idle and re-run idle. I've removed the two > relevant .pyc files. It holds onto the first compile made after starting > idle. I've triple-checked the names I've given the modules, they're all > unique. Any clues? Use reload. Or an external interpreter, to avoid side-effects. Diez From carsten at uniqsys.com Sat Jul 21 22:40:44 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 21 Jul 2007 22:40:44 -0400 Subject: [2.5] Regex doesn't support MULTILINE? In-Reply-To: <7xy7h9kwi9.fsf@ruckus.brouhaha.com> References: <7xy7h9kwi9.fsf@ruckus.brouhaha.com> Message-ID: <1185072044.4151.9.camel@localhost.localdomain> On Sat, 2007-07-21 at 19:22 -0700, Paul Rubin wrote: > Carsten Haese writes: > > Use an actual HTML parser such as BeautifulSoup > > (http://www.crummy.com/software/BeautifulSoup/) and your life will be > > much easier. > > BeautifulSoup is a lot simpler to use than RE's but a heck of a lot > slower. I ended up having to use RE's last time I had to scrape a lot > of pages. True, but the OP said "extract information from a web page", not "from a lot of pages." Until BeautifulSoup is actually too slow for that job, going straight to RE is premature optimization. -- Carsten Haese http://informixdb.sourceforge.net From kyosohma at gmail.com Tue Jul 31 10:43:11 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 31 Jul 2007 14:43:11 -0000 Subject: how to add a toolbar to a Frame using wxpython In-Reply-To: <1185888258.035919.55880@b79g2000hse.googlegroups.com> References: <1185888258.035919.55880@b79g2000hse.googlegroups.com> Message-ID: <1185892991.678744.218280@z24g2000prh.googlegroups.com> On Jul 31, 8:24 am, yadin wrote: > hi > please am learning wxpython and I Need help on getting examles of how > to create a toolbar with images > that is add a toolbar to a Frame using wxpython > using wxpython on a windows pc > how can i add a toolbar to a GUI > all sample codes i could find contain errors. > i did the following but it is wrong! > my biggest trouble seems to be with the IMAGES? do i have to create > them, load them...? or they come with python like in Matlab > thank you. > > import wx > > from pylab import* > > class MainWindow(wx.Frame): > def __init__(self,parent,id,title): > self.dirname='' > wx.Frame.__init__(self,parent,wx.ID_ANY, > title,wx.DefaultPosition, wx.Size(320,410)) > > ##############_______________________ADDING A > TOOLBAR___________________###################### > > toolbar = wx.ToolBar(self, -1, style=wx.TB_HORIZONTAL | > wx.NO_BORDER) > toolbar.AddSimpleTool(1, wx.Image('stock_new.png', > wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'New', '') > toolbar.Realize() > Frame.Add(toolbar, 0, border=5) > > app = wx.PySimpleApp() > frame = MainWindow(None, -1, " dipole antenna ") > frame.show(1) > frame.SetBackgroundColour('light grey') > app.MainLoop() The internal pictures that I've found so far for wxPython are listed here: http://www.wxpython.org/docs/api/wx.ArtProvider-class.html If you need to create your own icons / bitmaps, I use the img2py utility included with wxPython. It's usage is below: # on the command line in windows # You have to pass a filename in for img2py to sends its output to c:\Python24\Lib\site-packages\wx-2.8-msw-ansi\wx\tools>python img2py.py -i iconFileName iconPyFile.py Also see: http://www.wxpython.org/docs/api/wx.tools.img2py-module.html Then I just created a function to create my toolbar: def createToolbar(self): toolbar = self.CreateToolBar() toolbar.SetToolBitmapSize((31,31)) bmp = mail_ico.getBitmap() sendTool = toolbar.AddSimpleTool(-1, bmp, 'Send', 'Sends Email') self.Bind(wx.EVT_MENU, self.OnSend, sendTool) toolbar.Realize() One caveat: I don't know how to force an image to scale to the size of the toolbar button. You'll have to figure that out on your own. You can also post to the wxPython list, which might give you more coherent answers: http://www.wxpython.org/maillist.php Mike From horpner at yahoo.com Tue Jul 3 14:11:04 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 03 Jul 2007 18:11:04 GMT Subject: python 3.0 or 3000 ....is it worth waiting??? Newbie Question References: <468a8dc1$0$27406$ba4acef3@news.orange.fr> Message-ID: On 2007-07-03, M?ta-MCI wrote: > Hi! > >> Python 3000 doesn't include many significant changes to the language > > One exemple : non-Ascii characters in identifiers (= no significatif > change?) It is one of not many? -- Neil Cerutti From craig.howard at earthlink.net Tue Jul 17 18:18:38 2007 From: craig.howard at earthlink.net (Craig Howard) Date: Tue, 17 Jul 2007 18:18:38 -0400 Subject: Single-stepping through a python script Message-ID: <534DE6C4-5100-4936-BD80-E77987A46F72@earthlink.net> Hello All: Is is possible to compile a code object and single-step through its execution? Craig From horpner at yahoo.com Mon Jul 2 13:18:27 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 02 Jul 2007 17:18:27 GMT Subject: Pretty Scheme, ??? Python Message-ID: The following simple language parser and interpreter is from chapter 2 of the textbook: _Programming Languages: Application and Interpretation_, by Shriram Krishnamurthi. http://www.cs.brown.edu/~sk/Publications/Books/ProgLangs/ First, I'll show the Scheme version of the program, which uses the cool define-type and type-case macros (I'd never heard of them before reading this book, which is too bad). I think it is beautiful. ; Our grammar: ; ::= ; ; | { + } ; | { - } ; | {with { } } ; | (define-type WAE [num (n number?)] [add (lhs WAE?) (rhs WAE?)] [sub (lhs WAE?) (rhs WAE?)] [id (name symbol?)] [with (name symbol?) (named-expr WAE?) (named-body WAE?)]) ;; parse : sexp --> WAE ;; To convert s-expressions into WAEs (define (parse sexp) (cond [(number? sexp) (num sexp)] [(symbol? sexp) (id sexp)] [(list? sexp) (case (first sexp) [(+) (if (= (length sexp) 3) (add (parse (second sexp)) (parse (third sexp))) (error 'parse "add: expected 2 args"))] [(-) (if (= (length sexp) 3) (sub (parse (second sexp)) (parse (third sexp))) (error 'parse "sub: expected 2 args"))] [(with) (with (first (second sexp)) (parse (second (second sexp))) (parse (third sexp)))] [else (error 'parse "invalid expression")])] [else (error 'parse "invalid expression")])) ;; subst : WAE symbol WAE --> WAE ;; substitutes second argument with third argument in first argument, ;; as per the rules of substitution; the resulting expression contains ;; no free instances of the second argument. (define (subst expr sub-id val) (type-case WAE expr [num (n) expr] [add (lhs rhs) (add (subst lhs sub-id val) (subst rhs sub-id val))] [sub (lhs rhs) (sub (subst lhs sub-id val) (subst rhs sub-id val))] [with (bound-id named-expr bound-body) (if (symbol=? bound-id sub-id) (with bound-id (subst named-expr sub-id val) bound-body) (with bound-id (subst named-expr sub-id val) (subst bound-body sub-id val)))] [id (v) (if (symbol=? v sub-id) val expr)])) ;; calc : WAE --> number ;; consumes a WAE and computes the corresponding number (define (calc an-ae) (type-case WAE an-ae [num (n) n] [add (lhs rhs) (+ (calc lhs) (calc rhs))] [sub (lhs rhs) (- (calc lhs) (calc rhs))] [with (bound-id named-expr bound-body) (calc (subst bound-body bound-id (num (calc named-expr))))] [id (v) (error 'calc "free identifier")])) (test (calc (parse '3)) 3) (test (calc (parse '{+ 3 4})) 7) (test (calc (parse '{+ {- 3 4} 7})) 6) ; etc... the rest of the tests omited The following is a translation of the above program into Python, as best as I could. I have not included the simple s-expression parser that I had to write as a front-end, but I'll post if if anyone's interested. The type-case is replaced with a class hierarchy, resulting in some extra syntax. Most of the docstrings and tests have been omited as irrelevant. import sexp import operator class Wae(object): """ An abstract base class for representing the abstract syntax tree of a Wae expression. """ def calc(self): raise NotImplementedError class Num(Wae): """ This subclass represents numbers. """ def __init__(self, number): self.number = number def __repr__(self): return '' % self.number def subst_(self, sub_id, value): return self def calc(self): return self.number class Id(Wae): """ This subclass represents an identifier. """ def __init__(self, name): self.name = name def __repr__(self): return '' % self.name def subst_(self, sub_id, value): if self.name == sub_id: return value return self def calc(self): raise SyntaxError('Free identifier '+self.name) class BinOp(Wae): """ This abstract class represents binary operations. """ def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def __repr__(self): return '<%s %r %r>' % (self.__class__.__name__, self.lhs, self.rhs) def subst_(self, sub_id, value): return self.__class__(self.lhs.subst_(sub_id, value), self.rhs.subst_(sub_id, value)) def calc(self): return self.op(self.lhs.calc(), self.rhs.calc()) class Add(BinOp): """ This subclass represents an addition expression. """ def __init__(self, lhs, rhs): super(Add, self).__init__(lhs, rhs) self.op = operator.add class Sub(BinOp): """ This subclass represents a substraction expression. """ def __init__(self, lhs, rhs): super(Sub, self).__init__(lhs, rhs) self.op = operator.sub class With(Wae): """ This subclass represents the Wae binding expression, 'with'. """ def __init__(self, bound_id, named_expr, bound_body): self.bound_id = bound_id self.named_expr = named_expr self.bound_body = bound_body def __repr__(self): return '' % (self.bound_id, self.named_expr, self.bound_body) def calc(self): return self.bound_body.subst_( self.bound_id, Num(self.named_expr.calc())).calc() def subst_(self, sub_id, value): if sub_id == self.bound_id: return With(self.bound_id, self.named_expr.subst_(sub_id, value), self.bound_body) else: return With(self.bound_id, self.named_expr.subst_(sub_id, value), self.bound_body.subst_(sub_id, value)) # parse : sexp --> Wae # Wae grammar: # Wae ::= Num # Wae ::= ( + ) # Wae ::= ( - ) # Wae ::= ( with ( Id ) ) # Wae ::= Id def parse(expr): """ Compile a string representing an WAE expression into an object that represents the abstract syntax tree of that expression. The AST provides a calc method that returns the result of evaluating the expression. >>> parse('(+ 4 5)') > >>> parse('(+ 4)') Traceback (most recent call last): ... SyntaxError: Ill-formed expression >>> parse('(with (x) (+ x x))') Traceback (most recent call last): ... SyntaxError: Ill-formed expression >>> parse('3').calc() 3 >>> parse('(+ 3 4)').calc() 7 >>> parse('(with (x (+ 5 5)) (+ x x))').calc() 20 >>> parse('(with (x x) x)').calc() Traceback (most recent call last): ... SyntaxError: Free identifier x """ def parse_ast(ast): if isinstance(ast, int): return Num(ast) elif isinstance(ast, str): return Id(ast) elif isinstance(ast, tuple): op = ast[0] if op in ['+', '-'] and len(ast) == 3: if op == '+': return Add(parse_ast(ast[1]), parse_ast(ast[2])) elif op == '-': return Sub(parse_ast(ast[1]), parse_ast(ast[2])) elif op == 'with' and len(ast) == 3 and len(ast[1]) == 2: return With(ast[1][0], parse_ast(ast[1][1]), parse_ast(ast[2])) raise SyntaxError("Ill-formed expression") return parse_ast(sexp.read(expr)) The sexp parser I wrote returns a tuple that represents the parse tree of an s-expression, and recognizes only s-expressions, strings and integers. How can I make the Python more idiomatic Python? How can I make it more "beautiful"? A type hierarchy seems over-engineered in comparison to Scheme's type-case, but I liked a cascade of isinstance calls (as in parse) even less. The type hierarchy did allow me to factor out the code duplication in the (sub ...) and (add ...) types of Scheme, and seems like a nice benefit over type-case. -- Neil Cerutti From ahlongxp at gmail.com Tue Jul 10 23:47:24 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Wed, 11 Jul 2007 03:47:24 -0000 Subject: socket.makefile() buggy? In-Reply-To: <87ps2zes1v.fsf@pobox.com> References: <1183892789.434028.15370@x35g2000prf.googlegroups.com> <1183970531.241008.295940@z28g2000prd.googlegroups.com> <87ps2zes1v.fsf@pobox.com> Message-ID: <1184125644.392077.299470@p39g2000hse.googlegroups.com> On Jul 11, 7:51 am, j... at pobox.com (John J. Lee) wrote: > Steve Holden writes: > > ahlongxp wrote: > >> On Jul 8, 9:54 pm, Steve Holden wrote: > >>> That's a pretty pejorative subject line for someone who's been > >>> programming Python [guessing by the date of your first post] for about a > >>> month. > > > [...] > >> And last but not least, I' here to be helped and help as long as I > >> can. > >> But as you noticed I'm not very good at expressing myself in English. > >> I didn't mean to offense anyone but I might seem to be rude or > >> offensive. > >> I hope you can understand. > > > Sure. I felt it necessary to explain my remarks as my own remarks > > seemed potentially rude or offensive. Naturally not everyone has > > English as a first language, but your first post was good enough that > > it wasn't immediately obvious in your case. > > This is the danger in getting too good at another language :-) > ahlongxp, maybe you should drop some deliberate mistakes in your > too-good English ;-) > > And FWLIW, I'd be less surprised than Steve at your finding a real bug > in Python's socket code... > > John Sorry, I don't think I understand what you are trying to say. But thanks for your response anyway. Frank Swarbrick, thank your for your advice. I'll think about it. -- ahlongxp Software College,Northeastern University,China ahlongxp at gmail.com http://www.herofit.cn From skip at pobox.com Wed Jul 18 10:49:40 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 18 Jul 2007 09:49:40 -0500 Subject: Mouse/keyboard watcher? Message-ID: <18078.10372.792537.288757@montanaro.dyndns.org> Sorry to bomb this list with an off-topic post, however... Ages ago I wrote a mouse/keyboard watcher in Python+Tk: http://sf.net/projects/watch. It's been idle for a long while though, isn't terribly portable and doesn't work properly with tools like Synergy (http://sf.net/projects/synergy2). Someone, I thought from this list or maybe python-dev, told me about a newer open source application in the same space which is more portable and actively maintained/developed. Alas, I can't recall the name, nor can I find it on my computer. Ring any bells? Thx, Skip From rustompmody at gmail.com Sat Jul 14 09:48:05 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 14 Jul 2007 19:18:05 +0530 Subject: Can a low-level programmer learn OOP? In-Reply-To: <1i17kzo.1kphm951d3jl5dN%aleax@mac.com> References: <1i17kzo.1kphm951d3jl5dN%aleax@mac.com> Message-ID: On 7/14/07, Alex Martelli wrote: > > OOP can be abused (particularly with deep or intricate inheritance > structures). But the base concept is simple and clear: you can bundle > state and behavior into a stateful "black box" (of which you may make as > many instances, with independent state but equal behavior, as you need). > Many years ago (86??) Wegner wrote a paper in OOPSLA called Dimensions of Object Orientation in which he called the 'base concept' of 'bundle of state and behavior' as 'object based' programming and 'object-oriented' as object-based + inheritance. What Alex is saying is (in effect) that object-based is simple and clear (and useful) whereas the object-orientation is subject to abuse. This anyway is my experience: C++ programmers are distinctly poorer programmers than C programmers -- for some strange reason closeness to the machine has a salutary effect whereas the encouragment of uselessly over-engineered programs makes worse programmers. GUI is one of those cases wherein inheritance actually helps people produce better code but this is something of an exception. And even here one of the most widely used popularisers of GUIs has been VB which was (at least initially) not object-oriented. VB shows that language orientation -- tailoring 'the language' of drag-n-drop to GUI-building and not just GUI-use -- wins over OOP. Ruby/Rails is another example of language-oriented programming though I feel it goes too far in (de)capitalizing, pluralizing, (de)hyphenizing etc towards 'readability'. [Sorry if this offends some people -- just my view!] And this makes me wonder: It seems that Tkinter, wxpython, pygtk etc are so much more popular among pythonistas than glade, dabo etc. Why is this? From acprkit at gmail.com Wed Jul 4 17:24:46 2007 From: acprkit at gmail.com (acprkit) Date: Wed, 04 Jul 2007 14:24:46 -0700 Subject: deleated bios? Message-ID: <1183584286.963465.324820@n60g2000hse.googlegroups.com> Hi I have an ibm thinkpad x23, and shut it down about an hour ago. When I went to reboot , all the lights come on then they go off and only the light with the z in a circle stays on. The screen stays blank and the hard drive spins. Could I have deleated the bios when I added memory (shocked the motherboard?) Thanks for any help! From stefan.behnel-n05pAM at web.de Wed Jul 4 02:18:03 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 04 Jul 2007 08:18:03 +0200 Subject: XML / Unicode / SAX question In-Reply-To: <1183527548.695326.303120@i13g2000prf.googlegroups.com> References: <1183527548.695326.303120@i13g2000prf.googlegroups.com> Message-ID: <468B3B9B.9070504@web.de> IamIan wrote: > I am using SAX to parse XML that has numeric html entities I need to > convert and feed to JavaScript as part of a CGI. I can get the > characters to print correctly, but not without being surrounded by > linebreaks: > > def characters(self, ch): > if self.isNews: > ch = unescape(ch) > print ch The print statement introduces line breaks at the end. Use print ch, instead. Note that you have to merge character sequences yourself in SAX. There is no guarantee into how many chunks the textual context of a single tag is broken before it is passed to the characters() SAX method. > For a line like 'Mark à Capbreton' > my results print as: > 'Mark > ? > Capbreton' > > Is this another SAX quirk? I've already had to hack my way around SAX > not being able to split results on a colon. No matter if I try strip, > etc the results are always the same: newlines surrounding the html > entities. I'm using version 2.3.5 and need to stick to the standard > libraries. Thanks. Too bad. If an external library was acceptable (Python 2.3 is ok), I would have proposed lxml, maybe lxml.html (which will be in lxml 2.0), or the Atom implementation on top of lxml.etree. http://codespeak.net/lxml http://codespeak.net/svn/lxml/branch/html/ https://svn.openplans.org/svn/TaggerClient/trunk/taggerclient/atom.py Hope it helps, Stefan From irmen.NOSPAM at xs4all.nl Thu Jul 19 17:25:35 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Thu, 19 Jul 2007 23:25:35 +0200 Subject: Pickled objects over the network In-Reply-To: References: <9c8d48280707171457p4448fdf3of40562bf62a18fc6@mail.gmail.com> <9c8d48280707180812q4343bcbaodbc803e9c9a92acb@mail.gmail.com> Message-ID: <469fd6d9$0$339$e4fe514c@news.xs4all.nl> Rustom Mody wrote: > Sure pyro may be the solution but it may also be overkill > Why not use safe_load from the yaml module? In what way would Pyro be overkill where Yaml (also a module that you need to install separately) wouldn't be? -irmen From funtimes at mailinator.com Mon Jul 9 10:15:57 2007 From: funtimes at mailinator.com (funtimes at mailinator.com) Date: Mon, 09 Jul 2007 10:15:57 -0400 Subject: Python ghost compile Message-ID: <5.2.1.1.0.20070709101536.025c69a0@goldy.holtzman.net> I split a large python (2.5.1) program into three modules. Let's call them mainmod, submod1, and submod2. mainmod imports submod1 and submod2. When I make changes to any of these modules, it is not reflected in the compile. Only if exit idle and re-run idle. I've removed the two relevant .pyc files. It holds onto the first compile made after starting idle. I've triple-checked the names I've given the modules, they're all unique. Any clues? From jstroud at mbi.ucla.edu Tue Jul 17 17:19:18 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 17 Jul 2007 14:19:18 -0700 Subject: Design question regarding exceptions. In-Reply-To: <1184701939.282684.260730@o11g2000prd.googlegroups.com> References: <1184701939.282684.260730@o11g2000prd.googlegroups.com> Message-ID: asincero wrote: > I have a class called Users that provides a higher level of > abstraction to an underlying "users" table in a pgsql database. It > has methods like "addUser()" and "deleteUser()" which, obviously, wrap > the corresponding SQL statements. My question is would it better to > let any exceptions thrown by the underlying DB-API calls bubble up > from these methods, or should I catch them inside the methods, wrap > them inside my own custom exceptions, and throw those exceptions > instead? > > Thanks. > > -- Arcadio > I don't think its wise to mask or otherwise waste cpu cycles catching and re-throwing lower level exceptions. If you anticipate problems with certain inputs, test for those possibilities and raise custom exceptions at module level. At package level, you can import a module with your package exceptions defined. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From semanticist at gmail.com Mon Jul 9 20:39:56 2007 From: semanticist at gmail.com (Miles) Date: Mon, 09 Jul 2007 17:39:56 -0700 Subject: "Empty" text In-Reply-To: References: <469147b8$1@griseus.its.uu.se><5fd1aeF3berb8U1@mid.uni-berlin.de> Message-ID: <1184027996.534390.315640@22g2000hsm.googlegroups.com> On Jul 9, 4:30 am, Nick Craig-Wood wrote: > Marc 'BlackJack' Rintsch wrote: > > On Sun, 08 Jul 2007 22:23:20 +0200, Jan Danielsson wrote: > > > Firefox is very unhappy about the textarea not having separate > > > opening and a closing tags. i.e. I need this: > > > > Then either Firefox is broken or you don't declare your XHTML properly and > > Firefox thinks it's HTML. > > I suspect the former - we noticed exactly the same thing (can't > remember which tags we were having problems with), using the > declaration :- > > > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> > > I haven't tested this again recently though. Firefox is not broken. The XML prolog and DOCTYPE do not affect HTML vs. XHTML interpretation--only the Content-Type does. If you are serving a page as "text/html", which you almost certainly are, then all browsers will parse it as HTML, regardless of prolog and doctype, and HTML does not support self-closing tags. You need to serve the page as "application/xhtml+xml", or avoid self-closing tags on elements other than ,
    , , etc. http://www.w3.org/TR/xhtml1/#C_3 From gmm2064 at yahoo.com Wed Jul 11 16:36:39 2007 From: gmm2064 at yahoo.com (GM M) Date: Wed, 11 Jul 2007 13:36:39 -0700 (PDT) Subject: C Python Network Performance Message-ID: <20070711203639.8099.qmail@web51805.mail.re2.yahoo.com> Hello, I am writing an application bulk of which is sending and receving UDP data. I was evaluating which language will be a better fit for the job. I wrote following small pieces of code in Python and C respectively: from socket import * import sys if __name__ == '__main__': s = socket(AF_INET, SOCK_DGRAM) while True: s.sendto("hello", (sys.argv[1], int(sys.argv[2]))) #include #include #include #include #include #define true 1 #define false 0 int main(int len, char** args){ int s = socket(AF_INET, SOCK_DGRAM, 0); struct sockaddr_in s_addr; inet_pton(AF_INET, args[1], &(s_addr.sin_addr)); printf("%s:%s\n", args[1], args[2]); in_port_t port; sscanf(args[2], "%u", &port); s_addr.sin_port = htons(port); s_addr.sin_family = AF_INET; char* msg = "hello"; int msg_len = 6; int addr_len = sizeof(struct sockaddr); struct sockaddr* s_g_addr = (struct sockaddr*) &s_addr; while(true){ int success = sendto(s, msg, msg_len, 0, s_g_addr, addr_len); } } Both pieces of code, take IP address and port on command line initely send UDP messages to the target. In this experiment target is another machine of mine and I record the data rate received at that machine. I was surpirised to see that python code was able to achieve 4-10 times higher data rate than C. I was expecting C code to perform the same, if not better. Can anyone please explain why this is the case? Thanks Ghulam Memon --------------------------------- Building a website is a piece of cake. Yahoo! Small Business gives you all the tools to get online. -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE.THIS.cybersource.com.au Tue Jul 10 19:24:11 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 11 Jul 2007 09:24:11 +1000 Subject: bool behavior in Python 3000? References: Message-ID: On Tue, 10 Jul 2007 13:13:38 -0600, Steven Bethard wrote: > It's much easier to explain to newcomers that *, + and - work on True > and False as if they were 1 and 0 than it is to introduce them to a two > element boolean algebra. So making this kind of change needs a pretty > strong motivation from real-world code. Pretending that False and True are just "magic names" for 0 and 1 might be "easier" than real boolean algebra, but that puts the cart before the horse. Functionality comes first: Python has lists and dicts and sets despite them not being ints, and somehow newcomers cope. I'm sure they will cope with False and True not being integers either. I mean, really, does anyone *expect* True+True to give 2, or that 2**True even works, without having learnt that Python bools are ints? I doubt it. And the old Python idiom for an if...then...else expression: ["something", "or other"][True] tends to come as a great surprise to most newbies. So I would argue that bools being ints is more surprising than the opposite would be. -- Steven. From esj at harvee.org Sun Jul 15 11:38:33 2007 From: esj at harvee.org (Eric S. Johansson) Date: Sun, 15 Jul 2007 11:38:33 -0400 Subject: in a bit of a quandary about an SMTP receiver Message-ID: I have wasted way too much time on this problem already and I'm hoping it's just that I'm missing some bit of information somewhere. I need an SMTP receiver so I can handle filter requests from a postfix mail server. the asyncore version works fine for one request at a time. This is great except I need to process bursts of 10 to 15 request per second and individual requests sometimes run 0.5-10 seconds per request. most of the filter work is either network or database query limited so queuing up a bunch of requests and handling them in parallel should work fine. I have tried using a threaded version od smtpd.py but, I'm not convinced it's running any more than one thread at a time and properly splitting off threads at the right time. Maybe my test case was inadequate but, high level of no confidence there. If someone can show me that I'm wrong, that would be wonderful. starting point: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440690 Another recommendation was twisted as a foundation for building a new server but it would take me as long to build a new server from scratch using ordinary sockets as it would take me to learn how to use twisted. the documentation leads me to two conclusions. First is that twisted is a career, not something for getting a job done. This is not meant to be disparaging but reflects three factors. A steep learning curve, minimum amount of knowledge necessary to get a job done, and persistence of that knowledge once the job is done especially if you don't live in the twisted environment all the time. The second is that for someone like me (speech recognition driven) twisted is pain. Pain, pain, pain from way too much hand use caused by bumpy cap names. normally, this shouldn't affect anybody else but for me, it is a serious disincentive. Having said this, I have no other real objections to twisted and if someone wants to help by volunteering to build an SMTP receiver capable of being used as postfix filter interface, I would be glad to work with them. The last option is building a new smtp filter around SocketServer but again, there is a serious lack of documentation making it another career option. I am really stuck. I can't go forward and there really isn't any other solution than I can see. If there was some way to use the baseline asyncore code to handle multiple simultaneous requests, I could just do all my work another process but I'm not seeing how I can context switch between multiple connections/connection states using asyncore as it stands today. Help? From horpner at yahoo.com Tue Jul 17 09:47:17 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 17 Jul 2007 13:47:17 GMT Subject: a=0100; print a ; 64 how to reverse this? References: <1184670575.205759.115360@i13g2000prf.googlegroups.com> <1184673934.660465.228280@i13g2000prf.googlegroups.com> <1184676038.231330.115220@e16g2000pri.googlegroups.com> Message-ID: On 2007-07-17, mosi wrote: > Thank you, > this is great, > I thought that this should be standard in python 2.4 or 2.5 or in some > standard library (math ???) > Didn`t find anything. Support is built-in for string representations of numbers in other than base 10, but conversions to integer is the only support. You can do: >>> d = int(s, base). but not: >>> s = str(d, base) The % format operator can do hex and octal, I believe. -- Neil Cerutti From zxo102 at gmail.com Wed Jul 18 23:34:21 2007 From: zxo102 at gmail.com (zxo102) Date: Wed, 18 Jul 2007 20:34:21 -0700 Subject: Is it possible to run two "while 1:" loops in two threadings respectively? In-Reply-To: <5g37qmF3earqjU1@mid.uni-berlin.de> References: <1184648352.400425.322440@e9g2000prf.googlegroups.com> <5g37qmF3earqjU1@mid.uni-berlin.de> Message-ID: <1184816061.329956.283180@i38g2000prf.googlegroups.com> On 7 17 , 3 01 , "Diez B. Roggisch" wrote: > zxo102 schrieb: > > > > > > > Hi, > > I would like to combine two python applications into a single one > > with two threadings. Both of them have a "while 1:" loop respectively. > > For example, one application is to monitoring serial port 'com1' and > > another application is a TCP/IP server which has used threadings > > already. I write the following demo code but it does not work right. > > It stays in the first "while 1:" and never thingOne.start(). The > > second threading never be started. > > Any ideas? > > > Thanks a lot. > > > Ouyang > > ################################################################# > > import threading, time > > class serial_port_com1: > > def spc(self): > > i = 0 > > while 1: > > time.sleep(5) > > print "%d: hello, I am here in spc()"%i > > i += 1 > > > class TCP_IP: > > def tcpip(self): > > i = 0 > > while 1: > > time.sleep(5) > > print "%d: hello, I am here in tcpip()"%i > > i += 1 > > > class ThreadOne ( threading.Thread ): > > def run ( self ): > > print 'Thread', self.getName(), 'started.' > > time.sleep ( 5 ) > > print 'Thread', self.getName(), 'ended.' > > > class ThreadTwo ( threading.Thread ): > > def run ( self ): > > print 'Thread', self.getName(), 'started.' > > thingOne.join() > > print 'Thread', self.getName(), 'ended.' > > > if __name__=="__main__": > > spc = serial_port_com1() > > tcpip = TCP_IP() > > thingOne = ThreadOne(target=spc.spc()) > > thingOne.start() > > thingTwo = ThreadTwo(target=tcpip.tcpip()) > > thingTwo.start() > > There are several problems here. First of all, one either subclasses > Thread and implements run - then your code should look like this: > > class ThreadTwo(Thread): > def run(self): > tcpip.tcpip() > > Or you don't subclass Thread and pass a target. But that target must be > a function. You don't pass a function, you call it!! > > Look at this: > > Thread(target=tcpip.tcpip) > > Note the missing parentheses! > > Apart from that, you should seriously consider applying a consistent > naming style to your code. > > Diez- - > > - - Diez, Thanks for your reply. I have tried the both you suggested. First one works and second one does not. I am using "subclass thread" way to implement my application. Thanks a lot. ouyang From carsten at uniqsys.com Tue Jul 24 09:47:16 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 24 Jul 2007 09:47:16 -0400 Subject: How do I 'stat' online files? In-Reply-To: References: Message-ID: <1185284836.3370.11.camel@dot.uniqsys.com> On Tue, 2007-07-24 at 09:07 -0400, DB Daniel Brown wrote: > I am working on a program that needs to stat files (gif, swf, xml, > dirs, etc) from the web. I know how to stat a local file? > > > import os > tplStat = os.stat(path) > > > > but I can?t figure out how to stat a file that resides on a web > server. You can't stat a file on a web server. > I am not sure if it makes a difference, but most (maybe all) of the > files that I need to stat reside within the same domain that will > generate the request. As long as you use HTTP to get to the file, that makes no difference. If you can get to the file via NFS or SMB, that would help. > I am able to open the file by using > > > > import urllib > > f = urllib.urlopen(url) > > > > but for some reason I cannot stat the files. That's because urlopen returns a file-like object, not a file. The best you can hope for is to inspect the headers that the web server returns: >>> import urllib >>> f = urllib.urlopen("http://www.python.org") >>> f.headers['last-modified'] 'Mon, 23 Jul 2007 20:35:52 GMT' >>> f.headers.items() [('content-length', '14053'), ('accept-ranges', 'bytes'), ('server', 'Apache/2.2.3 (Debian) DAV/2 SVN/1.4.2 mod_ssl/2.2.3 OpenSSL/0.9.8c'), ('last-modified', 'Mon, 23 Jul 2007 20:35:52 GMT'), ('connection', 'close'), ('etag', '"60193-36e5-39089a00"'), ('date', 'Tue, 24 Jul 2007 13:42:57 GMT'), ('content-type', 'text/html')] Maybe that's good enough for your needs. HTH, -- Carsten Haese http://informixdb.sourceforge.net From nikbaer at gmail.com Wed Jul 11 19:34:16 2007 From: nikbaer at gmail.com (nik) Date: Wed, 11 Jul 2007 23:34:16 -0000 Subject: interactive graphical script builder Message-ID: <1184196856.996182.25040@k79g2000hse.googlegroups.com> Hi, I am looking for an interactive graphical script builder for python. Basically, something like the os X automator. I have made a group of methods that some non-programmers need to combine into a script. I don't need a python IDE necessarially, but more of a sequence builder. I am imagining a tool that could show graphical representations of my different commands and then string them together in a single "script." I've done a lot of googling, and the closest things that I can find are apple automator or labview, but before I go through the process of making one of those interact with python I would like to know if anybody already knows of something like them that is more tuned to python. Thanks, Nik From _wdx at 163.com Wed Jul 25 03:48:21 2007 From: _wdx at 163.com (_wdx at 163.com) Date: Wed, 25 Jul 2007 00:48:21 -0700 Subject: Unable to abort a FTP command? Message-ID: <1185349701.504484.14370@m37g2000prh.googlegroups.com> Hi, I write the following script to retrieve a part of a large file from a FTP site: import ftplib class ftp_getter(object): def __init__(self): self.handle = ftplib.FTP('ftp_server_address') self.handle.set_debuglevel(2) self.login() def login(self): self.handle.login('user', 'pass') self.handle.cwd('/temp1/') def quit(self, is_close = False): self.handle.quit() if is_close: self.handle.close() print 'ftp handle closed' def getpart_callback(self, received): print "received a packet" if self.cnt <= 0: if not self.outf.closed: self.outf.close() if not self.aborted: try: self.handle.abort() self.aborted = True except Exception,ex: pass else: print 'received packet, [0] = %x' % ord(received[0]) self.outf.write(received) self.cnt -= len(received) def getpart(self, ftp_filename, rest, cnt, out_filename): self.outf = open(out_filename, 'wb') self.cnt = cnt self.aborted = False self.handle.retrbinary('RETR ' + ftp_filename, self.getpart_callback, 8192, rest) if not self.outf.closed: self.outf.close() if __name__ == '__main__': g = ftp_getter() g.getpart('FILE_TO_RETRIEVE.DAT', 50000, 20, 'out.dat') g.quit(True) print "all done." As the last four lines shown, I want to connect to my FTP server, retrieve 20 bytes starting at offset 50000 from FILE_TO_RETRIEVE.DAT, and stop retrieving after more than 20 bytes have been received. It's quite simple, but to my suprise, this code does not work. "self.handle.abort()" have been executed and I got the expected response from server(426), but the RETR command does not seem to stop at all. More and more data are received and getpart_callback method is called again and again. Why the RETR command is not actually aborted? Can anyone help me? Thanks Xu Wang From rvanroode at gmail.com Wed Jul 11 06:02:48 2007 From: rvanroode at gmail.com (rvr) Date: Wed, 11 Jul 2007 10:02:48 -0000 Subject: stripping the first byte from a binary file In-Reply-To: References: <1184063032.195000.25880@i13g2000prf.googlegroups.com> <1184115964.912526.273780@e16g2000pri.googlegroups.com> Message-ID: <1184148168.639675.85900@a26g2000pre.googlegroups.com> On Jul 11, 1:28 pm, Steven D'Aprano wrote: > On Wed, 11 Jul 2007 01:06:04 +0000, rvr wrote: > > Is there a way to edit the file in place? The best I seem to be able to > > do is to use your second solution to read the file into the string, then > > re-open the file for writing and put the whole thing back (minus the > > first byte). Thanks. > > I don't believe that any of the popular operating systems in common use > (Windows, Linux, Mac, *BSD) have any such functionality. > > For safety, you are best off copying the file (minus the first byte) to a > temporary file, then renaming the copy over the original. That way if > your process dies midway through copying the file, you don't lose data. > > Renaming the file is atomic under Linux and (probably) Mac, so it is as > safe as possible. Even under Windows, which isn't atomic, it has a > smaller margin for disaster than over-writing the file in place. Thanks for your response. While searching for solution, I found this: http://mail.python.org/pipermail/python-list/2001-December/116519.html Quoting from it: """ Replace 2 bytes in place beginning at offset 100 (101st byte): f = open('text_input', 'r+b') f.seek(100) f.write(chr(123) + chr(0x80)) f.seek(0,2) f.close() """ Can I use the seek() and write() methods in a similar way to remove the first byte? For whatever reason I can't seem to make it work myself. Thanks again. ~rvr From alia_khouri at yahoo.com Sun Jul 22 19:09:55 2007 From: alia_khouri at yahoo.com (Alia Khouri) Date: Sun, 22 Jul 2007 16:09:55 -0700 Subject: recursively expanding $references in dictionaries In-Reply-To: <1185144473.592477.27570@w3g2000hsg.googlegroups.com> References: <1185144473.592477.27570@w3g2000hsg.googlegroups.com> Message-ID: <1185145795.478500.229370@57g2000hsv.googlegroups.com> Oops, I left some redundant cruft in the function... here it is slightly cleaner: def expand(dikt): names = {} output = {} def _search(_, sourceDict): for key, value in sourceDict.items(): if isinstance(value, dict): _search({}, value) if not '$' in value: names[key] = value _search({}, dikt) def _substitute(targetDict, sourceDict): for key, value in sourceDict.items(): if isinstance(value, dict): new_target = targetDict.setdefault(key, {}) _substitute(new_target, value) else: targetDict[key] = Template(value).substitute(names) _substitute(output, dikt) return output print expand(d2) From marcpp at gmail.com Mon Jul 9 07:35:44 2007 From: marcpp at gmail.com (Marcpp) Date: Mon, 09 Jul 2007 04:35:44 -0700 Subject: wx DatePicker (set blank values) Message-ID: <1183980944.479203.19390@r34g2000hsd.googlegroups.com> I need to set a DatePicker to blank value and GetValue() needs to be 0. Thanks by advance. From nazgul at jsbsystems.com Tue Jul 31 11:09:51 2007 From: nazgul at jsbsystems.com (nazgul) Date: Tue, 31 Jul 2007 10:09:51 -0500 Subject: Compiling 2.5.1 on OpenBSD 4.1 References: <46AC1B91.3070706@v.loewis.de> <46ACC344.1020701@v.loewis.de> <46AD7B62.3090506@v.loewis.de> Message-ID: > I don't have OpenBSD available, so I have to do all my research over > the web. I would really appreciate if this problem could be solved > "for good". In the past, it was always difficult that the *BSDs would > hide interfaces if I say that my program uses XOPEN/Unix. Python > uses a "POSIX+" approach: use POSIX interfaces where available; > use platform-specific ones elsewhere. > I'll be happy to test anything you want WRT OpenBSD. I have one here and I don't think it's going anywhere. > > I see. The macros _BSD_SOURCE didn't actually get defined. > Please try the revised patch below. > This looks to have fixed it. Build was succesful. Thanks! dnm From gagsl-py2 at yahoo.com.ar Sun Jul 15 15:08:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 15 Jul 2007 16:08:49 -0300 Subject: Circular import problem References: <1184294176.550267.119980@n60g2000hse.googlegroups.com> <1184343897.111992.107880@g4g2000hsf.googlegroups.com> <1184500194.909470.178430@w3g2000hsg.googlegroups.com> Message-ID: En Sun, 15 Jul 2007 08:49:54 -0300, Alex Popescu escribi?: >> > But, I still don't understand how python can access a function in a >> > file I have NOT included. In this case, to get things to work, I DO >> > NOT "import MMA.grooves" but later in the module I access a function >> > with "xx=MMA.grooves.somefunc()" and it finds the function, and works >> > just fine. It shouldn't work. >> >> That depends a bit on what is "MMA" and what is "grooves". >> MMA.grooves means "look for an attribute named grooves inside MMA". If >> MMA >> is a module, and MMA.grooves is a class/function defined inside the >> module, you don't need to import it before using it. > > I am a bit confused: I think the above should be: > > if MMA.grooves in a class/function defined inside the module MMA, you > don't need to import the > class/function before using it, but only import the module MMA. > > Am I wrong? You are right, but we were talking about a slightly different scenario. To make things clear: 1) import MMA xx=MMA.grooves.somefunc() 2) import MMA.grooves xx=MMA.grooves.somefunc() If MMA is a module, containing a class named gooves, those two ways are valid. If MMA is a package, and grooves is a module contained in the package, only the second one is valid (assuming the package has an empty __init__.py, or does not import grooves itself) The OP was asking why the second form worked fine for him for a while, but stopped working after reordering some imports. And the answer (according to "Greg") is: some other module imported MMA.grooves, and that put grooves into MMA namespace, available for everyone else. -- Gabriel Genellina From tdelaney at avaya.com Mon Jul 9 23:16:26 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 10 Jul 2007 11:16:26 +0800 Subject: Broken MUA interactions In-Reply-To: <87d4z1m8mv.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > If your MUA is not using the information, provided in every message > from the mailing list, to do what you want, don't ask mailing list > admmministrators to accomodate your broken MUA. There would be nothing wrong with an MUA for example, having a "reply" button where the user could choose if it defaulted to "reply to author", "reply to all", "reply to all except me" or "reply to list" depending on the presence of the right headers and number of recipients. I'd like such an MUA - I'd default it to replying to list when applicable. But such an MUA should also provide the option for doing any of those for each individual message as well. They could also have "reply to only people in the To: header", "reply to only people in the CC: header", etc if they wanted. I have a company-mandated use of Outlook, which does *not* give me the above options (it only has "reply" and "reply to all"). And I still prefer mailing lists to do the right thing. Tim Delaney From gluckj at gmail.com Sun Jul 1 02:36:55 2007 From: gluckj at gmail.com (gluckj at gmail.com) Date: Sat, 30 Jun 2007 23:36:55 -0700 Subject: shelve crashing under Win ME In-Reply-To: <1183257088.085647.280010@z28g2000prd.googlegroups.com> References: <1183193535.127098.299840@a26g2000pre.googlegroups.com> <200706301007.29992.inq1ltd@verizon.net> <1183257088.085647.280010@z28g2000prd.googlegroups.com> Message-ID: <1183271815.085382.251640@d30g2000prg.googlegroups.com> OK, here's my workaround for shelve -- it's primitive and obviously much slower (it saves the entire dictionary each time), and you have to manually save -- BUT: it works...even on the Win ME machine. And it's possibly more universally portable in the long run than shelve...Also, once you open the dictionary, it is just as fast (perhaps faster?) than shelve for reading the contents (just not for saving...) --Joel ================ #! /usr/local/bin/python """ myshelve.py -- a simpler (safer though slower) approach to shelve """ #Import Modules import os, cPickle def msopen(path): """ open file containing pickled dict & return dict; if no such file, create it & return empty dict """ if os.access(path, os.R_OK): f=open(path, "r") mydict=cPickle.load(f) f.close() return(mydict) else: f=open(path, "w") cPickle.dump({}, f) f.close() return({}) def mssave(mydict,path): """ pickle and save the dict to the file, overwriting previous contents """ f=open(path, "w") cPickle.dump(mydict, f) f.close() def mstest(): f1="_myshelvetest_.txt" print "Testing myshelve..." print "1) New file:",f1 if os.access(f1, os.F_OK): os.remove(f1) d1=msopen(f1) print "Contents of new file:",d1 d2=msopen(f1) print "Contents on re-read:",d2 print "2) Write/Read/Overwrite/Read..." d1={1:"hello",2:"there",3:"folks"} print "Test dict:",d1 mssave(d1,f1) d2=msopen(f1) print "Loaded:",d2 print "Equal?",d1==d2 d1={1:"goodbye",2:"now",3:"folks"} print "Test dict:",d1 mssave(d1,f1) d2=msopen(f1) print "Loaded:",d2 print "Equal?",d1==d2 print "** DONE **" os.remove(f1) if __name__=="__main__": mstest() From rshepard at nospam.appl-ecosys.com Thu Jul 5 18:03:59 2007 From: rshepard at nospam.appl-ecosys.com (rshepard at nospam.appl-ecosys.com) Date: 5 Jul 2007 22:03:59 GMT Subject: Embedded For Loop With No Data Message-ID: Haven't found an answer to my question in the books and other docs I have available, so I am asking here. I have three lists of data retrieved from database tables. I want to cycle through all three lists using nested FOR loops. What is the behavior if there are no data in the list used in the middle loop? Example: for a in types: for b in subtypes: for c in details: do some processing Not every item in the 'types' list will have an associated 'subtype'. Does the index ignore that loop and drop to the one nested beneath it? Rich From gabrielg_laburando at yahoo.com.ar Wed Jul 4 03:27:02 2007 From: gabrielg_laburando at yahoo.com.ar (Gabriel Genellina) Date: Wed, 4 Jul 2007 04:27:02 -0300 (ART) Subject: Unbound Local error --??? Message-ID: <789745.26038.qm@web32806.mail.mud.yahoo.com> (Please keep posting on the list - I don't read this account too often) At Friday 29/06/2007 22:03, you wrote: > But what i am asking in particular is, how python > interpretes when we initialize a variable with a > name same as a method name ? for ex: > > def f(): > > ... x = g() > ... g = 'sample' > It's the same thing: - First, the *compiler* determines (statically) whether a variable name is local or not. If you assign something to it, it IS local (unless you explicitely use the global keyword). This is done when the code is compiled, not when it is run. - In your example, you assign something to g, so the compiler knows that g is a local variable. - When the function is run, there is an attempt to reference a local variable g, but is still unassigned, so you get an UnboundLocalError. Python treats function names and variable names like the same thing. That is, all names are just that... names - pointing to objects. -- Gabriel Genellina Softlab SRL ______________________________________________ Todo sobre la Copa Am?rica. Mantenete actualizado con las ?ltimas noticias sobre esta competencia en Yahoo! Deportes. http://ar.sports.yahoo.com/futbol/copaamerica/index.html From sjmachin at lexicon.net Mon Jul 2 19:49:39 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 02 Jul 2007 16:49:39 -0700 Subject: Probably simple syntax error In-Reply-To: <1183417476.394762.285190@w5g2000hsg.googlegroups.com> References: <1183351228.878746.233430@o61g2000hsh.googlegroups.com> <1183352843.803263.82140@57g2000hsv.googlegroups.com> <1183417476.394762.285190@w5g2000hsg.googlegroups.com> Message-ID: <1183420179.055208.156880@i38g2000prf.googlegroups.com> On Jul 3, 9:04 am, Dustin MacDonald wrote: > And Cameron: Ah, yes. It does reduce the confusion. I do know that > square brackets are used for *creating* a dictionary (blah = ["A", > "B", "C"], That's a list, not a dictionary. > so I figured the same would apply to accessing it (which is > why for my list, which I created with parenthesis I assumed I accessed > with parenthesis). If you created it with parentheses, it's not a list, it's a tuple. Problem 10: Tuples are immutable. atuple[index_variable] = something and atuple.append(something) will fail. Print this, cut it out, and paste it inside your hat: """ alist = ['foo', 42, True, 123.456] assert alist[1] == 42 atuple = ('foo', 42, True, 123.456) assert atuple[1] == 42 adict = {'bar': 'foo', 1: 42, 'abool': True, 'afloat': 123.456} assert adict[1] == 42 """ and, in general: Abjure guesswork, read the documentation! From banaouas.medialog at wanadoo.fr Thu Jul 5 02:45:20 2007 From: banaouas.medialog at wanadoo.fr (m.banaouas) Date: Thu, 05 Jul 2007 08:45:20 +0200 Subject: windows cetificates In-Reply-To: <1183610011_40089@sp12lax.superfeed.net> References: <468b6509$0$27375$ba4acef3@news.orange.fr> <1183610011_40089@sp12lax.superfeed.net> Message-ID: <468c93a4$0$25921$ba4acef3@news.orange.fr> thank you I will take a look on capicom ... Roger Upole a ?crit : > m.banaouas wrote: >> hi, >> >> is there any way to decrypt an email (already read with poplib, so available on client side) with python using a window >> certificate (those we can see on ie/internet options/content/certificates) ? >> >> the purpose is to decrypt an email sent and crypted by the sender with both his own certificate and the recipient one. >> >> thanks for any help. > > If the messages use standard encoding, you should be able to use CAPICOM. > The interfaces are fairly simple to use through win32com.client. > The 'capicom.envelopeddata' object encrypts and decrypts using certificate keys. > > Roger > > > > > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==---- > http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups > ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- From dr.death.tm at gmail.com Tue Jul 3 09:44:34 2007 From: dr.death.tm at gmail.com (ddtm) Date: Tue, 03 Jul 2007 13:44:34 -0000 Subject: Python IRC bot using Twisted In-Reply-To: References: <1183456019.764920.6820@q75g2000hsh.googlegroups.com> Message-ID: <1183470274.113508.308370@n60g2000hse.googlegroups.com> On 3 , 16:01, Jean-Paul Calderone wrote: > On Tue, 03 Jul 2007 09:46:59 -0000, ddtm wrote: > >I'm using an example of IRC bot (_ttp://twistedmatrix.com/projects/ > >words/documentation/examples/ircLogBot.py) to create my own bot. But I > >have a problem. I'm trying to make my bot send messages periodically. > >But I can't find a way of adding Timer or something similar to my code > >so that it could work. Could somebody modify an example to make IRC > >bot send anything to chat every 20 seconds? > > >P.S. Timer should not lock the main program (I think it should work in > >other thread or so) > >P.P.S. Could somebody write a code of delay between messages too? In > >pseudocode it looks like this: > > sleep(20) > > sendMessage(channel,'lopata') > >This delay should be non-locking too. > >P.P.P.S. Sorry for my bad English (and for a noob question too) > > You can use reactor.callLater to schedule a one-time event to happen at > some future point: > > reactor.callLater(20, sendMessage, channel, 'lopata') > > There is also a utility class, twisted.internet.task.LoopingCall, which > you can use to schedule an event to occur repeatedly at some interval: > > call = LoopingCall(sendMessage, channel, 'lopata') > loopDeferred = call.start(20) > > You can read more about these APIs in the scheduling howto: > > http://twistedmatrix.com/projects/core/documentation/howto/time.html > > Or you can refer to the generated API documentation: > > http://twistedmatrix.com/documents/current/api/twisted.internet.inter...http://twistedmatrix.com/documents/current/api/twisted.internet.task.... > > Hope this helps, > > Jean-Paul Thank you very much! It's a very useful information. One more question: can I cancel the DelayedCall using its ID (it is returned from callLater(...)) from another function? In example bot there are two functions: def joined(self, channel): ... def privmsg(self, user, channel, msg): ... For example, I add callLater(...) to joined(...) function and I'd like to cancel this in privmsg(...) function. What should I do? From kirk at strauser.com Fri Jul 6 11:12:56 2007 From: kirk at strauser.com (Kirk Strauser) Date: Fri, 06 Jul 2007 10:12:56 -0500 Subject: Auto-parallelizing with decorators? Message-ID: I was thinking about how a lot of Lisp proponents claim that Lisp is inherently parallelizable because its functions don't have (or are not supposed to have) side effects, and therefore the compiler can easily tell which calls may be run in parallel instead of strictly serially. I'm not a Lisp expert so I can't say whether that's true or not, but it seems like an interesting idea for Python. Suppose that Python had a new decorator, say "@parallelizable". Functions so decorated would be eligible for multi-processed or multi-threaded execution by such native constructs as list comprehensions, or the map() function. Their logic could be something along the lines of: 1) Is every function in the "function expression" of map() or a list comprehension decorated with @parallelizable? If not, use the normal implementation. 2) Spawn an appropriate number of child threads and queue values to be processed. 3) As results return, either store them in the result list (for map()), or insert them into their place in the output queue to be consumed by users of a list comprehension. In #2, "appropriate" could default to something like 2 times the number of CPUs detected in the system (which could be found the first time it was needed so that programs that don't use this functionality don't pay for finding that information). I could imagine that it'd be useful to pass hints to the decorator to more explicitly size the thread pool, such as: @parallelizable(number=100) def lightweightfunction: """Launch as many parallel copies as you can""" @parallelizable(perproc=1) def heavierfunction: """Only run one copy per CPU""" @parallelizable(number=2) def bigslowfunction: """This benefits from parallel execution, but don't kill the system""" Would something like this have merit? I like the idea because it's completely optional; if you don't use it, you never have to deal with the side effects. However, if you take care to make your functions loosely coupled and not dependent on execution order, you could get a nice speedup every single time you give Python permission to schedule your repeated function calls. -- Kirk Strauser From jimxu at google.com Fri Jul 6 19:50:52 2007 From: jimxu at google.com (jimxu) Date: Fri, 6 Jul 2007 16:50:52 -0700 Subject: Repeating Thread Error In-Reply-To: <1183758016.776354.241620@g4g2000hsf.googlegroups.com> References: <1183758016.776354.241620@g4g2000hsf.googlegroups.com> Message-ID: hmm.. why use while True? After 5 secs, the function is going to run. so t = threading.Thread(5.0, func) t.start() should just work. Put it in a infinite loop will start the thread and then start a the stopped thread... forever. Jim On Jul 6, 2007, at 2:40 PM, Jonathan Shan wrote: > Hello, > > I am trying to call a function every 5 seconds. My understanding of > time.sleep() is during the sleep time everything "stops". However, in > my application, there are background processes that must be running > continuously during the five second interval. Thus, threading.Timer > seems like a good function. Here is the relevant code: > > # background processes > t = threading.Timer(5.0, function_name, [arguments]) > while True: > # Do background processes run inside while loop? > t.start() > > The above code generates an error: > AssertionError: thread already started > > Any hints on how to fix the error? Also, do background processes run > inside while loops? > > Thanks in advance, > Jonathan Shan > > -- > http://mail.python.org/mailman/listinfo/python-list From rschroev_nospam_ml at fastmail.fm Wed Jul 25 13:58:36 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Wed, 25 Jul 2007 17:58:36 GMT Subject: wxGlade: Who knows how to drive this application? In-Reply-To: References: Message-ID: Steve Holden schreef: > I've been trying to use wxGlade recently and I am finding it something > of a challenge. Is there any user who finds the user interface > satisfactory and the operation of the program predictable? I haven't used it much, but it always seems to be a pain to use the interface. I actually thought it was just me; I'm glad to see that at least one other person has problems with it too. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From evan at yelp.com Wed Jul 11 20:47:55 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 11 Jul 2007 17:47:55 -0700 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> <1184173446.779276.250530@k79g2000hse.googlegroups.com> <1184182757.797808.206480@d55g2000hsg.googlegroups.com> Message-ID: On 7/11/07, Gabriel Genellina wrote: > En Wed, 11 Jul 2007 16:39:17 -0300, Paul McGuire > escribi?: > > > As was > > pointed out earlier, left-associativity with exponentiation is of > > little value, since (2**3)**2 is the same as 2**(3*2) or 2**6=64. > > Just for curiosity: This helps to find the answer to the problem "Which is > the largest number that can be written with only 3 digits?" > Some people stop at 999, others try 99**9 and 9**99, and the winner is > 9**9**9, or: > > | 9 > | 9 > | 9 > > Sorry, couldn't resist. But you can append ! (i.e. factorial) indefinitely without adding any digits to make the number arbitrarily large ;-) -- Evan Klitzke From rrenaud at gmail.com Mon Jul 9 20:36:47 2007 From: rrenaud at gmail.com (rrenaud at gmail.com) Date: Tue, 10 Jul 2007 00:36:47 -0000 Subject: Purpose of delayload in cookielib.FileCookieJar? Message-ID: <1184027807.876169.44100@k79g2000hse.googlegroups.com> What is the reason for delayload=False in the FileCookieJar.__init__ function? It doesn't seem to be used in any of the code that ships with python2.4, and it seems to directly contradict the comment following it """ Cookies are NOT loaded from the named file until either the .load() or .revert() method is called. """ which sounds like exactly the opposite the delayload=False default. From horpner at yahoo.com Wed Jul 4 12:28:43 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 04 Jul 2007 16:28:43 GMT Subject: what is wrong with that r"\" References: <5f1ehiF3a62csU1@mid.uni-berlin.de> Message-ID: <%UPii.36166$G23.16677@newsreading01.news.tds.net> On 2007-07-04, Marc 'BlackJack' Rintsch wrote: > On Wed, 04 Jul 2007 11:21:14 +0000, Neil Cerutti wrote: > >> If the escaped quotes didn't function in raw strings, I'd be >> unable to construct (with a single notation) a regex that >> included both kinds of quotes at once. >> >> re.compile(r"'\"") > > Where's the problem!? :: > > re.compile(r''''"''') That incurs the problem that you can't end with a '. So you can't end with *something* either way. -- Neil Cerutti From nis at superlativ.dk Thu Jul 5 04:39:09 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Thu, 05 Jul 2007 10:39:09 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <468c18fc$0$26377$426a74cc@news.free.fr> References: <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <468c0827$0$22906$426a74cc@news.free.fr> <7x3b03lusa.fsf@ruckus.brouhaha.com> <468c18fc$0$26377$426a74cc@news.free.fr> Message-ID: <468cae3d$0$90268$14726298@news.sunsite.dk> Bruno Desthuilliers skrev: > Paul Rubin a ?crit : >> Bruno Desthuilliers writes: >> >>> Haskell - as other languages using type-inference like OCaml - are in >>> a different category. Yes, I know, don't say it, they are statically >>> typed - but it's mostly structural typing, not declarative >>> typing. Which makes them much more usable IMHO. >> >> >> Some users in fact recommend writing an explicit type signature for >> every Haskell function, which functions sort of like a unit test. > > Stop here. explicit type signature == declarative static typing != unit > test. Well, it quacks like a duck ... Nis From arkanes at gmail.com Fri Jul 27 08:46:41 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 27 Jul 2007 07:46:41 -0500 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? In-Reply-To: <0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de> References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> <0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de> Message-ID: <4866bea60707270546p4bb71313ta9057b493f4d0b18@mail.gmail.com> On 7/26/07, Stefan Scholl wrote: > Chris Mellon wrote: > > XML is not a string. It's a specific type of bytestream. If you want > > to work with XML, then generate well-formed XML in the correct > > encoding. There's no reason you should have an XML document (as > > opposed to values extracted from that document) in unicode objects at > > all. > > The affected method in xml.sax is called parseString() > The imprecision of the english language has caused greater problems than this. Since you've now had everything clarified for you, and the imprecision is resolved, I'm sure that this won't be a problem again. From skontos at overturepartners.com Wed Jul 18 13:58:57 2007 From: skontos at overturepartners.com (Sandy Kontos) Date: 18 Jul 2007 13:58:57 -0400 Subject: New Python opportunity in Boston Message-ID: <5274424.1184781537794.JavaMail.cfservice@webserver25> Hello, My name is Sandy Kontos and I have a Python/Jython role here in Boston for 3-6 months. Should you have any interest in the Boston area please give either myself and/or Mo Bitahi a call at 781 449 0600 Thank you Sandy Sandy Kontos Overture Partners, LLC 75 Second Avenue Suite 710 Needham, MA 02494 www.overturepartners.com skontos at overturepartners.com 781 449 0600 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dennis.varghese at wipro.com Fri Jul 20 11:47:38 2007 From: dennis.varghese at wipro.com (pycraze) Date: Fri, 20 Jul 2007 08:47:38 -0700 Subject: Python C Embedded ! Attribute Error Message-ID: <1184946458.306346.211950@i38g2000prf.googlegroups.com> Hi , I am using the below C code so that i can embed a Python Code and get input from a python function and use it in C code . Below is the C Code #include int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue; int i; if (argc < 3) { fprintf(stderr,"Usage: call pythonfile funcname [args]\n"); return 1; } Py_Initialize(); pName = PyString_FromString(argv[1]); /* Error checking of pName left out */ PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('/home/dennis/workplace/ aps098')"); PyRun_SimpleString("sys.path.append('/home/dennis/workplace/aps098/ lib')"); PyRun_SimpleString("import server, logger,config, ntlm_procs, config_affairs "); pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pFunc = PyObject_GetAttrString(pModule, argv[2]); /* pFunc is a new reference */ if (pFunc && PyCallable_Check(pFunc)) { pArgs = PyTuple_New(argc - 3); for (i = 0; i < argc - 3; ++i) { pValue = PyInt_FromLong(atoi(argv[i + 3])); if (!pValue) { Py_DECREF(pArgs); Py_DECREF(pModule); fprintf(stderr, "Cannot convert argument\n"); return 1; } /* pValue reference stolen here: */ PyTuple_SetItem(pArgs, i, pValue); } pValue = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pValue != NULL) { printf("Result of call: %ld\n", PyInt_AsLong(pValue)); Py_DECREF(pValue); } else { Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } } else { if (PyErr_Occurred()) PyErr_Print(); fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]); } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load \"%s\"\n", argv[1]); return 1; } Py_Finalize(); return 0; } The python code is a simple code def pr(var): print var I am getting error AttributeError: 'module' object has no attribute 'print' Cannot find function "print" I am a newbie to python . I need some to embed python in C . Anyone Pls help From info at egenix.com Mon Jul 2 09:38:22 2007 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Mon, 02 Jul 2007 15:38:22 +0200 Subject: Interest in a one-day business conference for Python, Zope and Plone companies ? Message-ID: <4688FFCE.6040009@egenix.com> Hello, eGenix is looking into organizing a one day conference specifically for companies doing business with Python, Zope and Plone. The conference will likely be held in or close to D?sseldorf, Germany, which is lively medium-sized city, with good airport connections world-wide and specifically to all major European cities, so it's easy getting there and ideal for a one day event. The focus of the conference is on networking, meeting people, exchanging experience and exploring ways of working together. We are aiming at having a small conference program with just a few talks. The main intent of the presentations should be to initiate discussions among the attendees. Since this will be a business-only event, we will likely get professional help from a conference organizer and also try to sign up with a hotel to do all the catering, conference room maintenance, etc. My questions to you: * Would there be interest in such a conference event ? * How many people from your company would likely attend ? * Would a weekday or weekend conference date be more attractive ? * Does the focus suit your needs ? We will be giving a short presentation of what we have in mind at EuroPython 2007 in Vilnius in the context of the Open Space sessions: http://wiki.python.org/moin/EuroPython2007OpenSpace If you're interested, please contact us. Thanks, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 02 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/ ________________________________________________________________________ 2007-07-09: EuroPython 2007, Vilnius, Lithuania 6 days to go :::: 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 paddy3118 at googlemail.com Wed Jul 25 13:47:33 2007 From: paddy3118 at googlemail.com (Paddy) Date: Wed, 25 Jul 2007 10:47:33 -0700 Subject: From D In-Reply-To: References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> Message-ID: <1185385653.269942.3570@19g2000hsx.googlegroups.com> On Jul 25, 1:47 am, "Gabriel Genellina" wrote: > En Tue, 24 Jul 2007 11:10:53 -0300, Stargaming > escribi?: > > > On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote: > > >> There are various things I like about the D language that I think Python > >> too may enjoy. Here are few bits (mostly syntactical ones): > > >> 1) (we have discussed part of this in the past) You can put underscores > >> inside number literals, like 1_000_000, the compiler doesn't enforce the > >> position of such underscores, so you can also put them like this: > >> 1_00_000. You can put them in literals of decimals, binary, hex, etc. I > > > Sounds like a good thing to be but the arbitrary positioning doesnt make > > any sense. Additionally, I'd suggest 10**n in such cases (eg. 10**6). > > Why not? Because in English major numbers are labeled in thousands? > (thousand, million, billion...) > In India, they're grouped by two after the first thousand; in China, > they're grouped each 4 digits (that is, there is a single word for "ten > thousands" = wan4 = , and the next required word is for 10**8 = yi4 = ) > > -- > Gabriel Genellina But then,what would _0 be, the number 0 or the name _0 analagous to a0 - Pad. From santi_anti at yahoo.com Fri Jul 13 12:18:00 2007 From: santi_anti at yahoo.com (78ncp) Date: Fri, 13 Jul 2007 09:18:00 -0700 (PDT) Subject: how to implementation latent semantic indexing in python.. Message-ID: <11582773.post@talk.nabble.com> hi... how to implementation algorithm latent semantic indexing in python programming...?? thank's for daniel who answered my question before.. -- View this message in context: http://www.nabble.com/how-to-implementation-latent-semantic-indexing-in-python..-tf4075439.html#a11582773 Sent from the Python - python-list mailing list archive at Nabble.com. From nwi at aol.com Mon Jul 16 05:21:29 2007 From: nwi at aol.com (Jordan Vivian) Date: Mon, 16 Jul 2007 11:21:29 +0200 Subject: Fwd: Message-ID: <469B3899.8030503@telecom.net.et> -------------- next part -------------- A non-text attachment was scrubbed... Name: Invoice.pdf Type: application/pdf Size: 14083 bytes Desc: not available URL: From AnonMail2005 at gmail.com Thu Jul 19 09:43:47 2007 From: AnonMail2005 at gmail.com (AnonMail2005 at gmail.com) Date: Thu, 19 Jul 2007 06:43:47 -0700 Subject: Embedding/Extending Python in/with C++: non-static members? In-Reply-To: <1184593533.995878.123010@k79g2000hse.googlegroups.com> References: <1184593533.995878.123010@k79g2000hse.googlegroups.com> Message-ID: <1184852627.480299.298470@x40g2000prg.googlegroups.com> On Jul 16, 9:45 am, dmoore wrote: > Hi Folks: > > I have a question about the use of static members in Python/C > extensions. Take the simple example from the "Extending and Embedding > the Python Interpreter" docs: > > A simple module method: > > static PyObject * > spam_system(PyObject *self, PyObject *args) > { > ... > > } > > listed in a method table: > > static PyMethodDef SpamMethods[] = { > ... > {"system", spam_system, METH_VARARGS, > "Execute a shell command."}, > ... > {NULL, NULL, 0, NULL} /* Sentinel */ > > }; > > that is registered with: > > PyMODINIT_FUNC > initspam(void) > { > (void) Py_InitModule("spam", SpamMethods); > > } > > I have an application that embed multiple interpreters. I want to be > able to register methods for each interpreter that access C++ state > data relevant to that particular interpreter. In other words I want to > be able to register non-static class members in a class like the > following: > > class PythonSpamModuleInstance > { > PythonSpamModuleInstance() > { > SpamMethods[0]={"system", spam_system, METH_VARARGS,"Execute > a shell command."}; > SpamMethods[1]={NULL, NULL, 0, NULL}; > PyObject *spammodule=Py_InitModule("spam", SpamMethods); // > Needs an INCREF call? > } > ~PythonSpamModuleInstance() > { > PyObject_Del("spam", SpamMethods); > } > PyObject *spam_system(PyObject *self, PyObject *args) > { > // accesses non-static data in this class > } > PyMethodDef SpamMethods[2]; > PyObject *spammodule; > // Other data specific to this instance of the module > > }; > > The idea is that each time my app launches an embedded Interpreter it > will create an accompanying instance of PythonSpamModuleInstance that > allows the Interpreter to call the registered non-static C++ member > function spam_system. Calls to that member function will also affect > state information. > > So the questions: will this work? In particular, will the use of non- > static member functions cause problems? Is there a better way of > creating extension modules for multiple embedded interpreters? If I am > forced to use static methods, how do i figure out which interpreter is > calling them? test posting. From steve at REMOVE.THIS.cybersource.com.au Wed Jul 25 21:54:56 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 26 Jul 2007 11:54:56 +1000 Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> Message-ID: On Wed, 25 Jul 2007 10:22:46 -0700, mensanator at aol.com wrote: > On Jul 24, 6:08 pm, Steven D'Aprano > wrote: >> On Tue, 24 Jul 2007 20:09:00 +0200, Bjoern Schliessmann wrote: >> > Stargaming wrote: >> >> On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote: >> >> >>> While in a syntax like: >> >>> for i in xrange(1_000_000): >> >>> my eyes help me group them at once. >> >> >> Sounds like a good thing to be but the arbitrary positioning >> >> doesnt make any sense. >> >> > Checking underscore positions would only add complexity. Why not >> > just ignore them, no matter where they are? >> >> Underscores in numerics are UGLY. Why not take a leaf out of implicit >> string concatenation and allow numeric literals to implicitly concatenate? >> >> Python already does: >> "hello-" "world" => "hello-world" >> >> Propose: >> 123 456 789 => 123456789 >> 123.456 789 => 123.456789 > > So, spaces will no longer be delimiters? Won't that cause > much wailing and gnashing of teeth? Did you miss the bit where Python ALREADY does this for strings? Yes, whitespace will still delimit tokens. No, it won't be a problem, because two int tokens can be "concatenated" to make a single int token, exactly as happens for strings. (I say "no problem", but of course I don't know how much _actual_ coding effort will be needed to Make This Work. It might be a little, it might be a lot.) Currently, 234 567 is a syntax error in Python, so there are no problems with backward compatibility or breaking code that relies on the meaning of whitespace between two ints. -- Steven From robert.kern at gmail.com Fri Jul 13 18:04:00 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 13 Jul 2007 17:04:00 -0500 Subject: Numpy array index handling In-Reply-To: <1184362652.982580.113910@m3g2000hsh.googlegroups.com> References: <1184352981.493615.18040@k79g2000hse.googlegroups.com> <1184359937.326180.107370@g4g2000hsf.googlegroups.com> <1184362652.982580.113910@m3g2000hsh.googlegroups.com> Message-ID: sturlamolden wrote: > Enthought and similar distros are in my experience "unclean". They > don't always work and they are difficult to update. I rather download > the binary installers (for Windows) and install the packages I need. Right, that's why we (I'm an Enthought employee) haven't been updating the Enthought Edition. We are moving to a less monolithic approach with Python eggs. -- 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 klove at tax.ok.gov Fri Jul 27 15:24:27 2007 From: klove at tax.ok.gov (Kenneth Love) Date: Fri, 27 Jul 2007 14:24:27 -0500 Subject: Comparing Dictionaries In-Reply-To: <87abtih7x0.fsf@benfinney.id.au> References: <87abtih7x0.fsf@benfinney.id.au> Message-ID: <6.1.0.6.2.20070727141116.02629d78@tax.ok.gov> At 09:55 PM 7/26/2007, Ben Finney wrote: >Kenneth Love writes: > > > In other words, I consider these two dictionaries to be equivalent: > > > > { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'mickey' } > > { 'mouse' : 'mickey', 'dog' : 'bone', 'cat' : 'fever' } > > > > while these two are not: > > > > { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'mickey' } > > { 'dog' : 'bone', 'cat' : 'fever', 'mouse' : 'michael' } > > > > Any suggestions on how to compare these via some assert statement? > >Dictionaries already know how to compare themselves to each other. > > >>> {'dog': 'bone', 'cat': 'fever', 'mouse': 'mickey'} == {'mouse': > 'mickey', 'dog': 'bone', 'cat': 'fever'} > True > >>> {'dog': 'bone', 'cat': 'fever', 'mouse': 'mickey'} == {'mouse': > 'michael', 'dog': 'bone', 'cat': 'fever'} > False After verifying this myself, I double checked my code. It turns out, the changes I made to get rid of the "import string" from the original recipe were the problem. Leaving the parenthesis off lower() and strip() in the following code causes all sorts of problems: config["%s$%s" % (name, key.lower())] = cp.get(sec, key).strip() That should teach me not to change working code at the same time I am writing unit tests. Even so, I realize it won't be the last time I do something so silly. Yes, I know about TDD's "write the test first", but I'm not comfortable with the philosophy of these new fangled unit tests yet. Thanks for the help! Sincerely, Kenneth Love -- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Kenneth Love | Oklahoma Tax Commission DP Programmer/Analyst | Information Technology (405) 522 - 5864 | http://www.tax.ok.gov/ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- From danmcleran at yahoo.com Mon Jul 16 17:11:47 2007 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: Mon, 16 Jul 2007 14:11:47 -0700 Subject: Break up list into groups Message-ID: <1184620307.340479.253430@z28g2000prd.googlegroups.com> All, I can't seem to find an answer to this question anywhere, but I'm still looking. My problem is I have a list of values like this: l = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, 13, 0xF0, 14, 0xF1, 15] A value with bit 0x80 set delineates the start of a new packet of information. What I want to do is to group the packets so that 1, 2, 3 go with the 1st packet tagged 0xF0, 4 ,5, 6 go with the 2nd packet tagged 0xF0, 7 & 8 go with the packet tagged 0xF1 and so on. The length of the data associated with each tag can vary. I've already written an algorithm to do this but I was wondering if some combination of itertools functions could do the job faster? Here's what I've done and the expected output of the algorithm: def splitIntoGroups(data): groups = [] local = [] for value in data: if 0x80 & value: if len(local) > 0: groups.append(local) local = [] local.append(value) else: local.append(value) if len(local) > 0: groups.append(local) return groups l = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, 13, 0xF0, 14, 0xF1, 15] print splitIntoGroups(l) Desired result: [[240, 1, 2, 3], [240, 4, 5, 6], [241, 7, 8], [242, 9, 10, 11, 12, 13], [240, 14], [241, 15]] Thanks, Dan McLeran From jjl at pobox.com Wed Jul 25 19:33:51 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 25 Jul 2007 23:33:51 GMT Subject: Singleton in Python Cookbook References: Message-ID: <873azct5wg.fsf@pobox.com> Alex Popescu writes: > Hi all! > > I was reading through Python Cookbook the Singleton recipe. At this moment > I am a bit puzzled as the example in the book is not working resulting in: > > TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of type Haven't looked at that recipe, but take a look at this related one: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531 John From attn.steven.kuo at gmail.com Wed Jul 25 13:16:31 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Wed, 25 Jul 2007 10:16:31 -0700 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <1185378418.100041.38560@w3g2000hsg.googlegroups.com> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> Message-ID: <1185383791.011764.251380@e16g2000pri.googlegroups.com> On Jul 25, 8:46 am, beginner wrote: > On Jul 25, 10:19 am, Stargaming wrote: > > > > > On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote: > > > Hi, > > > > I am wondering how do I 'flatten' a list or a tuple? For example, I'd > > > like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4]. > > > A recursive function, always yielding the first element of the list, > > could do the job. See the ASPN Python Cookbook for a few implementations.http://aspn.activestate.com/ASPN/search? > > query=flatten§ion=PYTHONCKBK&type=Subsection > > > > Another question is how do I pass a tuple or list of all the aurgements > > > of a function to the function. For example, I have all the arguments of > > > a function in a tuple a=(1,2,3). Then I want to pass each item in the > > > tuple to a function f so that I make a function call f(1,2,3). In perl > > > it is a given, but in python, I haven't figured out a way to do it. > > > (Maybe apply? but it is deprecated?) > > >>> def foo(a, b, c): print a, b, c > > ... > > >>> t = (1, 2, 3) > > >>> foo(*t) > > > 1 2 3 > > > Have a look at the official tutorial, 4.7.4http://www.python.org/doc/ > > current/tut/node6.html#SECTION006740000000000000000 > > > > Thanks, > > > cg > > > HTH, > > Stargaming > > Hi Stargaming, > > I know the * operator. However, a 'partial unpack' does not seem to > work. > > def g(): > return (1,2) > > def f(a,b,c): > return a+b+c > > f(*g(),10) will return an error. > > Do you know how to get that to work? You can use the "partial" method from functools: import functools sum_of_three = functools.partial(f, *g())(10) -- Hope this helps, Steven From mail at timgolden.me.uk Thu Jul 19 11:36:41 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 19 Jul 2007 16:36:41 +0100 Subject: odbc module for python In-Reply-To: References: <1184816453.519242.187940@g12g2000prg.googlegroups.com> Message-ID: <469F8509.70405@timgolden.me.uk> Steve Holden wrote: > Sean Davis wrote: >> What are the alternatives for accessing an ODBC source from python >> (linux 64-bit, python 2.5)? It looks like mxODBC is the only one >> available? >> > There is, I understand, a pyodbc module as well. Having never used it I > can't say how good it is. This post seems pertinent: http://www.devpicayune.com/entry/200707181242 TJG From deets at nospam.web.de Mon Jul 30 09:48:00 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 30 Jul 2007 15:48:00 +0200 Subject: Detecting __future__ features References: <1185800016.950517.43240@g4g2000hsf.googlegroups.com> Message-ID: <5h68ggF3idk61U1@mid.uni-berlin.de> Neil Cerutti wrote: > On 2007-07-30, Andr? wrote: >> On Jul 30, 9:39 am, Neil Cerutti wrote: >>> I don't understand the qualification, "at runtime," you're >>> making. What's wrong with just importing what you want and >>> using it? If it's already been enabled, no harm will come from >>> the import statement. >>> >> >> I'm not the OP, so perhaps I am missing his intent. However, I >> can see a good reason for asking this question. >> >> I seem to recall that the "from __future__ import" statement >> can only be done at the beginning of a script. What if you are >> designing a module meant to be imported, and used by other >> programs over which you have no control? You can't use "from >> __future__ import" in your module. So, you may have to find a >> way to figure out what's been done. (the example given with >> the division operator is a good one). > > Is "from __future__ import" really that lame? Well, if you consider it lame, how about you being a 7331 haX0r who tells us how python is going to handle this then: def foo(): yield 1 if random_condition(): from __future__ import generators def bar(): yield 2 The point is that from __future__ can massively alter the behavior of the parser - accepting keywords that otherwise won't be keywords, as in this example, and many more. Making the switch between different parser-implementations on the fly isn't technically impossible - but really, really, really complicated. But then, if it's lameness sucks so much, you might wanna take a stab at it? Diez From vasudevram at gmail.com Mon Jul 9 13:55:45 2007 From: vasudevram at gmail.com (vasudevram) Date: Mon, 09 Jul 2007 17:55:45 -0000 Subject: How to Machine A python script execute Machine B python script? In-Reply-To: References: <1183945503.875939.292420@57g2000hsv.googlegroups.com> <1183948545.893438.305600@g37g2000prf.googlegroups.com> Message-ID: <1184003745.073318.291160@e16g2000pri.googlegroups.com> On Jul 9, 1:30 pm, Nick Craig-Wood wrote: > half.ital... at gmail.com wrote: > > On Jul 8, 6:45 pm, johnny wrote: > > > Anyone know how I can make Machine A python script execute a python > > > script on Machine B ? > > > xmlrpc will work. > > Or pyro > > http://pyro.sourceforge.net/ > > Pyro is short for PYthon Remote Objects. It is an advanced and > powerful Distributed Object Technology system written entirely in > Python, that is designed to be very easy to use. Never worry about > writing network communication code again, when using Pyro you just > write your Python objects like you would normally. With only a few > lines of extra code, Pyro takes care of the network communication > between your objects once you split them over different machines on > the network. All the gory socket programming details are taken care > of, you just call a method on a remote object as if it were a local > object! > > -- > Nick Craig-Wood --http://www.craig-wood.com/nick >> xmlrpc will work. Right. Pretty easy to use. Go to the xml-rpc.com site to read about it. Python has it included in the standard library, so you don't need to get anything extra to use XML-RPC. And it works as advertised, more or less - I recently wrote some simple servers and clients using Python and XML-RPC. Or SOAP (Google for "Python SOAP"). But not sure if SOAP is actively supported for Python nowadays. Or ICE - see www.zeroc.com. Haven't tried it out yet, but appears interesting. But it seems ICE has more overhead to setup (your ICE code, I mean, not to install the software itself) than XML-RPC or Pyro. (It looks like a lighter version of CORBA - some of the key people who created it are ex-CORBA experts). Could possibly give better performance or have more features, though ... Also, XML-RPC, SOAP, and ICE are all interoperable with different languages - meaning your server and client can be in different languages; at least, XML-RPC and SOAP have support in many languages, while ICE has it for at least for C++, C#, Java, Python, Ruby, PHP, and Visual Basic (some of these have only support for clients, when I last checked). Vasudev Ram http://www.dancingbison.com http://jugad.livejournal.com http://sourceforge.net/projects/xtopdf From gagsl-py2 at yahoo.com.ar Tue Jul 31 13:18:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 31 Jul 2007 14:18:59 -0300 Subject: encode() question References: <1185900791.595830.21290@d55g2000hsg.googlegroups.com> Message-ID: En Tue, 31 Jul 2007 13:53:11 -0300, 7stud escribi?: > 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? Converting from unicode characters into a string of bytes is the "encode" operation: unicode.encode() -> str Converting from string of bytes to unicode characters is the "decode" operation: str.decode() -> unicode str.decode and unicode.encode should NOT exist, or at least issue a warning (IMHO). When you try to do str.encode, as the encode operation requires an unicode source, the string is first decoded using the default encoding - and fails. -- Gabriel Genellina From westymatt at gmail.com Thu Jul 26 11:55:47 2007 From: westymatt at gmail.com (matt westerburg) Date: Thu, 26 Jul 2007 11:55:47 -0400 Subject: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> <878x93ivqx.fsf@benfinney.id.au> Message-ID: <4b490f2f0707260855v4eb22b7ftebca647497cf54cc@mail.gmail.com> Maybe we should welcome zentara instead of try to recreate the perl experience. Your not a troll either. That is very inappropriate and rather rude. Welcome to Python enjoy! -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.rawlins at thinkbluemedia.co.uk Tue Jul 3 06:34:17 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Tue, 3 Jul 2007 11:34:17 +0100 Subject: DatePart From String In-Reply-To: References: <43232.8877890997$1183453330@news.gmane.org> Message-ID: <00f901c7bd5d$b59cd170$20d67450$@rawlins@thinkbluemedia.co.uk> Hello Dave, Thanks for getting back to me, I had been trying to use it like this: time.strptime('2007-01-01 00:00:00','%H:%M:%S') I was getting an error thrown at me: ValueError: time data did not match format: data=2007-01-01 00:00:00 fmt=%H:%M:%S I see how your solution works, but I'm hoping to trip is down a little bit as this has to be used in a conditional statement such as the one below: If time.strftime('%H:%M:%S') > time.strptime('2007-01-01 00:00:00','%H:%M:%S') Print 'Later In The Day' You see how that works? I'm basically trying to check if the current time is later that the one defined in my string. Are you able to give me a working example of how I might do this with my conditional? Thanks Dave, 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 Dave Sent: 03 July 2007 10:46 To: python-list at python.org Subject: Re: DatePart From String Robert Rawlins - Think Blue thinkbluemedia.co.uk> writes: > I?ve tried using the time.strptime() function without much success so > thought I?d come and ask your advice. > How exactly does it not work?? This works for me: from time import mktime, strptime from datetime import datetime datetime_string = '2007-02-01 00:00:00' datetime_object = datetime.fromtimestamp( mktime(strptime(datetime_string,'%Y-%m-%d %H:%M:%S'))) print datetime_object.year print datetime_object.month print datetime_object.day print datetime_object.hour print datetime_object.minute print datetime_object.second HTH, Dave -- http://mail.python.org/mailman/listinfo/python-list From mccredie at gmail.com Tue Jul 3 18:00:27 2007 From: mccredie at gmail.com (Matimus) Date: Tue, 03 Jul 2007 22:00:27 -0000 Subject: Restarting a Python Application In-Reply-To: <1183498045.092504.229250@m36g2000hse.googlegroups.com> References: <1183498045.092504.229250@m36g2000hse.googlegroups.com> Message-ID: <1183500027.659730.211790@d30g2000prg.googlegroups.com> On Jul 3, 2:27 pm, kyoso... at gmail.com wrote: > Hi, > > I packaged up an application I am developing into an executable. In > the application, it has user configurable options. I would like a way > to restart the application so that the new options the user chooses > can be applied. Firefox can restart itself. Does anyone know how to > accomplish this in Python? > > Here is what I tried: > > > > exePath = os.path.join(os.getcwd(), 'myprogram.exe') > subprocess.Popen(exePath) > sys.exit() > > > > This didn't work. It closed the program, but another instance did not > appear. > > Tips would be appreciated. > > Mike You could package your program into a function or class and just restart that. [code] # global flag for restart. do_restart = False def main(args=None): # program code # set do_restart and return to restart if __name__ == "__main__": retval = main() while do_restart: retval = main() sys.exit(retval) [/code] From shafik23 at gmail.com Thu Jul 12 14:12:28 2007 From: shafik23 at gmail.com (Shafik) Date: Thu, 12 Jul 2007 18:12:28 -0000 Subject: Tuple vs List: Whats the difference? In-Reply-To: <87y7hlkf12.fsf@benfinney.id.au> References: <1184177195.569916.184770@22g2000hsm.googlegroups.com> <87y7hlkf12.fsf@benfinney.id.au> Message-ID: <1184263948.795000.255230@k79g2000hse.googlegroups.com> Thanks to all of you, Im sure I'll pick your brains some more later down the line. --Shafik From __peter__ at web.de Tue Jul 24 02:54:05 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 24 Jul 2007 08:54:05 +0200 Subject: Extracting attributes from compiled python code or parse trees References: <1185225185.546338.84980@m3g2000hsh.googlegroups.com> Message-ID: Matteo wrote: > I am trying to get Python to extract attributes in full dotted form > from compiled expression. For instance, if I have the following: > > param = compile('a.x + a.y','','single') > > then I would like to retrieve the list consisting of ['a.x','a.y']. > I have tried using inspect to look at 'co_names', but when I do that, You can have a look at the compiler package. A very limited example: import compiler import compiler.ast import sys class Visitor: def __init__(self): self.names = [] def visitName(self, node): self.names.append(node.name) def visitGetattr(self, node): dotted = [] n = node while isinstance(n, compiler.ast.Getattr): dotted.append(n.attrname) n = n.expr try: dotted.append(n.name) except AttributeError: print >> sys.stderr, "ignoring", node else: self.names.append(".".join(reversed(dotted))) if __name__ == "__main__": expr = " ".join(sys.argv[1:]) visitor = Visitor() compiler.walk(compiler.parse(expr), visitor) print "\n".join(visitor.names) Output: $ python dotted_names.py "a + b * (c + sin(d.e) + x.y.z)" a b c sin d.e x.y.z $ python dotted_names.py "a + b * ((c + d).e + x.y.z)" ignoring Getattr(Add((Name('c'), Name('d'))), 'e') a b x.y.z Peter From bbxx789_05ss at yahoo.com Mon Jul 30 02:58:43 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 29 Jul 2007 23:58:43 -0700 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1185776482.804291.301200@g4g2000hsf.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> <1184458002.961657.267830@x35g2000prf.googlegroups.com> <1184466882.446791.127670@x35g2000prf.googlegroups.com> <1185658013.859359.47700@57g2000hsv.googlegroups.com> <1185703671.241103.124780@g12g2000prg.googlegroups.com> <1185727058.306635.203130@b79g2000hse.googlegroups.com> <1185751725.882668.269850@i13g2000prf.googlegroups.com> <1185776482.804291.301200@g4g2000hsf.googlegroups.com> Message-ID: <1185778723.073491.32680@l70g2000hse.googlegroups.com> > Yeah! So is my install good? Why didn't the Directory tags in > httpd.conf work? Ok. I got the mod_python manual's Testing directions to work as well. The Testing section actually says: ------- Add the following Apache directives, which can appear in ... the main server configuration file...and ****you will need to make sure the AllowOverride directive applicable to this directory has at least FileInfo specified. (The default is None, which will not work.)**** AddHandler mod_python .py PythonHandler mptest PythonDebug On (Substitute /some/directory above for something applicable to your system, usually your Apache ServerRoot) ---------------- I'm not sure how they expect people to interpret that to mean that you need to add(in my case): AllowOverride FileInfo to Apache's httpd.conf file. But, in any case when I add that, I get the message "Hello World!" to display when I type: http://localhost/modPythonPages/mptest.py in my browser's address bar. From nospam.themindstorm at gmail.com Fri Jul 27 19:24:14 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Fri, 27 Jul 2007 23:24:14 +0000 (UTC) Subject: problem with change to exceptions References: Message-ID: Neal Becker wrote in news:f8dspe$fm2$1 at sea.gmane.org: > import exceptions > > class nothing (exceptions.Exception): > def __init__ (self, args=None): > self.args = args > > if __name__ == "__main__": > raise nothing > > Traceback (most recent call last): > File "", line 1, in > File "/usr/tmp/python-3143hDH", line 5, in __init__ > self.args = args > TypeError: 'NoneType' object is not iterable > > I'll have to say, I don't understand this error. > You can pass to the exception: a) a string (it will become the message) b) a tuple of values (can it be a list also?) In your case there is no message, no values so args is NoneType. bests, ./alex -- .w( the_mindstorm )p. From steve at REMOVE.THIS.cybersource.com.au Wed Jul 25 21:06:37 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 26 Jul 2007 11:06:37 +1000 Subject: classmethod & staticmethod References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> <46a5b2ad$0$18903$426a74cc@news.free.fr> Message-ID: On Wed, 25 Jul 2007 00:22:18 +0000, Alex Popescu wrote: > "Steven D'Aprano" wrote in > news:pan.2007.07.24.23.21.20.988798 at REMOVE.THIS.cybersource.com.au: > >> On Tue, 24 Jul 2007 21:35:58 +0000, Alex Popescu wrote: >> >>> Neil Cerutti wrote in >>> news:slrnfaccgl.1gk.horpner at FIAD06.norwich.edu: >>> >>>> On 2007-07-24, Alex Popescu wrote: >>>>> Bruno Desthuilliers >>>>> wrote in >>>>> news:46a5b2ad$0$18903$426a74cc at news.free.fr: >>>>> >>>> >>>> [snip...] >>>> >> >> Use self.class_list when you want to use inheritance. >> > > As a matter of style, how do you figure out that class_list is a class > attribute and not an instance attribute? (I don't remember seeing anything > in the PEP describing the coding style). The whole point of inheritance is that you don't care where the attribute is (the instance, the class, a parent class...) just that it exists. -- Steven. From attn.steven.kuo at gmail.com Mon Jul 2 21:27:50 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Mon, 02 Jul 2007 18:27:50 -0700 Subject: Programming Idiomatic Code In-Reply-To: References: Message-ID: <1183426070.921098.277130@i38g2000prf.googlegroups.com> On Jul 2, 5:22 pm, "Nathan Harmston" wrote: > Hi, > > I m sorry but I m bored at work (and no ones looking so I can write > some Python) and following a job advertisement post,I decided to write > the code to do its for the one entitled Ninjas or something like that. > I was wondering what could be done to my following code to make it > more idiomatic...or whether it was idiomatic and to be honest what > idiomatic really means. All comments greatly appreciated and welcomed. > > Thanks in advance > > Nathan > > import urllib2,sys > from elementtree.ElementTree import parse > > base_url = "http://api.etsy.com/feeds/xml_user_details.php?id=" > > def read_id_file(filename): > """ reads a file and generates a list of ids from it""" > ids = [ ] > try: > id_file = open(filename, "r") > for l in id_file: > ids.append( l.strip("\n") ) > id_file.close() > except e: > print e > os._exit(99) > return ids > The expression in the except clause should evaluate to an object that "matches" the exception. For example, import sys try: idfile = open(filename, "r") except IOError, e print >> sys.stderr, str(e) # or look into the warnings module # etc. -- Hope this helps, Steven From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 17 03:29:16 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 17 Jul 2007 09:29:16 +0200 Subject: How to organize control access to source code ? In-Reply-To: <1184618776.798929.98960@57g2000hsv.googlegroups.com> References: <1184618776.798929.98960@57g2000hsv.googlegroups.com> Message-ID: <469c6fc6$0$27173$426a34cc@news.free.fr> Succelus at gmail.com a ?crit : > Hello, > How can we organize development team with code source control policy, > that limit access to some portion of code ? The question may be of interest, but I'm afraid I don't understand how it relates to Python ??? From stefan.behnel-n05pAM at web.de Fri Jul 27 02:39:27 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 27 Jul 2007 08:39:27 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? In-Reply-To: <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> Message-ID: <46A9931F.3020100@web.de> Stefan Scholl wrote: > Stefan Behnel wrote: >> The XML is *not* well-formed if you pass Python unicode instead of a byte >> encoded string. Read the XML spec. > > Pointers, please. There you have it: http://www.w3.org/TR/xml/#charencoding """ In the absence of information provided by an external transport protocol (e.g. HTTP or MIME), it is a *fatal error* for an entity including an encoding declaration to be presented to the XML processor in an encoding other than that named in the declaration, or for an entity which begins with neither a Byte Order Mark nor an encoding declaration to use an encoding other than UTF-8. """ """ Entities encoded in UTF-16 MUST and entities encoded in UTF-8 MAY begin with the Byte Order Mark ... """ Python does not use BOMs internally (although that again may be platform specific). You might argue that there is some kind of "external transportation protocol" as it is a Python Unicode string (I used that excuse when I implemented Unicode parsing support in lxml), but Python's Unicode objects are strictly a character stream, not a byte stream. XML is only defined for streams of bytes. Also, there is no requirement for an XML processor to be able to parse anything but UTF-8 and UTF-16. Especially if the encoding is *undefined* and *platform-specific*, as that of a Python Unicode string. Anything else I can help you understanding? Stefan From dmacdonald95 at gmail.com Mon Jul 2 00:40:28 2007 From: dmacdonald95 at gmail.com (Dustin MacDonald) Date: Sun, 01 Jul 2007 21:40:28 -0700 Subject: Probably simple syntax error Message-ID: <1183351228.878746.233430@o61g2000hsh.googlegroups.com> Hi everyone. This is my first time posting to this newsgroup, and although I maintain my netiquette I might've missed something specific to the newsgroup, so hopefully you can avoid flaming me if I have :) I apologize for the length of this post but I figure the more information the better. My problem is that I'm getting a syntax error in some Python code that looks quite simple. The original code was in Object Pascal as I'm a recent Delphi-turned-Python programmer. I took the code (which is only about 130 lines in OP) and 'translated' it the best I could into Python (ended up being one line shy of 80 when I was done). I can't see any problems with the code but it's coming up with a bunch of errors, which I'm guessing are probably my assuming something is the same in Python as it is in Pascal, and being wrong. Anyway, here's the code I'm having trouble with (the same error comes up several times but this is the first part of the code it shows up in): [code] randomizing_counter = 0 # Put the loop counter for the randomizing to zero. until_val = 36 # Set the "until val" to 36. We'll compare them to make sure we're not at the end of our wordlist_both. while randomizing_counter < until_val: big_randomized_int = RandRange(0,100) # Make a random value and store it. small_randomized_int = big_randomized_int / 100 # Divide that random value and store it in a different variable. small_randomized_int = Round(small_randomized_int, 2) # Round that value to 2 decimal places **weights_array(randomizing_counter) = small_randomized_int # Assign the first randomized value to our first word to be weighted. randomizing_counter = randomizing_counter + 1 # Up the counter and repeat. [/code] The starred line is the one getting the error message: "SyntaxError: can't assign to function call" Now, I do understand what this means. I'm trying to assign to a function instead of the value that the function should create. But since when is weights_array or small_randomizing_int a function? Both are being declared in the code on their first usage. This one has got me stumped, maybe you guys can help me out with it? Thanks, ~Dustin From sjmachin at lexicon.net Thu Jul 12 20:49:56 2007 From: sjmachin at lexicon.net (John Machin) Date: Thu, 12 Jul 2007 17:49:56 -0700 Subject: Fastest way to convert a byte of integer into a list In-Reply-To: <7xr6ndtae7.fsf@ruckus.brouhaha.com> References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> <1184284461.506663.75500@g12g2000prg.googlegroups.com> <1184284861.695430.99300@e9g2000prf.googlegroups.com> <7xr6ndtae7.fsf@ruckus.brouhaha.com> Message-ID: <1184287796.252097.46660@x35g2000prf.googlegroups.com> On Jul 13, 10:28 am, Paul Rubin wrote: > Godzilla writes: > > > num = 255 > > > numlist = [num >> i & 1 for i in range(8)] > > > Thanks matimus! I will look into it... > > numlist = lookup_table[num] > > where lookup_table is a precomputed list of lists. Ummm ... didn't the OP say he had 32-bit numbers??? From nospam.themindstorm at gmail.com Sat Jul 21 10:51:32 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Sat, 21 Jul 2007 14:51:32 +0000 (UTC) Subject: code packaging References: <7xfy3jpem8.fsf_-_@ruckus.brouhaha.com> <00df01c7cb38$49f83980$030ba8c0@MOUSE> Message-ID: "Ryan Ginstrom" wrote in news:00df01c7cb38$49f83980$030ba8c0 at MOUSE: >> On Behalf Of Paul Rubin >> I'm wondering how other projects go about this. > > I develop an automated build system from the very beginning. Running > the build script: > * Creates the API documentation (epydoc) > * Creates the help files (extracting some information from the source) > * Builds a windows executable (py2exe) > * Builds an installer (Inno Setup) > * Runs the installer (AutoIt) > * Runs a smoke test on the installed application (AutoIt) > > The program must at least install and pass the smoke tests at any > given point in development. > > Another script uploads the installer to my server, and sends an email > to the testers stating that a new version is ready, with a list of > additions/improvements. > > Regards, > Ryan Ginstrom > What "build" tools are available in Python? Any initial hints are highly appreciated. bests, ./alex -- .w( the_mindstorm )p. From rschroev_nospam_ml at fastmail.fm Mon Jul 23 05:15:34 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 23 Jul 2007 09:15:34 GMT Subject: decorators tutorials In-Reply-To: <1185178383.499234.299850@z24g2000prh.googlegroups.com> References: <1185178383.499234.299850@z24g2000prh.googlegroups.com> Message-ID: james_027 schreef: > Hi, > > I am learning python by learning django, and I stumble upon decorator > which is very cool, any beginners resources for python decorators, > although I can google it, I just want to get a good tutorial for this > topic. I like the short explanation on Kent's Korner: http://personalpages.tds.net/~kent37/kk/00001.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 ptmcg at austin.rr.com Mon Jul 9 12:59:40 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 09 Jul 2007 09:59:40 -0700 Subject: A clean way to program an interface In-Reply-To: <5feuvvF3bcgoiU1@mid.uni-berlin.de> References: <1183957402.819499.227350@o11g2000prd.googlegroups.com> <5feidnF3au460U1@mid.uni-berlin.de> <1183989399.366239.250850@g4g2000hsf.googlegroups.com> <5feuvvF3bcgoiU1@mid.uni-berlin.de> Message-ID: <1184000380.457434.316970@g4g2000hsf.googlegroups.com> I believe the OP is talking about "interface" as in "hardware interface", using some form of serial communication. His example does not use pyserial, but it does refer to a "UnidenConnection" class, with parameters such as bitrate, port, etc. for what looks like serial communication. Some general comments: 1. Much of the OP's use of sys._getframe().f_code.co_name coincides with his naming of certain methods with the same name as the command to be sent down the serial line. "STS", "EPG", "PRG", "SIN", etc. are all 3-character command codes that get sent down the wire, along with the appropriate values for the particular command. While many of these routines have *some* code in common, only a few have their entire method body duplicated with one or more other methods. Refactoring a couple of these into code closures, you can get: @staticmethod def makeStatusCheckCommandFunction(cmd): def fn(self): return ( self.uniden.write(cmd)[0]=="OK" ) return fn PRG = makeStatusCheckCommandFunction("PRG") EPG = makeStatusCheckCommandFunction("EPG") @staticmethod def makeCmdFunction(cmd,attrname): def fn(self): setattr(self, attrname, int(self.PRGWrite(cmd)[0])) return getattr(self,attrname) return fn SCT = makeCmdFunction("SCT","systems") SIH = makeCmdFunction("SIH","sih") SIT = makeCmdFunction("SIT","sit") Now there is no sys._getframe().f_code.co_name legerdemain going on, the command strings are just passed along as the argument cmd, and the functions themselves are named the same for some level of self- documentation and/or convenience. For the remaining methods, I declare a local variable named cmd and assign to it the write mnemonic. Yes, I know it violates DRY ("Don't Repeat Yourself"), but it avoids the getframe() stuff and again, is at least a snippet of self-documentation. 2. This code for reading and unpacking all the non-blank values feels ugly: cmd = "SIF" if args is None: p=self.PRGWrite("%s,%s" % (cmd,idx)) t={} t["site_type"],t["name"],t["quick_key"],t["hld"],t["lout"],\ t["mod"],t["att"],t["cch"],t["apco"],t["threshold"],\ t["rev_index"],t["fwd_index"],t["sys_index"],t["chn_head"], \ t["chn_tail"],t["seq_no"],t["start_key"],t["latitude"],\ t["longitude"],t["range"],t["gps_enable"],t["rsv"]=p delitems=[] for item in t: if t[item]=="": delitems.append(item) for x in delitems: del t[x] How about this instead?: cmd = "SIF" if args is None: p=self.PRGWrite("%s,%s" % (cmd,idx)) names = "site_type name quick_key hld lout mod att cch "\ "apco threshold rev_index fwd_index sys_index "\ "chn_head chn_tail seq_no start_key latitude " \ "longitude range gps_enable rsv".split() t = dict( k,v for k,v in zip(names,p) if v != "" ) HTH, -- Paul From gagsl-py2 at yahoo.com.ar Mon Jul 16 21:41:56 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jul 2007 22:41:56 -0300 Subject: how to find available classes in a file ? References: <2e302$469bf38f$d443bb3a$30036@news.speedlinq.nl> <1184627599.597658.267380@g4g2000hsf.googlegroups.com> Message-ID: En Mon, 16 Jul 2007 20:13:19 -0300, Alex Popescu escribi?: > On Jul 17, 1:44 am, Stef Mientki > wrote: >> I want to have a (dynamically) list of all classes defined in a py-file. >> Is there a way of getting this list, without manually parsing the file ? > > I have written something that does something like this, but I am not > sure it is the pythonic way. > Bascially I am loading the module and then using dir() on the module > object I am looking for > attribute of the type classobj (for old style classes) and type type > (for new style classes). There is also the pyclbr standard module that does not load the module (just reparses enough of it to get the info needed). So a broken import, or any other initialization error, won't hurt. > I also heard of the inspect module, but I haven't checked it yet. inspect.getmembers(the_module, inspect.isclass) would do. But this requires the module to be importable. -- Gabriel Genellina From klove at tax.ok.gov Mon Jul 30 15:06:29 2007 From: klove at tax.ok.gov (Kenneth Love) Date: Mon, 30 Jul 2007 14:06:29 -0500 Subject: Fwd: Re: Comparing Dictionaries Message-ID: <6.1.0.6.2.20070730132242.02885c88@tax.ok.gov> >From: "Steven D'Aprano" >Newsgroups: comp.lang.python >Subject: Re: Comparing Dictionaries >Date: Sat, 28 Jul 2007 10:21:14 +1000 >To: python-list at python.org > >On Fri, 27 Jul 2007 14:11:02 -0500, Kenneth Love wrote: > > > The published recipe (based on ConfigParser) did not handle my INI > > files. I have periods in both the section names and the key names. > > The INI files contents were developed according to an internally > > defined process that other non-Python programs rely on. The published > > recipe *did not work* with this scenario. > >I think you have made a mistake. ConfigParser as published certainly DOES >accept periods in section and option names. It just *works*. The recipe I'm using is based upon ConfigParser and creates a dictionary that is based on the contents of the INI file. The dictionary's key is based on the section name and the key name from the INI file. The two are concatenated with a separator. In the original recipe, the separator is a period. To use your example (deleted as an attempt at brevity), the dictionary would be: { "SECTION.FRED.option.wilma" : "45" } As originally written, the section name is now "SECTION" when you write the INI file back out. The key is "FRED.option.wilma". Here is the original recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/65334 My version replaces the period with a dollar sign giving: { "SECTION.FRED$option.wilma" : "45" } I also removed the "import string" and put both the load() and save() functions in a file with proper comments and the Python equivalent of Javadoc comments. >Even if the existing ConfigParser doesn't do what you want, the right way >to fix the problem is not to recreate the entire module from scratch, but >to subclass it: >[snip] In no way did I rewrite ConfigParser. I have a real job with time pressures and I'm not so arrogant as to think I could whip something up in an hour that would be anywhere close to correct. I see that I wasn't as clear as I thought I was in my original post as you are second person to think I was developing my own INI solution. All I wanted to know was "How do I compare two dictionaries to see if they are equal?". It turns out that this functionality is built-in and it is my own stupid fault that my unit test was failing (modifying working code and writing a unit test at the same time is a recipe for failure). Oh well. Next time I'll spend two hours trying to figure it out instead of one before I post. :-\ >-- >Steven. > >-- >http://mail.python.org/mailman/listinfo/python-list -- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Kenneth Love | Oklahoma Tax Commission DP Programmer/Analyst | Information Technology (405) 522 - 5864 | http://www.tax.ok.gov/ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- From bignose+hates-spam at benfinney.id.au Mon Jul 23 09:48:31 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 23 Jul 2007 23:48:31 +1000 Subject: decorators tutorials References: <1185178383.499234.299850@z24g2000prh.googlegroups.com> <1185180112.321457.73170@n2g2000hse.googlegroups.com> <1185183257.471106.318070@x35g2000prf.googlegroups.com> Message-ID: <877iorkz80.fsf@benfinney.id.au> james_027 writes: > Hi all, (Please don't top-post your reply. Instead, remove from the quoted material all the parts that are irrelevant to your reply, and post underneath what you're responding to, in normal chronological order like any other discussion.) > I am having difficulty understanding decorator. The definition was > clear for me, but the syntax is not so clear to me. > > will decorators will always have to be in this way > > def check_login(func): > def _check_login(*args): > print "I am decorator" > return func(*args) > return _check_login > > @check_login > def method2(input): > print "I am method TWO. Input %s" % input That looks okay. What is unclear? -- \ "I went to court for a parking ticket; I pleaded insanity. I | `\ said 'Your Honour, who in their right mind parks in the passing | _o__) lane?'" -- Steven Wright | Ben Finney From robert.rawlins at thinkbluemedia.co.uk Wed Jul 18 07:58:51 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 18 Jul 2007 12:58:51 +0100 Subject: Copy List Message-ID: <02e901c7c933$02184ad0$0648e070$@rawlins@thinkbluemedia.co.uk> Hello Guys, What's the best way to create a copy of a list? I've seen several method and I'm not sure what to use. This will be in a class and one method creates a list which I then want to move to the self scope, like so: __Init__(self): Self.myList = [] regenerateList(self): newList = [] for somthing in somthing: newList.append('SomeStuff') self.Mylist = newList.copy() See, The iteration and rebuilding of the list could be quite slow, during which time the application could be reading from the self.mylist variable so i think simply doing this: regenerateList(self): self.myList = [] for somthing in somthing: self.myList.append('SomeStuff') Might cause a few inconsistencies in the list if it's being read from whilst I'm appending too it, so I'm guessing that the top example is the best method, I'm just looking for the best way to copy() that list into the self scope, should i be using copy(), deepcopy() or simply self.mylist = newlist? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From zyzhu2000 at gmail.com Tue Jul 31 21:33:49 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 01 Aug 2007 01:33:49 -0000 Subject: A way to re-organize a list In-Reply-To: <1184857535.033057.49150@m3g2000hsh.googlegroups.com> References: <1184857535.033057.49150@m3g2000hsh.googlegroups.com> Message-ID: <1185932029.235957.226720@e9g2000prf.googlegroups.com> 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). """Put a sorted hirerchical structure into nested groups""" def group_items(source_list, f_list, target=[]): """Group_items: Group a list based on the grouping functions. source_list is a list or iterator that produces a stream of source records. f_list is a list of functions. Each function takes the form f(a,b), where a and b are two records. If the two records should be in the same group, it returns True, otherwise it returns False. If target is not provided, a new list will be created. Otherwise, the records are appended to the provided list. """ last_item=None for new_item in source_list: level=len(f_list) t=target for fn in f_list: if t==[] or last_item==None or not fn(last_item, new_item): ng=new_item for i in range(level): ng=[ng] t.append(ng) break else: t=t[-1] level -= 1 else: t.append(new_item) last_item=new_item return target if __name__=="__main__": import pprint def f(a,b): return a[0]==b[0] def g(a,b): return a[1]==b[1] mydata=[[1,2,3,4],[1,2,4,5],[1,2,"A","B"],[2,2,"A","C"]] t=group_items(mydata, [f,g]) pprint.pprint(t) From manasd at gmail.com Mon Jul 16 09:08:13 2007 From: manasd at gmail.com (MD) Date: Mon, 16 Jul 2007 06:08:13 -0700 Subject: Accessing Python variables in an extension module In-Reply-To: <1i1b7zw.64m7g071sk32N%aleax@mac.com> References: <1184553584.757696.92630@g4g2000hsf.googlegroups.com> <1i1b7zw.64m7g071sk32N%aleax@mac.com> Message-ID: <1184591293.938223.105800@o61g2000hsh.googlegroups.com> Hi Alex, Thanks for your reply. It was exactly what I was looking for. Two additional questions 1) Is there anyway to find out which modules a variable belongs to when I have only its name (and its not qualified with the complete name like module.varname) 2) Is there anyway to find the type of the object in C using something like a switch statement? I was looking for something like this switch type(object) { STRING: "This is a string object"; break; INTEGER: "This is an integer object"; break; BOOLEAN: "This is a boolean object"; ......... ......... } I don't want to run all the C Py***_Check functions on the object. Something like the switch statement above will lead to nice and clean code. Thanks again for your reply. Regards, -Manas On Jul 15, 11:02 pm, al... at mac.com (Alex Martelli) wrote: > MD wrote: > > Hi, > > > I would like to access "variables" defined in my Python program in > > a C module extension for Python. Is this possible? I looked at the > > Python C API reference but didn't find anything there that could help > > me. > > If they're global variables of a certain module XYZ, your C code may > "import" XZY (or look it up in the C API equivalent of the sys.modules > dict) and get those variables as attributes of object XYZ. Is that what > you mean by ``variables defined in your Python program''...? > > Alex From chilispecially0 at yahoo.com Tue Jul 17 17:24:54 2007 From: chilispecially0 at yahoo.com (Billy Bean) Date: Tue, 17 Jul 2007 14:24:54 -0700 Subject: * * * New eBooks Store * * * Message-ID: <1184707494.019311.146830@g12g2000prg.googlegroups.com> Multiple categories including literature, business, home & garden, computers & internet, and more! Learn how to make money at home, start your own business, try new recipes, etc. Complete resell rights included! http://www.grandgold.net From iferca at gmail.com Mon Jul 23 23:13:46 2007 From: iferca at gmail.com (=?ISO-8859-1?Q?Israel_Fern=E1ndez_Cabrera?=) Date: Mon, 23 Jul 2007 22:13:46 -0500 Subject: Re-running unittest In-Reply-To: References: Message-ID: Hi Gabriel > Perhaps the best option is to run the tests in another process. Use any of > the available IPC mechanisms to gather the test results. This has the > added advantage of isolating the tested code from your GUI testing > framework; all requested resources are released to the OS; the tests run > in a predictable environment; etc. This could be a solution it will complicate the GUI design, for example the current test number to implement a progress bar or something like that, but I think a well designed IPC may help again. Thks again for the tips, regards -- ____________________ Israel Fdez. Cabrera iferca at gmail.com Linux registered user No.: 270292 [http://counter.li.org] . 0 . . . 0 0 0 0 From percivall at gmail.com Thu Jul 12 07:43:56 2007 From: percivall at gmail.com (Simon Percivall) Date: Thu, 12 Jul 2007 04:43:56 -0700 Subject: pytz giving incorrect offset and timezone In-Reply-To: <1184233668.072963.264020@d55g2000hsg.googlegroups.com> References: <1184233668.072963.264020@d55g2000hsg.googlegroups.com> Message-ID: <1184240636.179512.54590@o61g2000hsh.googlegroups.com> On Jul 12, 11:47 am, Sanjay wrote: > Hi All, > > Using pytz, I am facing a problem with Asia/Calcutta, described below. > > Asia/Calcutta is actually IST, which is GMT + 5:30. But while using > pytz, it was recognized as HMT (GMT + 5:53). While I digged into the > oslan database, I see the following: > > # Zone NAME GMTOFF RULES FORMAT [UNTIL] > Zone Asia/Calcutta 5:53:28 - LMT 1880 # Kolkata > 5:53:20 - HMT 1941 Oct # Howrah Mean Time? > 6:30 - BURT 1942 May 15 # Burma Time > 5:30 - IST 1942 Sep > 5:30 1:00 IST 1945 Oct 15 > 5:30 - IST > > Searching in this group, I saw a similar problem posted athttp://groups.google.co.in/group/comp.lang.python/browse_thread/threa... > without any solutions. > > I mailed to Stuart and also posted it at the launchpad of pytz, but > did not get any response. > > Unable to know how to proceed further. Any suggestion will be of vital > help. > > thanks > Sanjay I don't use pytz myself that often so I can't be sure, but I don't think it's a bug in pytz. The problem seems to be that the timezone has changed for the location. Now, without a date as reference, pytz can't know what timezone to use when constructing the tzinfo; you might want a date from the 1800's. When you're constructing the datetime with the tzinfo argument, you're saying: use this timezone as the local timezone. datetime_new (the constructor in C) never calls the tzinfo to verify that the timezone is still valid, it just uses it. On the other hand: When you construct a datetime with datetime.now() and pass a timezone, datetime_now (again, in C) calls the method fromutz() on the tzinfo object. Now the pytz tzinfo object has a reference by which to choose the current timezone for the location, and that's why it's correct when you use datetime.now() but not for a manual construction. A "workaround" (or maybe the proper way to do it) is to construct the datetime without a tzinfo set, and then use the localize() method on the tzinfo object, this will give you the correct result. >>> tz = pytz.timezone("Asia/Calcutta") >>> mydate = datetime.datetime(2007, 2, 18, 15, 35) >>> print tz.localize(mydate) 2007-02-18 15:35:00+05:30 From horpner at yahoo.com Fri Jul 6 08:36:48 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 06 Jul 2007 12:36:48 GMT Subject: Where is the syntax for the dict() constructor ?! References: <468D1D9D.6060002@gmail.com> <468D3445.2060408@gmail.com> <1183675552.466967.136360@i13g2000prf.googlegroups.com> Message-ID: On 2007-07-06, Neil Cerutti wrote: > On 2007-07-05, John Machin wrote: >> On Jul 6, 5:31 am, Neil Cerutti wrote: >>> >>> Mostly you can use the default 'excel' dialect and be quite >>> happy, since Excel is the main reason anybody still cares about >>> this unecessarily hard to parse (it requires more than one >>> character of lookahead for no reason except bad design) data >>> format. >> >> One cares about this format because people create data files of >> millions of rows (far exceeding the capacity of Excel (pre-2007)) in >> many imaginative xSV dialects, some of which are not handled by the >> Python csv module. >> >> I don't know what you mean by "requires more than one >> character of lookahead" > > It's because of the silly way that quotes are quoted in quoted > fields. > > "a,""b",c > > But I'm not a parsing expert by any means. Moreover, the most common version of csv uses both escape and shift codes, when only escape codes were really needed, and then compounds this stupidity by using the same character for escaping and shifting. -- Neil Cerutti From hniksic at xemacs.org Thu Jul 12 08:29:32 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 12 Jul 2007 14:29:32 +0200 Subject: os.wait() losing child? References: <4694903B.8000105@cosc.canterbury.ac.nz> Message-ID: <87fy3tg5zn.fsf@mulj.homelinux.net> Nick Craig-Wood writes: >> I think your polling way works; it seems there no other way around this >> problem other than polling or extending Popen class. > > I think polling is probably the right way of doing it... It requires the program to wake up every 0.1s to poll for freshly exited subprocesses. That doesn't consume excess CPU cycles, but it does prevent the kernel from swapping it out when there is nothing to do. Sleeping in os.wait allows the operating system to know exactly what the process is waiting for, and to move it out of the way until those conditions are met. (Pedants would also notice that polling introduces on average 0.1/2 seconds delay between the subprocess dying and the parent reaping it.) In general, a program that waits for something should do so in a single call to the OS. OP's usage of os.wait was exactly correct. Fortunately the problem can be worked around by hanging on to Popen instances until they are reaped. If all of them are kept referenced when os.wait is called, they will never end up in the _active list because the list is only populated in Popen.__del__. > Internally subprocess uses os.waitpid(pid) just waiting for its own > specific pids. IMHO this is the right way of doing it other than > os.wait() which waits for any pids. os.wait() can reap children > that you weren't expecting (say some library uses os.system())... system calls waitpid immediately after the fork. This can still be a problem for applications that call wait in a dedicated thread, but the program can always ignore the processes it doesn't know anything about. From rschroev_nospam_ml at fastmail.fm Mon Jul 16 16:21:03 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 16 Jul 2007 20:21:03 GMT Subject: sqlite3 db update extremely slow In-Reply-To: <1184613750.873464.312390@r34g2000hsd.googlegroups.com> References: <1184613750.873464.312390@r34g2000hsd.googlegroups.com> Message-ID: coldpizza schreef: > I am trying to fill a sqlite3 database with records, and to this end I > have written a class that creates the db, the table and adds rows to > the table. > > The problem is that the updating process is *extremely* slow, and > occasionally I get the message "database locked". > > I tried removing "self.con.commit()" in the add_record method, but > then nothing is saved in the db. I don't know whether this has > anything to do with it, but I have found no option to enable > autocommit. Remove self.con.commit() from add_record(), and do it once after all records are added. The reason that the process is slow with a commit after every INSERT is that sqlite syncs the inserted data to disk before it continues. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From gagsl-py2 at yahoo.com.ar Thu Jul 12 21:26:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Jul 2007 22:26:51 -0300 Subject: storing pickles in sql data base References: <592087469.jZQWuvoN0q@teancum> <5flucrF3cnokrU1@mid.uni-berlin.de> <4866bea60707121018m454bd7e8vaa21d6c38874aca1@mail.gmail.com> Message-ID: En Thu, 12 Jul 2007 14:18:11 -0300, Chris Mellon escribi?: > On 12 Jul 2007 06:00:59 GMT, Marc 'BlackJack' Rintsch > wrote: >> On Wed, 11 Jul 2007 17:14:43 -0500, Chris Mellon wrote: >> >> > [pickle] >> > >> > Protocol 0 (the default) is a text protocol, it's safe to store in a >> > text field or write to a text file. >> >> It's not really a text protocol it's more a binary protocol that uses >> just >> the ASCII range of byte values. You have to write and read the "text" >> files in binary mode or they break if taken across platform boundaries >> because of the different line endings in Linux and Windows for instance. >> > > It's fine as long as you use universal line endings mode. Neither. Won't work for Unicode objects then. See bug#1724366 -- Gabriel Genellina From B.Ogryczak at gmail.com Thu Jul 12 11:33:34 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: Thu, 12 Jul 2007 15:33:34 -0000 Subject: Lists in classes In-Reply-To: <1184253811.052346.220470@22g2000hsm.googlegroups.com> References: <1184253811.052346.220470@22g2000hsm.googlegroups.com> Message-ID: <1184254414.236260.108860@m3g2000hsh.googlegroups.com> On 12 jul, 17:23, Jeremy Lynch wrote: > Hello, > > Learning python from a c++ background. Very confused about this: > > ============ > class jeremy: > list=[] You've defined list (very bad choice of a name, BTW), as a class variable. To declare is as instance variable you have to prepend it with "self." From bdesth.quelquechose at free.quelquepart.fr Sat Jul 21 08:46:15 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Jul 2007 14:46:15 +0200 Subject: class C: vs class C(object): In-Reply-To: References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> <469f1557$0$26759$426a74cc@news.free.fr> <46a082ed$0$431$426a74cc@news.free.fr> Message-ID: <46a6712f$0$19643$426a34cc@news.free.fr> Aahz a ?crit : (snip) > *YOU* are the one confusing people by your dogmatic insistance that > classic classes should be ignored. Grow up. I did. I still do. With every new Python release. I'm sorry for you that you are still stuck with almost prehistoric Python versions, but I don't accept this as a reason to pretend Python has not "grown up" during the last five years... From musiccomposition at gmail.com Thu Jul 26 22:29:59 2007 From: musiccomposition at gmail.com (Benjamin) Date: Fri, 27 Jul 2007 02:29:59 -0000 Subject: Learning Jython? In-Reply-To: <7xmyxiwx5j.fsf@ruckus.brouhaha.com> References: <1185489708.437968.74890@57g2000hsv.googlegroups.com> <7xmyxiwx5j.fsf@ruckus.brouhaha.com> Message-ID: <1185503399.054915.34050@i38g2000prf.googlegroups.com> Paul Rubin wrote: > Matt Bitten writes: > > It looks like Jython is for me. That said, I have two questions: > > (1) Am I thinking straight here? Or is there some other solution that > > a knows-Python-but-not-Java programmer might use? You could convert to the whole world to using the Grail (http:// grail.sourceforge.net), which can run Python applets, but Java applets with Jython are probably the second best option. The java.awt.Applet class isn't that bad. For simple applets, it's probably the only one you'll need. After all, Jython makes Java classes look like Python. Good Luck! > > You are thinking of embedding Jython in a web applet? Probably not > such a great idea, due to its size. Ah, but Jython compiles Python to Java bytecode so browsers will run it. However, it is true, that you'd have to include all of the standard library modules you used. From rcdailey at gmail.com Tue Jul 31 16:07:09 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 31 Jul 2007 15:07:09 -0500 Subject: Iteration over strings In-Reply-To: <46AF8046.7090702@gmx.net> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> <46AF7A49.3040804@jayloden.com> <46AF8046.7090702@gmx.net> Message-ID: <496954360707311307y7d503b8eybd72795c8e699104@mail.gmail.com> Hey, Thanks a lot for your answers guys. I had already known that strings are immutable, but having been a C++ programmer for years I'm still trying to get over the fact that it's not std::string :) The python documentation isn't that easy to navigate in my opinion, so I wasn't able to find the 'replace()' function you guys are talking about. It's actually the perfect solution for the problem. I appreciate your time. On 7/31/07, Hexamorph wrote: > > Jay Loden schrieb: > > Robert Dailey wrote: > >> str = "C:/somepath/folder/file.txt" > >> > >> for char in str: > >> if char == "\\": > >> char = "/" > > > strings in Python are immutable - in other words, they cannot be updated > in place as you're doing above. However, that doesn't mean you can't achieve > what you're after. In Python, the way to approach this problem since you > cannot modify the string in place, is to create a new string object with the > desired content: > > Also note, that you are just extracting one char from the string > into another variable (which you then change) and you are *not* > getting any "reference" to the char in the string. > > As has been alreagy told, use the str.replace() function > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From vedrandekovic at v-programs.com Mon Jul 23 06:00:16 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Mon, 23 Jul 2007 03:00:16 -0700 Subject: problem with exec In-Reply-To: References: <1185099810.772825.284620@m3g2000hsh.googlegroups.com> <1185111419.177524.131870@d55g2000hsg.googlegroups.com> Message-ID: <1185184816.679703.159850@o61g2000hsh.googlegroups.com> On 23 srp, 09:19, "Gabriel Genellina" wrote: > En Sun, 22 Jul 2007 10:36:59 -0300, > escribi?: > > >> Since the application is transforming > >> its input, it could transform braces into indentation. Of course > >> *Python* > >> doesn't use braces, but the question was how to write "pseudo-Python" > >> without using indentation to indicate grouping. > > > This previously is exactly what I need can you help me somehow about > > this > > code > > indentation, on any way you know.Plese help I will really appreciate > > this!!!!!!!!!!!!!! > > If you are using the tokenize module as suggested some time ago, try to > analyze the token sequence you get using { } (or perhaps begin/end pairs > in your own language, that are easier to distinguish from a dictionary > display) and the sequence you get from the "real" python code. Then write > a script to transform one into another: > > from tokenize import generate_tokens > from token import tok_name > from cStringIO import StringIO > > def analyze(source): > g = generate_tokens(StringIO(source).readline) > for toknum, tokval, _, _, _ in g: > print tok_name[toknum], repr(tokval) > > I think you basically will have to ignore INDENT, DEDENT, and replace > NAME+"begin" with INDENT, NAME+"end" with DEDENT. > > -- > Gabriel Genellina Hello, I know what do you mean and I really need that , but I don't know how to I do this. Please help me!!!!! It's really important to me Regards, Vedran From crobc at BOGUS.sbcglobal.net Tue Jul 10 22:59:49 2007 From: crobc at BOGUS.sbcglobal.net (CC) Date: Tue, 10 Jul 2007 19:59:49 -0700 Subject: Should I use Python for these programs? In-Reply-To: <5fh8s2F3crmfnU1@mid.individual.net> References: <1395v33mpci3p5c@corp.supernews.com> <5fh8s2F3crmfnU1@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Grant Edwards wrote: > >>Most of the graphics I do with Python is with Gnuplot (not >>really appropriate for what you want to do. >>wxWidgets/Floatcanvas might be worth looking into. > > Agreed (I'm quite sure you mean wxPython though). Also, in "wxPython > in Action" (the official book) a simple drawing app is constructed. > It could help to start from there. Ooh, that's interesting. The programming contractor at work who does all our DAQ stuff also uses wxPython so it's looking like I should use that since I can get lots of help. Thanks for the book tip. -- _____________________ Christopher R. Carlen crobc at bogus-remove-me.sbcglobal.net SuSE 9.1 Linux 2.6.5 From mail at microcorp.co.za Wed Jul 18 03:09:00 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 18 Jul 2007 09:09:00 +0200 Subject: Pickled objects over the network References: <9c8d48280707171457p4448fdf3of40562bf62a18fc6@mail.gmail.com> Message-ID: <013101c7c90b$99c50e40$03000080@hendrik> Walker Lindley wrote: 8< ---- complaint about pickle error on receiving side --------- Google for netstrings. It looks to me like you are trying to unpickle something that is not a whole pickle... Append the length of the pickle to the front of it, and on the receiving side, first receive the length, then the pickle... Also have a look at Pyro - Hendrik From sjdevnull at yahoo.com Sun Jul 1 20:30:28 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Sun, 01 Jul 2007 17:30:28 -0700 Subject: The best platform and editor for Python In-Reply-To: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> Message-ID: <1183336228.611575.300860@c77g2000hse.googlegroups.com> kimiraikkonen wrote: > Hi, > For experienced with Pyhton users, which developing software and > enviroment would you suggest for Pyhton programming? Compiler+Editor > +Debugger. I use standard CPython bytecode compiler/virtual machine, the Vim editor, and standard pdb for debugging. Vim is nice as it's multiplatform, has a built-in Python interpreter for writing extensions, is free and lightweight. It's a modal editor so that's a matter of taste--people either love it or hate it. > Also what are your suggestions for beginners of Pyhton programming? Start with something like http://www.diveintopython.org for a brief intro. Pick a very small project and program it. Then pick something bigger and do that. Once you're comfortable with small projects, find an open-source project that you like and try to understand the code enough to make some change you find useful; reading code is as important as writing it. From jokeslide at gmail.com Tue Jul 17 01:35:21 2007 From: jokeslide at gmail.com (Jokeslide) Date: Mon, 16 Jul 2007 22:35:21 -0700 Subject: Programming Jokes Message-ID: <1184650521.339838.184240@i13g2000prf.googlegroups.com> Muahahaha http://www.jokeslide.com/index.php?cmd=4&project_id=78&obby_id=242 From Bulkan at gmail.com Thu Jul 12 01:31:40 2007 From: Bulkan at gmail.com (placid) Date: Wed, 11 Jul 2007 22:31:40 -0700 Subject: path backslash escaping trouble In-Reply-To: References: <1184031604.157526.45120@c77g2000hse.googlegroups.com> Message-ID: <1184218300.562746.207390@o61g2000hsh.googlegroups.com> On Jul 11, 10:37 am, "Gabriel Genellina" wrote: > En Mon, 09 Jul 2007 22:40:04 -0300, placid escribi?: > > > > > I have these files; which are Merge Request (ClearCase) files that are > > created by a Perl CGI script (being re-written in Python, as the HTML/ > > JavaScript have been mixed with Perl, maintainability is zero) > > > MergeType::::codefromlabel:::: > > BLname::::BUILDMODS:::: > > OldLname:::::::: > > BaseVersion::::6.9.1.24A:::: > > RequiredRelease::::6.10.1.3:::: > > Description:::::::: > > FixRelation:::::::: > > Dependencies:::::::: > > LpAffected::::No:::: > > CodeReview::::FirstName LastName:::: > > Testing::::Compile/Build;Designer;Smoketests;:::: > > OtherTesting:::::::: > > Vobs::::ipsupport;:::: > > Elements::::\ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3:::: > > > i read this whole file into a string so i can search for the value of > > Elements which is > > \ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3 > > > but this path is escaped > > \\ipsupport\\ipbuild\\Wizard\\build.pl@@\\main\\buildmods\\3 > > > so when i try to escape a string containing that same path using any > > of the os.path escaping methods doesnt > > result in the correct escaped path. It either appends "C:\\" in front > > of the string with all the backslashes escaped > > or it converts the three(3) at then end to "x03" and a match doesnt > > occur! > > You may be confused about the actual string contents: "a\\b" contains > exactly 3 characters, the second being a single backslash. The \ is the > escape character; to include an actual \ inside a string, you have to > double it. Another way is to use raw string literals (supressing escape > processing): r"a\\b" contains four characters. > See section 3.1.2 in the Python tutorial or the Reference (more > technical):http://docs.python.org/ref/strings.html > > -- > Gabriel When a user submits a merge request the Python script creats a subprocess and reads the stdout via a pipe (cleartool find ...) which returns elements that have a particular label. These elements appeared like; \ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3 these elements are then checked againts previously submitted merge requests to see if there are any merge requests that require the same elements to be merged too. When the elements are read from the stdout pipe of the subprocess the backslashes aren't escaped and because these "paths" aren't real windows paths non of the os.path... path escaping methods work! Well i've solved the problem just by using pycleartool "links directly against ClearCase libraries" which returns a tuple containing (status,output,error) and the element paths in output are properly escaped. Thanks for the replies From horpner at yahoo.com Fri Jul 6 06:58:36 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 06 Jul 2007 10:58:36 GMT Subject: Re-raising exceptions with modified message References: <1183668029.470160.218230@q69g2000hsb.googlegroups.com> <1183673210.409169.51830@n2g2000hse.googlegroups.com> <1183713430.018956.46380@w3g2000hsg.googlegroups.com> Message-ID: On 2007-07-06, Alex Popescu wrote: > On Jul 6, 4:20 am, Christoph Zwerschke wrote: >> Alex Popescu wrote: >> > Probably the simplest solution would be to create a new exception and >> > wrapping the old one and the additional info. Unfortunately, this >> > may have a huge impact on 3rd party code that was catching the >> > original exception. So, I think you should create an utility >> > factory-like function that is either creating a new exception >> > instance as the one caught and with the additional information, >> >> Right, I have gone with that (see the example with the PoliteException >> class somewhere below). >> >> > or an utility that knows how to modify the caught exception according >> > to its type. >> >> I guess you mean something like this (simplified): >> >> except Exception, e: >> if getattr(e, 'reason'): >> e.reason += "sorry" >> else: >> e.message += "sorry" >> >> The problem is that these attribute names are not standardized and can >> change between Python versions. Not even "args" is sure, and if a class >> has "message" it does not mean that it is displayed. Therefore I think >> the first approach is better. >> >> > In the first case you will need somehow to tell to the new instance >> > exception the real stack trace, because by simply raising >> > a new one the original stack trace may get lost. >> >> Yes, but thats a different problem that is easy to solve. > > Yeah maybe for a python guy, but I am a newbie. I would really > appreciate if you can show in this thread how this can be done > in Python. Chech out the docs for sys.exc_info(), and for the raise statement. When handling an exception, you can rethrow a different exception, but with the same traceback, by using the three-arg version of raise. See one of my earlier posts in this thread for a working example (although it didn't solve Chris's problem). -- Neil Cerutti From rustompmody at gmail.com Tue Jul 10 12:50:03 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Tue, 10 Jul 2007 22:20:03 +0530 Subject: xml yml and dependency hell Message-ID: yaml by its indent-orientation is quite pythonic. In comparison xml is cumbersome and laborious. Strangely ruby supports yaml out of the box but python requires a third party package PyYAML. Now this may not seem like a big deal for us -- installing pyYAML takes all of one minute -- but it may not be so to others as I recently learned. I conducted a python training for a corporate in which I showed among other things that yaml is much neater than xml. They agreed that it was neat but were reluctant to consider it because it adds dependency headaches at a later point with their customers. So is it likely that yaml will make it to the standard python library at some point?? From rrr at ronadam.com Fri Jul 20 11:35:51 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 20 Jul 2007 10:35:51 -0500 Subject: Break up list into groups In-Reply-To: <1184859881.860066.198940@e16g2000pri.googlegroups.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> <1184694533.380918.169640@m37g2000prh.googlegroups.com> <469D09CC.3080402@ronadam.com> <9e95df10707171408k2dfc8e08wd4056b80fcbe309b@mail.gmail.com> <1184859881.860066.198940@e16g2000pri.googlegroups.com> Message-ID: <46A0D657.9030306@ronadam.com> Matimus wrote: > Excellent work! One more modification and I get below 10us/pass: > > def getgroups(seq): > groups = [] > push = groups.append > iseq = iter(xrange(len(seq))) > for start in iseq: > if seq[start] & 0x80: > for stop in iseq: > if seq[stop] & 0x80: > push(seq[start:stop]) > start = stop > push(seq[start:]) > return groups > > -Matt Looks good to me. :-) So a generator versions would be... (not tested) def getgroups(seq): iseq = iter(xrange(len(seq))) for start in iseq: if seq[start] & 0x80: for stop in iseq: if seq[stop] & 0x80: yield seq[start:stop] start = stop yield seq[start:] (I also wanted to compare this to Georges solution, maybe later.) Now if there is some way to generalize this so it can be used in a broader range of situations without loosing too much of it's efficiency. Of course then maybe group by would be better. Cheers, Ron From bj_666 at gmx.net Wed Jul 11 14:38:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Jul 2007 18:38:38 GMT Subject: binascii.unhexlify ... not clear about usage, and output References: <1180511251.625790.280260@h2g2000hsg.googlegroups.com> <1184142108.846958.189080@k79g2000hse.googlegroups.com> <1184175983.898310.321630@q75g2000hsh.googlegroups.com> Message-ID: <5fkmdeF3cu82eU3@mid.uni-berlin.de> On Wed, 11 Jul 2007 10:46:23 -0700, mensanator at aol.com wrote: > You can with gmpy: > >>>> import gmpy >>>> x = 0x0164 >>>> s = gmpy.digits(x,2) # convert to base 2 >>>> y = '0'*(16-len(s)) + s # pad to 16 bits >>>> y > '0000000101100100' For the padding I'd use the `zfill()` method. In [15]: a = 0x0164 In [16]: gmpy.digits(a, 2).zfill(16) Out[16]: '0000000101100100' Ciao, Marc 'BlackJack' Rintsch From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jul 9 11:34:23 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 09 Jul 2007 17:34:23 +0200 Subject: What is the most efficient way to test for False in a list? References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <7x7ipajvst.fsf@ruckus.brouhaha.com> <5fejp2F3cp3igU1@mid.individual.net> <5feju0F3c7pd1U1@mid.uni-berlin.de> Message-ID: <5ff2ruF3cpan3U1@mid.individual.net> Diez B. Roggisch wrote: > Bjoern Schliessmann wrote: >> Paul Rubin wrote: >>> lex writes: >>>> but what is your best way to test for for False in a list? >>> >>> status = all(list) >> >> Am I mistaken, or is this no identity test for False at all? > > You are mistaken. all take an iterable and returns if each value > of it is true. That's an identity test for True, not for False (the latter was requested). Thus, I'm not mistaken. Regards, Bj?rn -- BOFH excuse #236: Fanout dropping voltage too much, try cutting some of those little traces From steve at holdenweb.com Mon Jul 23 20:37:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Jul 2007 20:37:28 -0400 Subject: Maintaining leading zeros with the lstrip string function? In-Reply-To: References: Message-ID: Randy Kreuziger wrote: > Thanks for the basename suggestion. That almost works. I'm running > into a problem with some of the directory names when they include > \800x\ see below. > ?----------------------------------------------------------------------------- > import sys, os, string > > teststring = 'C:\shoreline\dvd\prep area\800x\060623_00001.jpg' > print os.path.basename(teststring) > ?----------------------------------------------------------------------------- > Results in > 800x0623_00001.jpg > > But it needs to be > 060623_00001.jpg > You need to be careful with those backslashes! >>> teststring = 'C:\shoreline\dvd\prep area\800x\060623_00001.jpg' >>> teststring 'C:\\shoreline\\dvd\\prep area\\800x0623_00001.jpg' >>> teststring = r'C:\shoreline\dvd\prep area\800x\060623_00001.jpg' >>> teststring 'C:\\shoreline\\dvd\\prep area\\800x\\060623_00001.jpg' >>> 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 Sat Jul 14 00:30:41 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 14 Jul 2007 06:30:41 +0200 Subject: Understanding python functions - Instant Python tutorial In-Reply-To: References: <878x9kkeif.fsf@benfinney.id.au> Message-ID: <4697e0ae$0$23165$426a74cc@news.free.fr> Chris Carlen a ?crit : (snip) > > Excellent description. This understandable to me since I can envision > doing this with pointers. But I have no idea how Python actually > implements this. The code source is freely available, and it's in C !-) > It also appears that I am being guided away from > thinking about it in terms of internal implementation. Indeed. Python *is* a hi-level language, and it's main benefit (wrt to lower-level languages like C or Pascal) is to let you think more in terms of "what" than in terms of "how". From kelvie at ieee.org Fri Jul 13 17:15:48 2007 From: kelvie at ieee.org (Kelvie Wong) Date: Fri, 13 Jul 2007 14:15:48 -0700 Subject: Getting values out of a CSV In-Reply-To: References: <1184295593.638409.22910@22g2000hsm.googlegroups.com> <5fpcdeF3dm8bpU2@mid.uni-berlin.de> Message-ID: <94ccbe710707131415p390b7b36gae9441c48d05a60d@mail.gmail.com> Hrm. Repeating the test several more times, it seems that the value fluctuates, sometimes one's faster than the other, and sometimes they're the same. Perhaps the minute difference between the two is statistically insignificant? Or perhaps the mechanism underlying both (i.e. the implementation) is the same? On 7/13/07, Daniel wrote: > On Fri, 13 Jul 2007 16:18:38 +0300, Marc 'BlackJack' Rintsch > wrote: > >> $ python -m timeit -c 'import csv; data = > >> list(csv.reader(open("some.csv", > >> "rb")))' > >> 10000 loops, best of 3: 44 usec per loop > >> $ python -m timeit -c 'import csv; data = [row for row in > >> csv.reader(open("some.csv", "rb"))]' > >> 10000 loops, best of 3: 37 usec per loop > >> > >> I don't know why there seems to be a differece, but I know that list > >> comps > >> are python are very heavily optimised. > > > > Does the machine use power saving features like SpeedStep or > > something similar, i.e. runs the processor always with 100% speed or is > > it > > dynamically stepped if there's load on the processor? Do both tests read > > the data always from cache or has the very first loop had to fetch the > > CSV > > file from disk? > > > > $ python -m timeit -n 1000 -c 'import csv; data = [row for row in > > csv.reader(open("test.csv", "rb"))]' 1000 loops, best of 3: 1.27 msec per > > loop > > > > $ python -m timeit -n 1000 -c 'import csv; data = > > list(csv.reader(open("test.csv", "rb")))' 1000 loops, best of 3: 1.25 > > msec > > per loop > > No SpeedStep - tried a few repeats just in case files were cached, > consistent 35usec for comp 40usec for list > > Python 2.5.1 on Linux 1.2ghz > > Even replacing the csv lookup with a straight variable declaration: > [range(10)*3], same results > > Weird. > > Python > -- > http://mail.python.org/mailman/listinfo/python-list > -- Kelvie From twisted0n3 at gmail.com Sat Jul 7 16:47:57 2007 From: twisted0n3 at gmail.com (Twisted) Date: Sat, 07 Jul 2007 20:47:57 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> Message-ID: <1183841277.333384.188950@g4g2000hsf.googlegroups.com> On Jul 7, 4:26 pm, Edward Dodge wrote: > So -- what magical computer app illuminates the entire room and shows > you how to use everything at the flip of a switch? This brilliant > discovery would put Sam's, O'Reilly, the for-Dummies series, and > virtually every other computer book publisher out of business in weeks. > Naturally, this would include the publishers of books on "easy-to-use" > Microsoft products. I don't know, but it sure as hell isn't emacs. From steve at holdenweb.com Thu Jul 26 15:12:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Jul 2007 15:12:22 -0400 Subject: Fwd: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: <611885.63070.qm@web36213.mail.mud.yahoo.com> References: <4b490f2f0707260810qe4a410co366291a6dccd4f01@mail.gmail.com> <611885.63070.qm@web36213.mail.mud.yahoo.com> Message-ID: jed drury wrote: > Hey, Perl's new motto is "There is more than 1 way to > be an ASSHOLE!" As you have just demonstrated. 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 rampeters at gmail.com Tue Jul 24 13:12:15 2007 From: rampeters at gmail.com (johnny) Date: Tue, 24 Jul 2007 10:12:15 -0700 Subject: Any python module for Traversing HTML files Message-ID: <1185297135.542235.55290@r34g2000hsd.googlegroups.com> Any python module for navigating and selecting, parsing HTML files? From no at no.no Sun Jul 8 23:42:12 2007 From: no at no.no (Daniel) Date: Mon, 09 Jul 2007 06:42:12 +0300 Subject: What is the most efficient way to test for False in a list? References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <1183951291.176559.12560@d55g2000hsg.googlegroups.com> Message-ID: On Mon, 09 Jul 2007 06:21:31 +0300, Simon Forman wrote: > > On Jul 8, 7:43 pm, lex wrote: >> Of course there is the always the iteration method: >> >> list = [1, True, True, False, False, True] >> status = True >> for each in list: >> status = status and each >> >> but what is your best way to test for for False in a list? > > > False in list > > all() is slightly faster -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From marc.stuart.risney at gmail.com Wed Jul 4 22:58:18 2007 From: marc.stuart.risney at gmail.com (Marc Stuart) Date: Thu, 5 Jul 2007 03:58:18 +0100 Subject: need a variation algorithm for Lists in Dictionaries Message-ID: Hi, I am trying to create a function, where I pass a dictionary with a lits of strings, and try to return a a list of strings, for all variations, any ideas ? Thanks def getAllVariants(someDict): keys = someDict.keys() for x in keys: print len(someDict[x]) x = {1:['a','b'],2:['b','c'],3:['d','e','f','g']} getAllVariants(x) """ I need to get a list of strings that render all possible variants, this is what my output should be based on the x dictionary: abd abe abf acd ace acf acg bbd bbe bbf bcd bce bcf bcg """ From kyosohma at gmail.com Thu Jul 12 11:33:20 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 12 Jul 2007 15:33:20 -0000 Subject: Lists in classes In-Reply-To: <1184253811.052346.220470@22g2000hsm.googlegroups.com> References: <1184253811.052346.220470@22g2000hsm.googlegroups.com> Message-ID: <1184254400.974981.213990@q75g2000hsh.googlegroups.com> On Jul 12, 10:23 am, Jeremy Lynch wrote: > Hello, > > Learning python from a c++ background. Very confused about this: > > ============ > class jeremy: > list=[] > def additem(self): > self.list.append("hi") > return > > temp = jeremy() > temp.additem() > temp.additem() > print temp.list > > temp2 = jeremy() > print temp2.list > ============== > The output gives: > ['hi','hi'] > ['hi','hi'] > > Why does adding items to one instance produce items in a separate > instance? Doesn't each instance of jeremy have its' own "list"? > > Many thanks for clearing up this newbie confusion. > > Jeremy. The reason it works like that is that your variable "list" isn't an instance variable per se. Instead, you should have it like this: class jeremy: def __init__(self): self.lst=[] def additem(self): self.lst.append("hi") return Now it works as expected. It's some kind of scope issue, but I can't explain it adequately. Mike From montyphyton at gmail.com Sat Jul 21 04:44:09 2007 From: montyphyton at gmail.com (montyphyton at gmail.com) Date: Sat, 21 Jul 2007 01:44:09 -0700 Subject: Sorting dict keys In-Reply-To: References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> Message-ID: <1185007449.179903.5480@w3g2000hsg.googlegroups.com> On 21 srp, 02:31, Steven D'Aprano wrote: > On Fri, 20 Jul 2007 15:27:51 -0700, montyphyton wrote: > >>>> b = a.keys() > >>>> b.sort() > > [1, 2, 3] > > > Works fine, but I would really like it if I could somehow do it in one > > line. > > Why? Is the Enter key on your keyboard broken? Is there a global shortage > of newline characters that I haven't been told about? Does your employer > pay you less if you write more lines? > > -- > Steven. I'd like to do it in one line because what I am trying to do is, after all, a single, simple enough action. I find the suggested b = sorted(a.keys()) much more readable than breaking it up in two lines. In the long run, I guess it's a matter of personal taste... Do I get payed less for more source code? Since I'm a student, I don't get payed at all, regardless of number of lines :) From bbxx789_05ss at yahoo.com Sun Jul 1 05:18:02 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 01 Jul 2007 02:18:02 -0700 Subject: os.path.isfile() Message-ID: <1183281482.668177.142470@c77g2000hse.googlegroups.com> Here is a program to print out the files in a directory: ----------- import os myfiles = os.listdir("../") print myfiles for afile in myfiles: print afile if os.path.isfile(afile): print afile, "___file" if os.path.isdir(afile): print afile, "___dir" print ------------ Here is what's in the directory: ---------- $ ls -al ../ total 2576 drwxr-xr-x 8 nnn nnn 272 Jul 1 03:03 . drwxr-xr-x 25 nnn nnn 850 Jul 1 01:34 .. -rw-r--r-- 1 nnn nnn 6148 Jul 1 03:02 .DS_Store -rw-r--r-- 1 nnn nnn 1300000 Jun 27 14:02 aaa.txt drwxr-xr-x 55 nnn nnn 1870 Jul 1 03:09 dir1 -rwxrwxrwx 1 nnn nnn 263 Jun 27 22:40 mytest.py -rw-r--r-- 1 nnn nnn 0 Mar 4 16:15 scratch.txt -rw-r--r-- 1 nnn nnn 275 Apr 11 03:40 xmlFile.xml ------------ Here is the output from my program: ---------- $ python 1test.py ['.DS_Store', 'aaa.txt', 'dir1', 'mytest.py', 'scratch.txt', 'xmlFile.xml'] .DS_Store .DS_Store ___file aaa.txt aaa.txt ___file dir1 mytest.py scratch.txt xmlFile.xml $ -------------- I expected the output: ----------- DS_Store .DS_Store ___file aaa.txt aaa.txt ___file dir1 dir1 ___dir mytest.py mytest.py ___file scratch.txt scratch.txt ___file xmlFile.xml xmlFile.xml ___file ------------ From wildemar at freakmail.de Wed Jul 18 09:40:07 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 18 Jul 2007 15:40:07 +0200 Subject: The Modernization of Emacs: exists already In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272678.877166.209640@j4g2000prf.googlegroups.com> <1184764620.778937.264760@m37g2000prh.googlegroups.com> Message-ID: <469E1837.9000106@freakmail.de> Rustom Mody wrote: > But how does posting an emacs related question help on a python mailing list?? > One Word: Ego. Don't reply. /W From bdesth.quelquechose at free.quelquepart.fr Wed Jul 25 15:19:08 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 25 Jul 2007 21:19:08 +0200 Subject: Relative-importing * In-Reply-To: <7xsl79uhm7.fsf@ruckus.brouhaha.com> References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> <871weth2gg.fsf@benfinney.id.au> <7xsl79uhm7.fsf@ruckus.brouhaha.com> Message-ID: <46ae3957$0$32275$426a74cc@news.free.fr> Paul Rubin a ?crit : > Steven D'Aprano writes: > >>I read "from module import *" as explicitly saying "clobber the current >>namespace with whatever names module exports". That's what from does: it >>imports names into the current namespace. It isn't some sort of easy to >>miss side-effect. If a name already existed, it gets clobbered, just like >>any other import: > > > Seems to me that there should be a compiler warning when this happens. if some_runtime_condition: from foo import * Paul, I do know why you think compile-time checks are a good thing, but you do have to understand that Python is *highly* dynamic. Except for syntax errors, don't expect much help from the Python's compiler. From exarkun at divmod.com Sun Jul 8 14:30:43 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 8 Jul 2007 14:30:43 -0400 Subject: In search of python idiom for accessing arbitrary fields at run time In-Reply-To: <1183918901.388300.220620@o61g2000hsh.googlegroups.com> Message-ID: <20070708183043.4947.1199519388.divmod.quotient.9149@ohm> On Sun, 08 Jul 2007 18:21:41 -0000, mshiltonj wrote: >I'm trying to find the preferred python idiom for access arbitrary >fields of objects at run time. > It's not an idiom, it's a built-in function: getattr. Jean-Paul From S.Mientki-nospam at mailbox.kun.nl Thu Jul 26 16:58:15 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 26 Jul 2007 22:58:15 +0200 Subject: removing items from a dictionary ? In-Reply-To: References: <46A8EFF5.4060600@mailbox.kun.nl> Message-ID: > > Since it isn't practical to iterate over Eagle_Power_Nets and test for > presence in your Nets dict, you have to iterate over at least the keys > of Nets. You could just iterate over the keys rather than the whole > table, though: > > for net in Nets.keys(): > # Nets.iterkeys() would avoid building the list > # but that runs the same risks as your original > if net.upper() in in Eagle_Power_Nets : > del Nets[net] > thanks Steve, that does the job. > Watch that spacing, by the way: Python is easy to keep readable if you > follow the style guidelines of PEP 8. Yeah, that's my great sin, in all languages I always 2 spaces, so that's the "best readable" for me. I still must write a beautifier, that doubles spaces when a Python file leaves my computer ;-) cheers, Stef Mientki From Brad.Johnson at ballardtech.com Mon Jul 30 18:49:17 2007 From: Brad.Johnson at ballardtech.com (Brad Johnson) Date: Mon, 30 Jul 2007 22:49:17 +0000 (UTC) Subject: win32 question in Python References: Message-ID: Huang, Shun-Hsien ercot.com> writes: > but how do I copy a excel file into > database table by using Python? > I'm not sure if this helps, but you can access the Excel Automation model very easily with: import win32com.client x1 = client.Dispatch("Excel.Application") Now you can use the x1 object to access any of the properties and methods in the Excel Automation model. From nick at craig-wood.com Wed Jul 4 05:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 04 Jul 2007 04:30:04 -0500 Subject: what is wrong with that r"\" References: <1183468603.714314.241430@n60g2000hse.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Jul 3, 7:15 am, alf wrote: > > question without words: > > > > >>> r"\" > > File "", line 1 > > r"\" > > ^ > > SyntaxError: EOL while scanning single-quoted string > > >>> r"\ " > > '\\ ' > > One slash escapes the following character, so the proper way of > writing it is either > > r"\\" or r"\"" I don't think so... >>> r"\\" '\\\\' >>> r"\"" '\\"' Indicating that all the \ in the above are inserted literally. Maybe you meant >>> "\\" '\\' >>> "\"" '"' -- Nick Craig-Wood -- http://www.craig-wood.com/nick From rbsharp at gmx.de Wed Jul 4 03:31:54 2007 From: rbsharp at gmx.de (rbsharp at gmx.de) Date: Wed, 04 Jul 2007 00:31:54 -0700 Subject: unify els database In-Reply-To: <1183465552.876190.66910@o61g2000hsh.googlegroups.com> References: <1183383335.842730.41600@q69g2000hsb.googlegroups.com> <1183446552.345276.44930@k29g2000hsd.googlegroups.com> <1183465552.876190.66910@o61g2000hsh.googlegroups.com> Message-ID: <1183534314.073800.180560@q69g2000hsb.googlegroups.com> On Jul 3, 2:25 pm, luca72 wrote: > Hello and thanks for your answer, the unify db is on unix-sco and i > need to connect with linux machine with python > > Regards > > Luca Hello, perhaps I introduced the confusion by using the word "connect" ambiguously. What I do is to directly use the unify database. My programs are then running on the sco machine and use the HLI-libraries to operate directly on the unify database file. In that sense I do not "connect" to the database. If your programs are running on the linux machine and want to connect to the unify database on the sco machine, then I suspect that you are talking about an ELS Server, probably configured with the DBIntegrator. The DBIntegrator, as far as I understand it since I don't use this route myself, offers the possibly of ODBC and JDBC access to the database. There are windows ODBC drives and a JDBC driver. If this is your scenario, then the problem is a) how to get ODBC access to the database under linux, a question I cannot answer, or b) perhaps using Jython and the JDBC-Driver, which should work if this is an option. I hope to have been of some help. Greetings, Richard Sharp From kyosohma at gmail.com Mon Jul 23 09:07:01 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 23 Jul 2007 13:07:01 -0000 Subject: Python MAPI In-Reply-To: <1185134453.934837.325310@w3g2000hsg.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> Message-ID: <1185196021.512126.93490@r34g2000hsd.googlegroups.com> On Jul 22, 3:00 pm, memra... at yahoo.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? > > I expect you will find it easier figuring out how to install your app > in the SendTo menu rather than making your app callable via MAPI. This > probably involves ShellExtensions but I believe there are utilities > that can be used to add any arbitrary application to the SendTo menu. > That may be enough for your application. > > You might want to have a look at SpamBayes for an example of an > Outlook extension written in Python to get an idea of how you can > interface with Outlook. We may add it to the Sendto menu, but we have users that want to be able to use the email functionality from within Office Apps. I've been planning on reading the SpamBayes source code anyway...however, we're trying to move away from Outlook. We're currently using Zimbra now and that's why I'd like to open my Python program with MAPI so I can send email through our new Zimbra mail server. I have interfaced with Outlook before using COM, but it's not pretty. Mike From deets at nospam.web.de Tue Jul 24 14:13:39 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 24 Jul 2007 20:13:39 +0200 Subject: Problem in Socket..... In-Reply-To: <1185299582.776366.17970@d55g2000hsg.googlegroups.com> References: <1185299582.776366.17970@d55g2000hsg.googlegroups.com> Message-ID: <5gmtqkF3d4pe9U1@mid.uni-berlin.de> Clement schrieb: > Is it possible to close the socket connection immediately in > Python...... Because i am getting error even though i close it after > all the transfer.... I read from one article it is possible in C > socket.... Whether is it possible in Python? > Which error? And usually the python api for sockets just wraps the C-calls, so you should have the same options to properly close it. Diez From emin.shopper at gmail.com Wed Jul 11 11:26:39 2007 From: emin.shopper at gmail.com (Emin.shopper Martinian.shopper) Date: Wed, 11 Jul 2007 11:26:39 -0400 Subject: profiling a C++ python extension In-Reply-To: <1184113272.962640.41240@22g2000hsm.googlegroups.com> References: <1184113272.962640.41240@22g2000hsm.googlegroups.com> Message-ID: <32e43bb70707110826o4957b03ci8a863d0ced2655ba@mail.gmail.com> Googling for "profiling python extensions" leads to the following link which worked for me a while ago: http://plexity.blogspot.com/2006/02/profiling-python-extensions.html On 7/10/07, rasmus wrote: > > I have used gprof to profile stand alone C++ programs. I am also > aware of pure python profilers. However, is there a way to get > profile information on my C++ functions when they are compiled in a > shared library (python extension module) and called from python. From > what I can tell, gmon.out will not be generated unless the entire > executable (python interpreter) was compiled with -pg. Is my only > solution to recompile the python interpreter with -pg so that my > extension module (also compiled with -pg) produces a gmon.out? > > Any suggestions or tips would be helpful. > > Matt > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Barry.Carroll at datalogic.com Mon Jul 30 13:25:57 2007 From: Barry.Carroll at datalogic.com (Carroll, Barry) Date: Mon, 30 Jul 2007 10:25:57 -0700 Subject: Free support for Python developers In-Reply-To: <200707300228.57525.python@cx.hu> Message-ID: <2BBAEE949D384D40A2B851287ADB6A4304595C03@eugsrv400.psc.pscnet.com> Viktor: This is a great idea. Thank you I don't currently have a voice setup on my machine, but will try to get one as soon as possible. I would be pleased to trade English practice for Python support. Regards, Barry barry.carroll at datalogic.com 541-302-1107 ________________________ We who cut mere stones must always be envisioning cathedrals. -Quarry worker's creed > -----Original Message----- > From: Ferenczi Viktor [mailto:python at cx.hu] > Sent: Sunday, July 29, 2007 5:29 PM > To: python-announce-list at python.org > Subject: Free support for Python developers > > I am pleased to announce the availability of python support for English > speaking developers. The service is free of charge. More information: > > http://python.cx.hu/support/ From kinch1967 at gmail.com Wed Jul 4 07:22:13 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: Wed, 04 Jul 2007 04:22:13 -0700 Subject: Generator for k-permutations without repetition Message-ID: <1183548133.495759.191390@d30g2000prg.googlegroups.com> I was able to google a recipe for a k_permutations generator, such that i can write: x = range(1, 4) # (say) [combi for combi in k_permutations(x, 3)] => [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, 3, 1], [1, 3, 2], [1, 3, 3], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2, 1], [2, 2, 2], [2, 2, 3], [2, 3, 1], [2, 3, 2], [2, 3, 3], [3, 1, 1], [3, 1, 2], [3, 1, 3], [3, 2, 1], [3, 2, 2], [3, 2, 3], [3, 3, 1], [3, 3, 2], [3, 3, 3]] but what i really want is the above without repetition, i.e.: [combi for combi in k_permutations_without_repetitions(x, 3)] => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] For smallish lists, it's no problem to generate the list as follows: no_reps_combis = [combi for combi in k_permutations(x, 3) if \ len(set(combi)) == 3] but i'm sure there must be a way to do this as a pure generator, just that i wouldn't have a clue how to go about it. Help please, Python Gods! :) Apologies in advance if I have got my terminology wrong and have been googling the wrong stuff and therefore coming up blank. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 24 04:22:16 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 24 Jul 2007 10:22:16 +0200 Subject: Where do they tech Python officialy ? In-Reply-To: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> Message-ID: <46a5b6b2$0$613$426a74cc@news.free.fr> NicolasG a ?crit : > Hi, > > I want to be a professional python programmer, While there are (more and more) professional programmers using Python, either as their main language or not, there's no such thing as a "professional Python programmer", because being a proofessional programmer requires much more than knowing one programming language. > unfortunately I'm > working on technical support and don't have the time/patience to start > making projects my self. I tried to apply to some Python positions but > unfortunately sometimes to work as a programmer is really hard in this > world, every employee requires professional experience You surely won't get any position as a programmer if you don't have any experience as a programmer. But it doesn't necessarily has to be "professional" experience - being a contributor to a serious OSS project is nowadays considered as valid experience by some shops. > and you can't > really start as a beginner.. Yes you can - obviously, everyone has to start somewhere !-) But being a beginner doesn't mean having strictly no experience - just that you didn't get paid so far. > I'm planning to save some money and attend a course in any of the > universities that teach hard core Python. > > Does some one have any suggestions on which University to attend ? > Alternatives solutions are welcome.. Don't focus on Python. The important part is to learn programming - once you'll be there, learning Python by yourself won't be a problem. And I second Paul Rubin's advice: avoid universities teaching Java as the main language. From see.signature at no.spam Mon Jul 30 10:48:57 2007 From: see.signature at no.spam (Eric Brunel) Date: Mon, 30 Jul 2007 16:48:57 +0200 Subject: File handle not being released by close References: <1185806160.161748.58910@d55g2000hsg.googlegroups.com> Message-ID: On Mon, 30 Jul 2007 16:36:00 +0200, wrote: > Hi, > > I'm in the process of writing some code and noticed a strange problem > while doing so. I'm working with PythonWin 210 built for Python 2.5. I > noticed the problem for the last py file processed by this script, > where the concerned tmp file is only actually written to when > PythonWin is closed. In other words, after I run this script, one of > the generated tmp files has a size of 0kB. I then close PythonWin and > it is then written to. > > I'm guessing the garbage collector is causing the file to be written, > but shouldn't close do this? > > /Barry > > import os, time, string > > dir = 'c:\\temp1' > > def listAllFile(fileNames,dir,files): > def f1(a,dir=dir): return os.path.join(dir,a) > files2 = map(f1, files) > fileNames.extend(files2) > > fileNames = [] > os.path.walk(dir,listAllFile,fileNames) > > for fileName in fileNames: > fileBeginning = os.path.splitext(fileName)[0] > fileEnd = os.path.splitext(fileName)[1] > > if fileEnd == ".py": > print fileName > f=open(fileBeginning+".tmp", 'w') > f.write("Hello") > f.close f.close() HTH... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From steve at holdenweb.com Tue Jul 31 23:07:47 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 31 Jul 2007 23:07:47 -0400 Subject: http client module In-Reply-To: <1185936595.262806.269290@19g2000hsx.googlegroups.com> References: <1185936595.262806.269290@19g2000hsx.googlegroups.com> Message-ID: 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/projects/httplib2/+httplib2+python&hl=es&ct=clnk&cd=1&gl=cl&client=firefox-a > > 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 ------------- From zyzhu2000 at gmail.com Fri Jul 27 17:19:23 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 27 Jul 2007 21:19:23 -0000 Subject: C API -- Two questions In-Reply-To: <5gthbnF3i0lfsU1@mid.uni-berlin.de> References: <1185496462.855297.21240@57g2000hsv.googlegroups.com> <5gthbnF3i0lfsU1@mid.uni-berlin.de> Message-ID: <1185571163.686327.190000@i13g2000prf.googlegroups.com> On Jul 27, 1:23 am, Marc 'BlackJack' Rintsch wrote: > On Fri, 27 Jul 2007 00:34:22 +0000, beginner wrote: > > 2) How can I make the arguments less picky without writing a lot of > > type conversion code? My function really needs a tuple as its > > argument. For example, f( (1,2,3) ) would work. However, in order to > > make it easy to use, I am thinking that it should be able to take a > > list too. In other words, I want f( [1,2,3] ) to work also. I can > > certainly check for the types in the code and deal with each > > situation. But remember this is tedious to do in C. Is there any > > better way to handle this? > > The same way as you would do in Python: convert the argument into a tuple > if you *really* need a tuple, or just use it as sequence or via iterator. > And pay attention to errors of course. > > Ciao, > Marc 'BlackJack' Rintsch That makes sense. Thanks. From steve at holdenweb.com Fri Jul 13 20:37:04 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Jul 2007 20:37:04 -0400 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: Aahz wrote: > In article , > Chris Carlen wrote: >>From what I've read of OOP, I don't get it. > > For that matter, even using OOP a bit with C++ and Perl, I didn't get it > until I learned Python. > >> The problem for me is that I've programmed extensively in C and .asm on >> PC DOS way back in 1988. > > Newbie. ;-) > > (I started with BASIC in 1976.) > Newbie ;-) (I started with Algol 60 in 1967). >> Form 2: Use Python and PySerial and TkInter or wxWidgets. >> >> Pro: Cross-platform goal will likely be achieved fully. Have a >> programmer nearby with extensive experience who can help. >> Con: Must learn new language and library. Must possibly learn a >> completely new way of thinking (OOP) not just a new language syntax. >> This might be difficult. > > My experience is that learning GUI programming is difficult. Moreover, > GUI programming in C involves a lot of boilerplate that can be automated > more easily with Python. So I think this will be a better solution. > I used to write in C for the SunView platform (back in the days when the GUI was integrated into the kernel as the only way to get acceptable speed on the display). From what I remember, "Hello World" took about 40 lines. The immense (relatively speaking: this was 1985) size of the libraries required was one of the primary justifications for implementing shared libraries. > Note very very carefully that Python does not require an OOP style of > programming, but it will almost certainly be the case that you just > naturally start using OOP techniques as you learn Python. That's very true. I still use a lot of (perhaps too much) procedural coding, but driving the object-oriented libraries is a great way for a noob to get started in OOP. 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 Sun Jul 15 17:02:25 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 15 Jul 2007 23:02:25 +0200 Subject: [OT] Re: Can a low-level programmer learn OOP? In-Reply-To: References: <4697d9f0$0$7614$426a74cc@news.free.fr> <1184485640.495801.194200@z28g2000prd.googlegroups.com> <469b27dd$0$21672$426a74cc@news.free.fr> Message-ID: <469bcd17$0$18608$426a74cc@news.free.fr> Wayne Brehaut a ?crit : > On Mon, 16 Jul 2007 10:10:05 +0200, Bruno Desthuilliers > wrote: > > >>Wayne Brehaut a ?crit : >>(snip) >> >>>after Bruno made the >>>claim: "OO is about machines - at least as conceveid by Alan Key, who >>>invented the term and most of the concept." >> >>Please reread more carefully the above. I do give credit to Smalltalk's >>author for the *term* "OOP", and *most* (not *all*) of the concepts (I >>strongly disagree with your opinion that message-passing is not a core >>concept of OO). > > > One problem is that it's often not clear what lists of properties are > his definition of OOP vs. what are the intended properties of > Smalltalk--his intended impelmentation of OOP. Many of the lists begin > with the basic requirements that "everything is an object" and > "objects communicate by message passing", but the most common > "generally agreed upon" definition abstracts just four requirements > from these (changing) lists--attempting to separate implementation > details from what is essential to the underlying framework. As I note > below, these were: > > 1. modularity (class-based? object-based?) > 2. inheritance (sub-classing) > 3. encapsulation (information hiding) I don't see information hiding and encapsulation as being the very same thing. But anyway... > 4. polymorphism ((sub-) class-specific response to a message, or > processing of a method) subclassing - and even classes - are not necessary for polymorphism. I guess you have a good enough knowledge of Python and/or some prototype-based OOPL to know why !-) > > Other details in Kay's lists are considered implementation details, > and important advances or alternatives to pevious methods, but not > required for a language to _be_ OO. It is reputed, though, that in > 2003 Kay said > (http://c2.com/cgi/wiki?AlanKaysDefinitionOfObjectOriented) "OOP to > me means only messaging, local retention and protection and hiding of > state-process, and extreme LateBinding of all things." > > So I understand your accepting one of Kay's lists as being a > definition of OOP instead of "just" a description of Smalltalk, or of > accepting this fairly recent "definition" as being the true one Is there any "true one" ?-) > (as > opposed to the previous lists of usually 6 properties). "It's hard to > hit a moving target!" Indeed. > >>FWIW, I first mentionned Simula too (about the state-machine and >>simulation aspect), then sniped this mention because I thought it was >>getting a bit too much OT - we're not on comp.object here. > > > Understood--sort of--but there is sufficient accurate information > about Simula available on the web now that it's no longer necessary to > use quotes from Kay about OOP and Smalltalk just because they're more > accessible, as used to be the case. What would be so OT about > referring to Simulain one sentence instead of or in addition to > Smalltalk? What I mean is that I felt my answer to be already OT enough so I sniped large parts of it. FWIW, I could have sniped the reference to Alan Kay and kept the one to Simula, but then it would have require more rewrite work. > But I digress--my only real objection to your post was your opinion > and claim that Kay "invented the term and most of the concept": I agree that the term "most" is perhaps a bit too strong. For my defense, please keep in mind that I'm not a native english speaker, so I often have hard time expressing myself with the exact nuance I'd use in french. (snip) > > As has been noted before, it's often the fact that a cause becomes a > religion: Good Lord, save us from becoming religious !-) Ok, I admit that I have my own understanding of OO (as anyone else, I guess), which is quite closer to Smalltalk's model than to any other OOPL (even Python). It probabaly has to do with the extremely generalized and systematic application of two key concepts - objects and messages - in such a way that it becomes a coherent whole - while most mainstream OOPLs feel to me more like ad-hoc collection of arbitrary rules and features. So yes, I'm probably guilty of being a bit too impassioned here, and you're right to correct me. But have mercy and take time to read a bit more of the offending post, I'm pretty confident you won't find me guilty of mis-placed "religiosity". (snip) > in contrast, all I've done so far is complain about > those who don't accept the correct (i.e., my) definition or use of > terms. Lol ! I'm afraid this is something we're all guilty of one day or another... From http Fri Jul 13 14:28:07 2007 From: http (Paul Rubin) Date: 13 Jul 2007 11:28:07 -0700 Subject: NoneType object not iterable References: <4697bcc6$0$25761$9b622d9e@news.freenet.de> Message-ID: <7xabu02m6g.fsf@ruckus.brouhaha.com> Stargaming writes: > It does not turn into something. The `sort()` method just works "in > place", i. e. it will mutate the list it has been called with. It > returns None (because there is no other sensible return value). > > For you, that means: You don't have to distinguish between keyList and > sortedList. Just call ``.sort()`` on keyList and it will just work. Alternatively, use sortedList = sorted(keyList) From ptmcg at austin.rr.com Mon Jul 23 11:28:32 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 23 Jul 2007 08:28:32 -0700 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: <7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com> Message-ID: <1185204512.255392.105820@r34g2000hsd.googlegroups.com> On Jul 23, 5:53 am, ed... at holyrood.ed.ac.uk (Eddie Corns) wrote: > Wolfgang Strobl writes: > >few of James Gimple's snippets from "Algorithms in SNOBOL4" > >(->http://www.snobol4.org/) as an exercise using that library might help > >to get a better appreciation. Perhaps I'll try, eventually ... > > I never noticed them or the PDF of the book there before. Some Friday > afternoon reading for sure. > > Personally I hope to get more to time to look at a combination of Lua and > PEGs (http://en.wikipedia.org/wiki/Parsing_expression_grammar) for my parsing > needs. > > Eddie If you get a chance to look at pyparsing, I'd be interested in your comments. The PEG page and the SNOBOL implementation have many similar concepts with pyparsing (or is it the other way around?). -- Paul From kyosohma at gmail.com Wed Jul 4 13:14:05 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 04 Jul 2007 10:14:05 -0700 Subject: How can i change an Object type ? In-Reply-To: References: <1183516235.774875.45710@q69g2000hsb.googlegroups.com> Message-ID: <1183569245.352019.147380@r34g2000hsd.googlegroups.com> On Jul 4, 12:40 am, Tim Roberts wrote: > KuhlmannSascha wrote: > > >i tried now for several hours to read through a win32com API to access > >Itunes and read out myplaylists. > > >First of all the Code: > >... > >The current Logic is to access first Itunes and then a Playlist > >Collection. > >This Playlist collection returns different kind of objects for > >Playlists. > >I am focussing on the Playlists of the object UserPlaylist. > >(CodeLine: if curPlaylist.Kind == 2:) > >After that i should be sure to have a UserPlaylist, but Python stops > >with an exception that the requested Attribute "Smart" is not > >available > >Error MEssage: > >AttributeError: ' >instance at 0x30216960>' object has no attribute 'Smart' > > Smart is part of IITUserPlaylist, not IITPlaylist. You need to call > curPlaylist.QueryInterface to get the IITUserPlaylist, but that means > you'll need to know the GUID for IITUserPlaylist. Perhaps Google will > help. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. These look like they could give you some pointers too: http://www.brunningonline.net/simon/blog/archives/001627.html http://lazycat.org/backburner.html http://mail.python.org/pipermail/python-win32/2007-February/005506.html Mike From jjl at pobox.com Thu Jul 5 18:49:22 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 05 Jul 2007 22:49:22 GMT Subject: deliberate versus os socket timeout References: Message-ID: <87odiqxy8d.fsf@pobox.com> Robin Becker writes: > While messing about with some deliberate socket timeout code I got an > unexpected timeout after 20 seconds when my code was doing > socket.setdefaulttimeout(120). > > Closer inspection revealed that this error in fact seemed to come from > the os (in this case windows xp). > > By inspection of test cases the error.reason from the deliberate > socket timeout looks like > 'timed out' > whereas the windows caused timeout error.reason looks like > '(10060 operation timed out)' > > it would be nice to know if that is in fact true and whether there is > any way to do the attribution of errors more sensibly. What do you mean "is in fact true"? Is what true? That the reason is always formatted in those ways when those particular errors occur? Not sure there's any reason to rely on that: I'd expect .reason to be an exception object, so (reading the docs for module socket) e.reason.args[0] should be the error code if one is available, in this case errno.ETIMEDOUT (i.e. WSAETIMEDOUT, which means the timeout occurred before a connection was established). Sometimes e.reason.args will be length-1, and e.reason.args[0] will be a string, again according to the docs for module socket. > Both of these seem to cause urllib2.URLError and presumably appear > somewhere in the socket code. > > It might be nice if the deliberate timeout could be something like > timed out deliberately after xxx seconds'. By "deliberate timeout", you mean the one you asked for by calling socket.setdefaulttimeout(). In that case, I think e.reason will be a socket.timeout instance (as opposed to socket.error in the WSAETIMEOUT case). > More importantly is there anything I can do to avoid these wrong os > inspired timeouts? I'm just using urllib2 to read from a remote site [...] Please define "wrong" ;-) Googling suggests Windows doesn't let you configure its connect timeout, except through a registry setting: http://www.tech-archive.net/Archive/VC/microsoft.public.vc.language/2005-09/msg00918.html John From python27email at yahoo.com Sat Jul 14 01:21:19 2007 From: python27email at yahoo.com (python27email at yahoo.com) Date: Fri, 13 Jul 2007 22:21:19 -0700 Subject: installation problems on mac powerpc Message-ID: <1184390479.885895.179720@q75g2000hsh.googlegroups.com> interested in nltk installation on a mac osx 10.4.9 however when try to install latest python get error cannot access subprocesses and won't even open idle got nltk to open through a terminal but entire process I fear is fragmented is there a better walk through of installation than what I've found on sourceforge? Any suggestions? From saint.infidel at gmail.com Tue Jul 3 14:16:58 2007 From: saint.infidel at gmail.com (infidel) Date: Tue, 03 Jul 2007 11:16:58 -0700 Subject: Help building GUI with Tix - solution In-Reply-To: <1183485858.701630.289830@d30g2000prg.googlegroups.com> References: <1183485858.701630.289830@d30g2000prg.googlegroups.com> Message-ID: <1183486618.449641.272840@e9g2000prf.googlegroups.com> I figured it out after finding an example somewhere: >>> import Tix >>> app = Tix.Tk("Demo") >>> panes = Tix.PanedWindow(app) >>> left = panes.add('left') >>> right = panes.add('right') >>> tree = Tix.Tree(left) >>> notebook = Tix.NoteBook(right) >>> tree.pack() >>> notebook.pack() >>> panes.pack() >>> app.mainloop() From jjl at pobox.com Tue Jul 10 19:00:31 2007 From: jjl at pobox.com (John J. Lee) Date: Tue, 10 Jul 2007 23:00:31 GMT Subject: Purpose of delayload in cookielib.FileCookieJar? References: <1184027807.876169.44100@k79g2000hse.googlegroups.com> Message-ID: <877ip7g8z4.fsf@pobox.com> "rrenaud at gmail.com" writes: > What is the reason for delayload=False in the FileCookieJar.__init__ > function? It doesn't seem to be used in any of the code that ships > with python2.4, That is true, as is in fact explicitly documented: http://docs.python.org/lib/cookie-jar-objects.html """ delayload If true, load cookies lazily from disk. This attribute should not be assigned to. This is only a hint, since this only affects performance, not behaviour (unless the cookies on disk are changing). A CookieJar object may ignore it. None of the FileCookieJar classes included in the standard library lazily loads cookies. """ Of the CookieJar implementations I know of (i.e. the ones I wrote), only MSIECookieJar takes notice of .delayload . That class is not included with the stdlib. > and it seems to directly contradict the comment > following it > > """ > Cookies are NOT loaded from the named file until either > the .load() or > .revert() method is called. > > """ > > which sounds like exactly the opposite the delayload=False default. The .load() and .revert() methods do cause the cookies to be loaded: if you don't call one of them, the CookieJar won't see the cookies; if you do call one of them, the CookieJar will see them (but see below re iteration). .delayload simply changes the way that loading is implemented. The reason for delayload's existence is that MSIE stores cookies in such a way (one cookie per file, or something; I forget now) that loading all of them at once can be slow. So MSIECookieJar only *actually* loads those it needs to keep the server happy -- but code using that cookie jar doesn't need to know that; as far as it's concerned, those cookies are loaded, and that's that. One sort-of-exception: Note this extract from the MSIECookieJar docstring: """ Iterating over a delayloaded MSIECookieJar instance will not cause any cookies to be read from disk. To force reading of all cookies from disk, call read_all_cookies. Note that the following methods iterate over self: clear_temporary_cookies, clear_expired_cookies, __len__, __repr__, __str__ and as_string. """ It's quite rare to care about that, since usually you'll just be passing the CookieJar instance to urllib2.HTTPCookieProcessor or similar, in order to send and receive cookies over HTTP, which does not require iteration over all cookies. Adding an explicit note about iteration to the docs for .delayload would be good, though. Perhaps I'll file a patch. The other exception of course is that .delayload determines whether you'll see updates to cookies that change between the .load() / .revert() call and the time the CookieJar actually decides to read the relevant file (this is already explicitly pointed out in the docs). John From ladynikon at gmail.com Thu Jul 26 14:29:53 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Thu, 26 Jul 2007 14:29:53 -0400 Subject: Fwd: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: <611885.63070.qm@web36213.mail.mud.yahoo.com> References: <4b490f2f0707260810qe4a410co366291a6dccd4f01@mail.gmail.com> <611885.63070.qm@web36213.mail.mud.yahoo.com> Message-ID: <59f9c5160707261129q24a4bfc0jfa1870cab4fdeb35@mail.gmail.com> Wow.. How about we let this die now? This isn't Perl its python. Let it die there. Danyelle From kirk at strauser.com Fri Jul 6 17:40:08 2007 From: kirk at strauser.com (Kirk Strauser) Date: Fri, 06 Jul 2007 16:40:08 -0500 Subject: Auto-parallelizing with decorators? References: Message-ID: In article , Kirk Strauser wrote: > I was thinking about how a lot of Lisp proponents claim that Lisp is > inherently parallelizable because its functions don't have (or are not > supposed to have) side effects, and therefore the compiler can easily tell > which calls may be run in parallel instead of strictly serially. I'm not a > Lisp expert so I can't say whether that's true or not, but it seems like an > interesting idea for Python. By the way, I uploaded a sample implementation (in Python) of what I had in mind to http://www.honeypot.net/multi-processing-map-python . Please let me know what you think of it and whether it seems remotely interesting or goofy. -- Kirk Strauser From josiah.carlson at sbcglobal.net Fri Jul 27 00:10:38 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Fri, 27 Jul 2007 04:10:38 GMT Subject: How to tell when a socket is closed on the other end? In-Reply-To: References: <1185371863.622473.205010@19g2000hsx.googlegroups.com> Message-ID: <2feqi.29127$2v1.12644@newssvr14.news.prodigy.net> Jay Loden wrote: > Roy Smith wrote: >> In article <1185371863.622473.205010 at 19g2000hsx.googlegroups.com>, >> billiejoex wrote: >> >>> Hi there. >>> I'm setting up test suite for a project of mine. >>> >From test suite, acting as a client, I'd like to know, in certain >>> situations, if the socket is closed on the other end or not. >>> I noticed that I can "detect" such state if a call to socket.read() >>> returns 0 but it seems a little poor to me. :-\ >>> Is there a reliable way to test such socket 'state'? >> This isn't really a Python question, it's a Berkeley Socket API question. >> You don't say, but I assume you're talking about a TCP (i.e. SOCKSTREAM) >> connection? >> >> The answer is you can use the select() system call to detect "exceptional >> conditions" on a socket. Python's select module provides this >> functionality, but to understand how to use it, you need to study the >> underlying API. > > Thanks for the interesting information and suggestion of using select(). You are correct that this is actually mostly a socket API question but pertains to Python since the code is all Python's socket and asyncore modules. It might help to step back and explain the original problem. The goal of this portion of the test suite we are writing for the project is to determine if a remote server is behaving properly by closing a socket from the server side based on a client-side command. > > Really what's needed is a way to make sure the socket gets closed, and preferably determine if it was closed from the remote end as expected. Do you know if this is possible to determine from the client side reliably/accurately? Would select()'s exceptional condition flag actually indicate whether or not the root cause of the condition was a socket closed by the remote peer? I've read through the select's manpage and I can't seem to find a reference that indicates what the possible values are for the I/O descriptor sets returned by select. Is there another man page, or a place in the header file for select I can look? Use select to determine if the socket is readable and writable. If it is, yet you can't send or receive to/from it, then it is closed. - Josiah From rcdailey at gmail.com Fri Jul 13 15:22:43 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 13 Jul 2007 19:22:43 -0000 Subject: Pass by reference or by value? In-Reply-To: <1184353832.314694.228270@n60g2000hse.googlegroups.com> References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> Message-ID: <1184354563.861992.119070@22g2000hsm.googlegroups.com> On Jul 13, 2:10 pm, Robert Dailey wrote: > Hi, > > I noticed in Python all function parameters seem to be passed by > reference. This means that when I modify the value of a variable of a > function, the value of the variable externally from the function is > also modified. > > Sometimes I wish to work with "copies", in that when I pass in an > integer variable into a function, I want the function to be modifying > a COPY, not the reference. Is this possible? > > Thanks. Correction: I ran a few more tests and python actually does a pass by value, meaning that a "copy" is made and the external variable that was passed in remains unchanged. I actually want to know how to "pass by reference", in that any changes made to a parameter inside of a function also changes the variable passed in. Thanks. From martin at v.loewis.de Fri Jul 6 04:51:07 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 06 Jul 2007 10:51:07 +0200 Subject: Writing a read only attribute In-Reply-To: References: Message-ID: <468E027B.4010107@v.loewis.de> > root = Tk() > > # save call address > original_tk_call = root.tk.call > > # disable tcl command execution (this is the read-only attribute) > root.tk.call = tk_dummy_call > > ... some code ... > > # restore tcl command execution > root.tk.call = original_tk_call > > > My goal is to make instances of Tkinter widgets without the effects of > commands directed to the tcl interpreter but preserving all effects at > python level. You can try to put in a fake Tk object into root.tk, as root.tk is not read-only. However, I would expect you run into other problems trying to do so. To change root.tk.call, you need to modify the implementation of the _tkinter module. Regards, Martin From samwyse at gmail.com Sat Jul 7 17:33:48 2007 From: samwyse at gmail.com (samwyse) Date: Sat, 07 Jul 2007 21:33:48 -0000 Subject: Re-raising exceptions with modified message In-Reply-To: <1183842825.057867.169710@q75g2000hsh.googlegroups.com> References: <1183842825.057867.169710@q75g2000hsh.googlegroups.com> Message-ID: <1183844028.501781.266230@g4g2000hsf.googlegroups.com> On Jul 7, 4:13 pm, samwyse wrote: > On Jul 5, 8:53 am, Christoph Zwerschke wrote: > > > What is the best way to re-raise any exception with a message > > supplemented with additional information (e.g. line number in a > > template)? [...] > That leaves the issue of the name being changed for > UnicodeDecodeError, which might be fixable by diddling with __name__ > properties. Or perhaps SorryEx needs to be a factory that returns > exception classes; the last line would be "SorryEx(e)()". I'll have > to play with this a bit. OK, the following mostly works. You probably want the factory to copy more of the original class into the SorryEx class each time, since someone catching an exception may expect to look at things besides its string representation. def SorryFactory(e): class SorryEx(Exception): def __init__(self): self._e = e def __getattr__(self, name): return getattr(self._e, name) def __str__(self): return str(self._e) + ", sorry!" SorryEx.__name__ = e.__class__.__name__ return SorryEx def test(code): try: code() except Exception, e: try: raise e.__class__, str(e) + ", sorry!" except TypeError: raise SorryFactory(e)() test(lambda: unicode('\xe4')) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jul 2 16:03:23 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 02 Jul 2007 22:03:23 +0200 Subject: subprocess -- broken pipe error References: <1183396350.429008.185200@n2g2000hse.googlegroups.com> <1183397577.959518.264230@g4g2000hsf.googlegroups.com> <1183403782.214378.270510@m36g2000hse.googlegroups.com> Message-ID: <5et40bF399q8uU2@mid.individual.net> 7stud wrote: > Why doesn't the following program write to the file? > [...] > It just hangs, and then when I hit Ctrl+C and look in the file, > the data isn't in there. I suppose your running child process isn't closed cleanly if you terminate the parent process. Also, the pipe may be unbuffered by default; file access isn't. Regards, Bj?rn -- BOFH excuse #384: it's an ID-10-T error From seerdecker at gmail.com Mon Jul 16 19:38:00 2007 From: seerdecker at gmail.com (seerdecker at gmail.com) Date: Mon, 16 Jul 2007 16:38:00 -0700 Subject: Semantics of file.close() In-Reply-To: <1184628945.314844.53300@k79g2000hse.googlegroups.com> References: <1184628945.314844.53300@k79g2000hse.googlegroups.com> Message-ID: <1184629080.986204.178380@q75g2000hsh.googlegroups.com> Sorry for the bad formatting; I've had to post this through the google groups. From urbangabo at gmail.com Tue Jul 10 08:10:40 2007 From: urbangabo at gmail.com (Gabor Urban) Date: Tue, 10 Jul 2007 14:10:40 +0200 Subject: Dynamic method Message-ID: Hi guys..... I have an issue I think Python could handle. But I do not have the knowledge to do it. Suppose I have a class 'myClass' and instance 'var'. There is function 'myFunc(..)'. I have to add (or bind) somehow the function to the class, or the instance. Any help, info or point of reference is wellcome.... Thx in advance, G -------------- next part -------------- An HTML attachment was scrubbed... URL: From jldunn2000 at googlemail.com Thu Jul 12 06:33:03 2007 From: jldunn2000 at googlemail.com (loial) Date: Thu, 12 Jul 2007 10:33:03 -0000 Subject: variable naming query Message-ID: <1184236383.691966.56530@w3g2000hsg.googlegroups.com> I'ma a newbie python user and would like clarification on variable naming conventions. What is the difference between self.myvariable self._myvariable self.__myvariable and when should I use each of them? From fdu.xiaojf at gmail.com Mon Jul 16 07:49:15 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Mon, 16 Jul 2007 19:49:15 +0800 Subject: questions about functions inside a function Message-ID: <469B5B3B.8040901@gmail.com> I want to create a list of function. Here is my code: In [9]: a = [] In [10]: for i in range(4): ....: b = lambda : i**2 ....: a.append(b) ....: ....: In [11]: for f in a: ....: f() ....: ....: 9 9 9 9 What I want is, the value of i should be bounded to the anonymous function. And the output should like this: for f in a: print f() 0 1 4 9 How to achieve this? Thanks a lot! From daniel at zelisko.net Sun Jul 1 15:28:03 2007 From: daniel at zelisko.net (Drex) Date: Sun, 01 Jul 2007 12:28:03 -0700 Subject: how to send files via bluetooth with python to a mobile In-Reply-To: <5eq94iF3a5b8bU1@mid.uni-berlin.de> References: <1183294323.556314.293860@m36g2000hse.googlegroups.com> <1183305873.736724.116680@c77g2000hse.googlegroups.com> <1183306850.712226.313800@m36g2000hse.googlegroups.com> <1183310919.771396.268760@q69g2000hsb.googlegroups.com> <5eq94iF3a5b8bU1@mid.uni-berlin.de> Message-ID: <1183318083.452427.318580@g4g2000hsf.googlegroups.com> Hello, > > Wrap this > > http://www.zuckschwerdt.org/apidocs/ > > using ctypes. thanks, no idea on how to do it (yet hopefully), but I will try ;) regards dz From noamtm at gmail.com Wed Jul 4 04:08:56 2007 From: noamtm at gmail.com (noamtm) Date: Wed, 04 Jul 2007 08:08:56 -0000 Subject: ignoring a part of returned tuples Message-ID: <1183536536.324939.236910@c77g2000hse.googlegroups.com> Hi, Some functions, like os.walk(), return multiple items packed as a tuple: for (dirpath, dirnames, filenames) in os.walk(...): Now, if you don't care about one of the tuple members, is there a clean way to ignore it, in a way that no unused variable is being created? What I wanted is: for (dirpath, , filenames) in os.walk(...): But that doesn't work. Thanks, Noam. From missive at frontiernet.net Fri Jul 13 18:57:01 2007 From: missive at frontiernet.net (Lee Harr) Date: Fri, 13 Jul 2007 22:57:01 GMT Subject: newbie question on def, passing param's help References: Message-ID: <1rTli.12069$ya1.10960@news02.roc.ny> > I have a def that I have been using but I realized that sometimes I need a LIST with > 5 or 6 brands instead of 4 so I want to put LIST outside of the def but I can't wrap > my head around a way to get LIST outside the def while still passing the same 4 > parameters in the function. I'm sure there is probably a simple answer but I can't > seem to think of it. > Here is what I want: > > > LIST=((row,base,lastcol,"A13","013"),(row,base,lastcol-1,"A14","014"),(row,base,lastcol-2,"A15","015"),(row,base,lastcol-3,"A16","016"), #brand1 > (row+20,base+20,lastcol,"A9","09"),(row+20,base+20,lastcol-1,"A10","010"),(row+20,base+20,lastcol-2,"A11","011"),(row+20,base+20,lastcol-3,"A12","012"),#brand2 > (row+40,base+40,lastcol,"A5","05"),(row+40,base+40,lastcol-1,"A6","06" ), (row+40,base+40,lastcol-2,"A7","07" ), (row+40,base+40,lastcol-3,"A8","08" ), #brand3 > (row+60,base+60,lastcol,"A1","01"),(row+60,base+60,lastcol-1,"A2","02" ), (row+60,base+60,lastcol-2,"A3","03" ), (row+60,base+60,lastcol-3,"A4","04" ), #brand4 > (row+80,base+80,lastcol,"A1","01"),(row+80,base+80,lastcol-1,"A2","02" ), (row+80,base+80,lastcol-2,"A3","03" ), (row+80,base+80,lastcol-3,"A4","04" )) #brand5 How about if you make this a separate function, and return the list (actually, what you have here is a tuple) that you want: def excells(row, base, lastcol): thelist = ((row, base, lastcol, "A13", "013"), ... return thelist The function might even take other parameters that tell whether to return 4, 5, or 6 brands. > def attributesbyID(row,base,slideID,spreadsheet): > sh = wb.Worksheets (spreadsheet) > sh.Select() > ########################################################## > ################ POWERPOINT SECTION ###################### lastcol = ?????? LIST = excells(row, base, lastcol) > for shape in WB.Slides.FindBySlideID(slideID).Shapes: > if (shape.Type== 7): > for oROW,oBASE,oCOL,oCELL,oHEADERCELL in LIST: > oVALUE = sh.Cells(oROW,oCOL).Value > oHEADER = sh.Cells(4,oCOL).Value + " (n=" + str(int(sh.Cells(oBASE,oCOL).Value)) + ")" > PWB = WB.Slides.FindBySlideID(slideID).Shapes(shape.Name) > oGraph = PWB.OLEFormat.Object > oGraph.Application.datasheet.Range(oCELL).Value = oVALUE > oGraph.Application.datasheet.Range(oHEADERCELL).Value = oHEADER > > ########################################################### > del oGraph > attributesbyID(14,12,31,"Attributes") # attr1 From semanticist at gmail.com Wed Jul 11 19:37:05 2007 From: semanticist at gmail.com (Miles) Date: Wed, 11 Jul 2007 16:37:05 -0700 Subject: Where does str class represent its data? In-Reply-To: <1184196082.903895.176020@n60g2000hse.googlegroups.com> References: <1184196082.903895.176020@n60g2000hse.googlegroups.com> Message-ID: <1184197025.491866.88110@r34g2000hsd.googlegroups.com> On Jul 11, 7:21 pm, ChrisEdge... at gmail.com wrote: > I'd like to implement a subclass of string that works like this: > > >>>m = MyString('mail') > >>>m == 'fail' > True > >>>m == 'mail' > False > >>>m in ['fail', hail'] > > True > > My best attempt for something like this is: > > class MyString(str): > def __init__(self, seq): > if self == self.clean(seq): pass > else: self = MyString(self.clean(seq)) > > def clean(self, seq): > seq = seq.replace("m", "f") > > but this doesn't work. Nothing gets changed. > > I understand that I could just remove the clean function from the > class and call it every time, but I use this class in several > locations, and I think it would be much safer to have it do the > cleaning itself. Since strings are immutable, you need to override the __new__ method. See http://www.python.org/download/releases/2.2.3/descrintro/#__new__ From tylerca at jeld-wen.com Fri Jul 27 17:08:47 2007 From: tylerca at jeld-wen.com (tylerca at jeld-wen.com) Date: Fri, 27 Jul 2007 21:08:47 -0000 Subject: Process Control Help Message-ID: <1185570527.665048.48780@e9g2000prf.googlegroups.com> I'm attempting to start some process control using Python. I've have quite a bit of literature on networking, and have made some tinkering servers and clients for different protocols HTTP, FTP, etc... But now it's time for the murky web of industrial protocol. I'm looking to start with IO and servo controls via Ethernet. Questions: Is there an existing forum on this already? What protocols are the most python friendly? i.e. are transparent enough that i can create my own python driver. (or do these drivers exist?) What ethernet accesible servo and IO industrial devices have people had success with? From bdesth.quelquechose at free.quelquepart.fr Sat Jul 14 00:46:06 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 14 Jul 2007 06:46:06 +0200 Subject: Pass by reference or by value? In-Reply-To: <1184354563.861992.119070@22g2000hsm.googlegroups.com> References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> <1184354563.861992.119070@22g2000hsm.googlegroups.com> Message-ID: <4697e44a$0$29005$426a34cc@news.free.fr> Robert Dailey a ?crit : > On Jul 13, 2:10 pm, Robert Dailey wrote: > >>Hi, >> >>I noticed in Python all function parameters seem to be passed by >>reference. (snip) > > Correction: > > I ran a few more tests and python actually does a pass by value, (snip) Still wrong !-) Python passes references to objects, but the *names* are local. So while *mutating* (ie: calling a method that changes the state of) an object in a function will impact the object outside the function, *rebinding* a name will not impact the name outside the function. But anyway, as Star mentionned, Ben Finney gave a pretty good (IMHO) explanation in the nearby thread named "understanding python functions". From dave at boost-consulting.com Wed Jul 4 09:59:24 2007 From: dave at boost-consulting.com (David Abrahams) Date: Wed, 04 Jul 2007 09:59:24 -0400 Subject: Proposal: s1.intersects(s2) Message-ID: <87sl84l16r.fsf@grogan.peloton> Here's an implementation of the functionality I propose, as a free-standing function: def intersects(s1,s2): if len(s1) < len(s2): for x in s1: if x in s2: return True else: for x in s2: if x in s1 return True return False Right now, the only convenient thing to do is if s1 & s2 ... but that builds a whole new set. IMO that query should be available as a method of set itself. -- Dave Abrahams Boost Consulting http://www.boost-consulting.com The Astoria Seminar ==> http://www.astoriaseminar.com From python at jayloden.com Sun Jul 1 23:08:02 2007 From: python at jayloden.com (Jay Loden) Date: Sun, 01 Jul 2007 23:08:02 -0400 Subject: Reversing a string In-Reply-To: <1i0kuau.pvs4131kz0oelN%aleax@mac.com> References: <1182997438.541012.54100@o61g2000hsh.googlegroups.com> <1i0kuau.pvs4131kz0oelN%aleax@mac.com> Message-ID: <46886C12.2080605@jayloden.com> Alex Martelli wrote: > since what you're doing is...: > >>>> s = "onomatopoeia" >>>> s = s.join(s[::-1]) >>>> s > 'aonomatopoeiaionomatopoeiaeonomatopoeiaoonomatopoeiaponomatopoeiaoonoma > topoeiatonomatopoeiaaonomatopoeiamonomatopoeiaoonomatopoeianonomatopoeia > o' > > ...which isn't really just reversing the string, but quite a bit more > work!-) That's what I get for copying and pasting from the post preceding mine and not actually checking it for what it does ;) From jjl at pobox.com Sun Jul 8 10:59:50 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 08 Jul 2007 14:59:50 GMT Subject: Pretty Printing Like Tidy for HTML References: <1183833340.610662.197060@o11g2000prd.googlegroups.com> Message-ID: <87ejjjlz4p.fsf@pobox.com> David writes: > Is there a pretty printing utility for Python, something like Tidy for > HTML? > > That will change: > > xp=self.uleft[0]+percentx*(self.xwidth) > > To: > > xp = self.uleft[0] + percentx * (self.xwidth) > > And other formatting issues. Googled and found these; no idea if they're any good (latter is commercial): http://cheeseshop.python.org/pypi/PythonTidy/1.11 http://python.softalizer.com/ See also: http://svn.python.org/view/python/trunk/Tools/scripts/reindent.py?view=log John From rbonvall at gmail.com Fri Jul 20 19:30:50 2007 From: rbonvall at gmail.com (Roberto Bonvallet) Date: Fri, 20 Jul 2007 23:30:50 -0000 Subject: Sorting dict keys In-Reply-To: References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> Message-ID: <1184974250.041481.316970@n60g2000hse.googlegroups.com> On 20 jul, 18:50, Alex Popescu wrote: > If you just want to iterate over your dict in an ordered manner than all > you have to do is: > > for k in my_dict.keys().sort(): > # rest of the code sort() returns None, so this code won't work either. -- Roberto Bonvallet From software at ginstrom.com Tue Jul 10 18:49:29 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Wed, 11 Jul 2007 07:49:29 +0900 Subject: win32com ppt embedded object In-Reply-To: Message-ID: <20070710224859643.PEYO.13519.emta104.odn.ne.jp@mta104.odn.ne.jp> > On Behalf Of Lance Hoffmeyer > for Z in WB.Slides(29).Shapes: > if (Z.Type== 7): > ZZ=Z.OLEFormat.Object > WSHEET = ZZ.Worksheets(1) > WSHEET.Range("A1").Value = .50 > WSHEET.Range("A1").NumberFormat="0%" I think you need to call Activate on your OLE object. Here is some code I use to extract the text from an Excel worksheet embedded in a PowerPoint slide. Maybe you can adapt it to your purposes. def extract_excel_text( shape ): """Process embedded excel worksheet in the powerpoint slide """ format = shape.OLEFormat format.Activate() excel = format.Object sheet = excel.ActiveSheet for row in sheet.UsedRange.Value: for cell in row: if cell: yield cell for shape in sheet.Shapes: try: # We need to give a range of characters, # # but we can take advantage of the fact that texboxes # # have a maximum length of 255 characters # yield shape.TextFrame.Characters(1,255).Text except com_error, details: log_error( "Exception getting shape text", details ) Regards, Ryan -- Ryan Ginstrom From martin at v.loewis.de Tue Jul 31 16:30:04 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 31 Jul 2007 22:30:04 +0200 Subject: Subprocess and pipe-fork-exec primitive In-Reply-To: References: Message-ID: <46af9bcc$0$17509$9b622d9e@news.freenet.de> > 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 rvanroode at gmail.com Tue Jul 10 21:06:04 2007 From: rvanroode at gmail.com (rvr) Date: Wed, 11 Jul 2007 01:06:04 -0000 Subject: stripping the first byte from a binary file In-Reply-To: References: <1184063032.195000.25880@i13g2000prf.googlegroups.com> Message-ID: <1184115964.912526.273780@e16g2000pri.googlegroups.com> On Jul 10, 6:37 pm, Jeremy Sanders wrote: > rvr wrote: > > Would someone mind showing me how to strip the first byte from a > > binary file? For some reason I can't figure this out from the binary > > file editing examples I've read. Thanks. > > Do you mean something like this? > > f = open('test.dat', 'rb') > f.read(1) # read 1st byte and ignore it > rest = f.read() # read rest > > or > > data = f.read() > data = data[1:] # skip 1st byte Is there a way to edit the file in place? The best I seem to be able to do is to use your second solution to read the file into the string, then re-open the file for writing and put the whole thing back (minus the first byte). Thanks. ~rvr From nagle at animats.com Mon Jul 9 01:56:48 2007 From: nagle at animats.com (John Nagle) Date: Mon, 09 Jul 2007 05:56:48 GMT Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xir8us3hm.fsf@ruckus.brouhaha.com> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <5engo8F38jdgaU1@mid.uni-berlin.de> <4686b9b0$0$27140$426a74cc@news.free.fr> <5epe7aF39ugprU1@mid.uni-berlin.de> <7xir8us3hm.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Diez B. Roggisch" writes: > >>>Which implies that even in ADA, runtime type errors are in fact >>>expected - else there would be no handler for such a case. >> >>Well, yes, runtime errors occur - in statically typed languages as >>well. That's essentially the halting-problem. > > > Well, no, it's quite possible for a language to reject every program > that has any possibility of throwing a runtime type error. The > halting problem implies that no algorithm can tell EXACTLY which > programs throw errors and which do not. So the language cannot accept > all programs that are free of runtime type errors and reject all > programs that definitely have runtime type errors, with no uncertain > cases. But it's fine for a language to reject uncertain cases and > accept only those which it can rigorously demonstrate have no type > errors. That's correct. Speaking as someone who once implemented an automatic proof of correctness system (here's the manual: http://www.animats.com/papers/verifier/verifiermanual.pdf), the halting problem isn't an issue. If you write a program for which halting is undecidable, the program is basically broken. The way you prove loop termination in the real world is to define some integer value (you can also use tuples like (1,2,1,3), like paragraph numbers) that gets smaller each time you go through the loop, but never goes negative. Most type issues can be resolved at compile time if you can see the whole program. John Nagle From wbrehaut at mcsnet.ca Sat Jul 14 01:43:29 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Fri, 13 Jul 2007 23:43:29 -0600 Subject: Understanding python functions - Instant Python tutorial References: <4697AB4F.80708@freakmail.de> Message-ID: <8jog9314ih8rr1g2pi9903lh4ap85hho31@4ax.com> On Sat, 14 Jul 2007 03:18:43 +0200, Wildemar Wildenburger wrote: >Wayne Brehaut wrote: >>> (had to be a semicolon there) >>> >> >> Not "had to be" since a discerning reader will note that the two >> values in the list: >> >> >>> id(x), id(y) >> (19105872, 19091664) > >Weeeell, as long as we are nitpicking: That's a tuple, not a list. Yeah, just wanted to see if you'd catch it! w >;) >/W From i3dmaster at gmail.com Sun Jul 8 05:01:52 2007 From: i3dmaster at gmail.com (i3dmaster) Date: Sun, 8 Jul 2007 02:01:52 -0700 Subject: Timing a python program run In-Reply-To: <1183836101.040882.56080@i38g2000prf.googlegroups.com> References: <1183836101.040882.56080@i38g2000prf.googlegroups.com> Message-ID: simplest way is just put a timer on start and another on the end, then calc the elapse. You can also take a look timeit module too which provides similar but more powerful functions... -Jim On Jul 7, 2007, at 12:21 PM, David wrote: > Hi, > > In matlab, I'd calculate the time for a script named test.m to run > with: > >>> tic, run, toc > > Is there some way to do this in python on a mac os x from the terminal > window? Or whatever? > > -- > http://mail.python.org/mailman/listinfo/python-list From robert.rawlins at thinkbluemedia.co.uk Sun Jul 15 15:56:02 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Sun, 15 Jul 2007 20:56:02 +0100 Subject: Access Object From 2 Applications or Fix Scheduler Message-ID: <015201c7c71a$2be05df0$83a119d0$@rawlins@thinkbluemedia.co.uk> Hello Guys, I have two applications which I need to get talking and sharing an object, what's the best way to do this? Basically my first application parses an XML document into a bunch of lists and tuples etc, and I need to access the data in these lists and tuples from my second application. Is this possible? And what's the simplest method? This problem all evolves from a hack/work around I've had to place together as I have been having problems with sched, these two applications used to be a single one to start with but for some reason when scheduling tasks using the sched module they wouldn't ever run when supposed too, so I'd schedule it to run every 2 minutes and it would run between 3 and 15 minutes :-s so I ripped it out into its own application and it now runs every 2 minutes exactly. I either need to fix my sched issues or the memory share, either way I'm quite happy, just need to get it working smoothly. Any ideas? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From cito at online.de Thu Jul 5 15:16:36 2007 From: cito at online.de (Christoph Zwerschke) Date: Thu, 05 Jul 2007 21:16:36 +0200 Subject: Proposal: s1.intersects(s2) In-Reply-To: <468cb090$0$90268$14726298@news.sunsite.dk> References: <5f1pldF3a62csU5@mid.uni-berlin.de> <468cb090$0$90268$14726298@news.sunsite.dk> Message-ID: Nis J?rgensen wrote: > The problem is, these functions can be read as "X is [consisting only > of] digit[s]", "X is lower [case]" etc, where the bits in brackets have > been removed for brewity. In the case of "s1 is intersect s2" there is > no way I can see of adding words to get a correct sentence. The > "obvious" naming is "s1.intersects(s2)" which reads as "s1 intersects > s2", a perfectly cromulent sentence. Agree. A possible alternative would be "s1.hasintersection(s2)", but s1.intersects(s2) is ok as well. -- Chris From arkanes at gmail.com Fri Jul 13 13:39:19 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 13 Jul 2007 12:39:19 -0500 Subject: Understanding python functions - Instant Python tutorial In-Reply-To: References: <878x9kkeif.fsf@benfinney.id.au> Message-ID: <4866bea60707131039l6d2027a9q5f0909f1c2e4b0@mail.gmail.com> On 7/13/07, Chris Carlen wrote: > Ben Finney wrote: > > Chris Carlen writes: > > That's not how Python works. Every value is an object; the assignment > > operator binds a name to an object. This is more like writing the name > > on a sticky-note, and sticking it onto the object. > > > > * The object itself doesn't change or "move". > > > > * The object can be referred to by that name, but isn't "inside" the > > name in any way. > > > > * Assigning multiple names to the same object just means you can > > refer to that same object by all those names. > > > > * When a name goes away, the object still exists -- but it can't be > > referred to if there are no longer any names left on it. > > > > * Assigning a different object to an existing name just means that > > the same sticky-note has moved from the original object to the new > > one. Referring to the same name now references a different object, > > while the existing object keeps all the other names it had. > > Excellent description. This understandable to me since I can envision > doing this with pointers. But I have no idea how Python actually > implements this. It also appears that I am being guided away from > thinking about it in terms of internal implementation. > I assume that you're familiar with the general concept of hash tables. Scopes in Python are hash tables mapping strings to Python objects. Names are keys into the hash table. a = 10 is the same as currentScope["a"] = 10 print a is the same as print currentScope["a"] As you can see, there's no way that assignment can result in any sort of sharing. The only way that changes can be seen between shared objects is if they are mutated via mutating methods. Python objects (the values in the hashtable) are refcounted and can be shared between any scope. > > When you pass an object as a parameter to a function, the object > > receives a new sticky-label: the parameter name under which it was > > received into the function scope. Assignment is an act of binding a > > name to an object; no new object is created, and it still has all the > > other names it had before. > Each scope is it's own hashtable. The values can be shared, but not the keys. When you call a function, the objects (retrieved from the callers local scope by name) are inserted into the functions local scope, bound to the names in the function signature. This is what Guido calls "call by object reference". > Ok, so I can understand the code above now. > > In the first case I pass the reference to the list to change(). In the > function, some_list is another name referring to the actual object > [1,2,3]. Then the function changes the object referred to by the second > element of the list to be a 4 instead of a 2. (Oh, the concept applies > here too!) Out of the function, the name x refers to the list which has > been changed. > > In the second case, y refers to a '1' object and when the function is > called the object 1 now gets a new reference (name) x inside the > function. But then a new object '0' is assigned to the x name. But the > y name still refers to a '1'. > > I get it. But I don't like it. Yet. Not sure how this will grow on me. > You need to learn about Pythons scoping now, not it's object passing semantics. When you're used to thinking in terms of pointers and memory addresses it can take some work to divorce yourself from those habits. From steve at holdenweb.com Wed Jul 11 08:23:32 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 11 Jul 2007 08:23:32 -0400 Subject: bool behavior in Python 3000? In-Reply-To: References: <7xzm23ygft.fsf@ruckus.brouhaha.com> Message-ID: Steven D'Aprano wrote: > On Tue, 10 Jul 2007 16:41:58 -0700, Paul Rubin wrote: > >> Steven D'Aprano writes: >>> Pretending that False and True are just "magic names" for 0 and 1 might >>> be "easier" than real boolean algebra, but that puts the cart before >>> the horse. Functionality comes first: Python has lists and dicts and >>> sets despite them not being ints, and somehow newcomers cope. I'm sure >>> they will cope with False and True not being integers either. >> Are they are aren't they? > > I'm sorry, I can't parse that sentence. > >> print 1 in [True] >> print 1 == True >> print len(set(map(type, [1, 1]))) >> print len(set(map(type, [1, True]))) > > > > But I guess that you are probably trying to make the point that True and > False are instances of a _subtype_ of int rather than ints, under the > mistaken idea that this pedantry would matter. (If this is not the case, > then I apologize for casting aspersions.) However, you may notice that I > said _integers_, which is not the same thing as ints: the Python types > int and bool are both implementations of the mathematical "integer" or > "whole number". > You can only cast aspersions in C, C# and similar languages. In Python you'd have to explicitly convert the aspersions to some other type ;-) 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 exarkun at divmod.com Thu Jul 5 15:21:13 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 5 Jul 2007 15:21:13 -0400 Subject: SMTP server w/o using Twisted framework In-Reply-To: <1183661809.613856.312100@57g2000hsv.googlegroups.com> Message-ID: <20070705192113.4947.2072493846.divmod.quotient.7519@ohm> On Thu, 05 Jul 2007 18:56:49 -0000, _spitFIRE wrote: >On Jul 5, 1:34 pm, "Jeff McNeil" wrote: >> If you just want to send mail, you should be able to use the standard >> smtplib module (http://docs.python.org/lib/module-smtplib.html). If >> your recipients are on the Internet, you would need to handle MX >> resolution yourself. >> > >How complicated is to handle the MX resolution by myself? I'm sorry >that I don't have a clue regarding that. Any pointers would be greatly >appreciated. You need to do a DNS MX lookup. There's nothing in the Python stdlib which provides this functionality. There are several libraries available which do this, though (Twisted among them ;). You can probably find them with a little googling. Beyond that, the rules for processing MX records are simple and it's not much work to pick the right host once you can do the MX lookups. Jean-Paul From nikbaer at gmail.com Tue Jul 10 12:43:57 2007 From: nikbaer at gmail.com (nik) Date: Tue, 10 Jul 2007 16:43:57 -0000 Subject: subprocess popen trouble Message-ID: <1184085837.104954.235230@n2g2000hse.googlegroups.com> I am having trouble using subprocess popen and stdin/stdout I have the following simple test application written in C++, that just echoes back the stdin. It works fine running from the command line: #include #include int main (int argc, char * const argv[]) { int currenttemp = 0; int settemp = 0; char* str; while(currenttemp < 500){ gets(str); sscanf(str, ">%d", &settemp); currenttemp = settemp; printf("<%d\n", currenttemp++); } return 0; } ###################################################### Then I have the following python code. A listener thread that waits for the output of test and the main part that creates the subprocess Popen object, passes it to the thread and then sends user input to the subprocess test. import subprocess import os, sys from threading import * import time class TempXListen(Thread): """ thread to listen for incomming messages and put them onto a shared queue, no time lost processing incoming lines """ def __init__(self, channel): """ connect internal response queue to external queue """ Thread.__init__(self) self.setDaemon(True) self._channel = channel self.start() def run(self): """ listening loop reads line off of input source puts the line into the response Q shared with parent thread sets event that parent is waiting for to indicate Q has at least 1 element """ while 1: try: response = self._channel.stdout.readline() # read input line print response except Exception, e: print 'Listener Exception: ' + str(e) print "Temp Monitor Test" tempx = subprocess.Popen('/Users/engineeringadmin/Documents/test/build/ Debug/test', \ bufsize=1, stdin=subprocess.PIPE, stdout=subprocess.PIPE, \ stderr=subprocess.PIPE) print tempx.stderr.readline() listener = TempXListen(tempx) while 1: data = sys.stdin.readline() if data != '': data = '>' + data + '\n' tempx.stdin.write(data) print data time.sleep(1) ############################################################### When I run it this is the output: Temp Monitor Test warning: this program uses gets(), which is unsafe. 45 >45 ################################################################ The subprocess is opened, because the warning is coming off of the test applications stderr, but nothing else seems to go in or out. I've been looking at a lot of examples and a lot of different postings, and can't see any mistakes in my use of subprocess. I would really appreciate it if somebody could see where I am going wrong. Thank you, Nik From haxc at btinternet.com Thu Jul 5 14:01:06 2007 From: haxc at btinternet.com (Owen) Date: Thu, 5 Jul 2007 11:01:06 -0700 Subject: Fwd: Abuse-6ca28a.pdf Message-ID: <468D31E2.6020306@allatps.com> -------------- next part -------------- A non-text attachment was scrubbed... Name: Abuse-6ca28a.pdf Type: application/pdf Size: 18216 bytes Desc: not available URL: From AnonMail2005 at gmail.com Thu Jul 19 01:35:43 2007 From: AnonMail2005 at gmail.com (AnonMail2005 at gmail.com) Date: Thu, 19 Jul 2007 05:35:43 -0000 Subject: Embedding/Extending Python in/with C++: non-static members? In-Reply-To: <1184689489.343144.178550@g37g2000prf.googlegroups.com> References: <1184593533.995878.123010@k79g2000hse.googlegroups.com> <1184689489.343144.178550@g37g2000prf.googlegroups.com> Message-ID: <1184823343.546273.253870@e9g2000prf.googlegroups.com> On Jul 17, 12:24 pm, dmoore wrote: > (I thought I'd follow up on this post so as not to send unsuspecting > readers down a hopeless path) > > duh! > > I've obviously spent too much time with dynamic languages. The problem > with what I'm trying to do is obvious: In C++ you simply can't pass > pointers to call a particular instance of a C++ class method so there > is no way to initialize the PyMethodDef with class methods instances. > In other words, there is no callback mechanism built into the language > and you are stuck with template based approaches, which obviously > don't mesh very well with the Python/C API (without SWIG, > Boost::Python etc). > > So to get a python interpreter instance to communicate with pre- > existing dynamically allocated C++ objects, it looks like I need to > implement some kind of lookup table approach. The static nature of the > Python/C API is just too cumbersome for use with multiple interpreters > and making me thing it might be better to embed just a sinlge > interpreter inside my app and use multi-process communication with > either pipes or sockets for the extra interpreters... I'm doing a similar thing, and I would imagine others are also. 1. In a python file, set up wrapper functions that the python user actually uses (e.g FunctionA). Each function corresponds to a particular C/C++ extension function that you are exposing (e.g. CFunctionA). 2. Each wrapper function takes the same number of args as the C/C++ extension function except it adds one additional argument - the interperter identifier. 3. The interpreter identifier is just a global id (e.g. an integer) that is unique for each interpreter and is set before hand. We set the id by first loading the wrapper function python file (in C/C++) and calling a predefined function that sets the id (you just pass the id as an argument to the function). 4. Now when you enter you C/C++ function you can find your object by looking it up in some predefined table using the id. What we actually do is not use an integer but instead use a void pointer which is cast appropriately once inside C/C++. This avoids the lookup. Hope that helps. From dev-random at arcor.de Thu Jul 19 03:43:02 2007 From: dev-random at arcor.de (Lutz Horn) Date: Thu, 19 Jul 2007 09:43:02 +0200 Subject: class C: vs class C(object): References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> <469f1557$0$26759$426a74cc@news.free.fr> Message-ID: Hi, On Thu, 19 Jul 2007 09:40:24 +0200, Bruno Desthuilliers wrote: > there's absolutely no reason to use it no more since "new-style" classes > can do anything "Classic" classes did and much more. IOW, don't even > bother with old-style classes. Just for the records: the new and preferred style is class C(object): ... Regards Lutz -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From http Sat Jul 21 22:22:38 2007 From: http (Paul Rubin) Date: 21 Jul 2007 19:22:38 -0700 Subject: [2.5] Regex doesn't support MULTILINE? References: Message-ID: <7xy7h9kwi9.fsf@ruckus.brouhaha.com> Carsten Haese writes: > Use an actual HTML parser such as BeautifulSoup > (http://www.crummy.com/software/BeautifulSoup/) and your life will be > much easier. BeautifulSoup is a lot simpler to use than RE's but a heck of a lot slower. I ended up having to use RE's last time I had to scrape a lot of pages. From gagsl-py2 at yahoo.com.ar Mon Jul 16 04:37:40 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jul 2007 05:37:40 -0300 Subject: How to determine which method was used in an inheritance heirarchy? References: <1184559788.712146.238190@q75g2000hsh.googlegroups.com> <1184565220.674041.270790@o61g2000hsh.googlegroups.com> <4BC3DC93-5F57-4B24-BE82-EB2D5FD679AF@myemma.com> Message-ID: En Mon, 16 Jul 2007 03:56:18 -0300, Erik Jones escribi?: > Perhaps an even better example of what I'm trying to do would be in > order (this is minus any exception handling): > > import sys > > def mytrace(frame, event, arg): > if event == 'call': > func_name = frame.f_code.co_name > > if func_name in frame.f_locals['self'].__class__.__dict__: > print frame.f_locals['self'].__class__.__name__ > else: > for base in frame.f_locals['self'].__class__.__bases__: > if func_name in base.__dict__: > print base.__name__ > break > > > class A(object): > def __init__(self): > pass > > class B(A): > def __init__(self): > A.__init__(self) > > sys.settrace(mytrace) > B() > > This will output: > > B > B If you don't mind post-processing the results, you can log the function name and source module (from frame.f_code.co_name and co_filename) and current line number (frame.f_lineno). Later, obtaining the class name from those is a bit tricky (and not even the inspect module does it right), but perhaps using the tokenizer module, watching for lines that contain "class" is enough. -- Gabriel Genellina From cornpicker at gmail.com Wed Jul 18 09:42:59 2007 From: cornpicker at gmail.com (cornpicker at gmail.com) Date: Wed, 18 Jul 2007 13:42:59 -0000 Subject: Problem with building extension in Python In-Reply-To: <1184264756.063561.259080@w3g2000hsg.googlegroups.com> References: <1183622938.086813.18950@k79g2000hse.googlegroups.com> <1184264756.063561.259080@w3g2000hsg.googlegroups.com> Message-ID: <1184766179.088588.215670@g12g2000prg.googlegroups.com> I solved my problem. I had the math.h import step in the wrong location. The import step needed to be outside of the function -- I'm so embarrassed. Code: [Download] 1. 2. # 3. # Use C math functions 4. # 5. 6. # Import the native C functions we need 7. cdef extern from "math.h": 8. double cos(double theta) 9. double sin(double theta) 10. 11. 12. def cTest(double theta): 13. 14. cdef double result[2] 15. 16. import sys 17. 18. result[0] = cos(theta) 19. result[1] = sin(theta) 20. 21. pyResult = (result[0], result[1]) 22. 23. return pyResult 24. 25. Now it works If I type the following into the python shell import cTest cTest.cTest(.775) The function returns (0.71442103405593138, 0.69971607534660352) From jeff at jmcneil.net Fri Jul 13 14:51:52 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Fri, 13 Jul 2007 14:51:52 -0400 Subject: A Python newbie ask a simple question In-Reply-To: <1184351716.298630.80670@z28g2000prd.googlegroups.com> References: <1184351716.298630.80670@z28g2000prd.googlegroups.com> Message-ID: <82d28c40707131151u5171b36emb08cc5269bdb5109@mail.gmail.com> The raw_input built-in returns a string. The '[0]' subscript returns the first character in the user supplied response as strings support indexing. [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> mystr = "asdf" >>> mystr[0] 'a' >>> >>> raw_input("Another one, please: ")[0] Another one, please: ASDF 'A' >>> -Jeff On 7/13/07, xing93111 at gmail.com wrote: > what does the statement "choice = raw_input(prompt)[0]" mean? I don't > know why there is a '[0]' in the statement. > > Thank you very much > > -- > http://mail.python.org/mailman/listinfo/python-list > From bbxx789_05ss at yahoo.com Tue Jul 24 16:56:11 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 24 Jul 2007 13:56:11 -0700 Subject: printing unicode strings Message-ID: <1185310571.173514.240940@r34g2000hsd.googlegroups.com> Can anyone tell me why I can print out the individual variables in the following code, but when I print them out combined into a single string, I get an error? symbol = u'ibm' price = u'4 \xbd' # 4 1/2 print "%s" % symbol print "%s" % price.encode("utf-8") print "%s %s" % (symbol, price.encode("utf-8") ) --output:-- ibm 4 1/2 File "pythontest.py", line 6, in ? print "%s %s" % (symbol, price.encode("utf-8") ) UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 2: ordinal not in range(128) From nick at craig-wood.com Wed Jul 18 07:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 18 Jul 2007 06:30:06 -0500 Subject: Pickled objects over the network References: <9c8d48280707171457p4448fdf3of40562bf62a18fc6@mail.gmail.com> Message-ID: Jean-Paul Calderone wrote: > On Tue, 17 Jul 2007 14:57:16 -0700, Walker Lindley wrote: > >I'm working on a distributed computing program and need to send Python > >objects over a TCP socket. [snip] > >Hopefully I'm doing something obviously wrong, but if anyone can help based > >on that description or if you need to see the source, please let me know > >(it's GPL'd). Thank you so much for any help. > > The obvious thing you're doing wrong is using pickle over a network. ;) > > http://jcalderone.livejournal.com/15864.html I'd say the obvious thing being done wrong is re-inventing the wheel. Use pyro instead... http://pyro.sourceforge.net/ Pyro does use pickle to serialise objects by default. It can use XML instead for an exploit free RPC at the cost of a bit of speed. http://pyro.sourceforge.net/manual/9-security.html#pickle -- Nick Craig-Wood -- http://www.craig-wood.com/nick From emin.shopper at gmail.com Wed Jul 18 16:40:46 2007 From: emin.shopper at gmail.com (Emin.shopper Martinian.shopper) Date: Wed, 18 Jul 2007 16:40:46 -0400 Subject: How do you debug when a unittest.TestCase fails? Message-ID: <32e43bb70707181340u7e4b545bp1f025c941b40134e@mail.gmail.com> Dear Experts, How do you use pdb to debug when a TestCase object from the unittest module fails? Basically, I'd like to run my unit tests and invoke pdb.pm when something fails. I tried the following with now success: Imagine that I have a module _test.py that looks like the following: ----------------------- import unittest class MyTest(unittest.TestCase): def testIt(self): raise Exception('boom') if __name__ == '__main__': unittest.main() ----------------------- If I do >>> import _test; _test.unittest() no tests get run. If I try >>> import _test; t = _test.MyTest() I get Traceback (most recent call last): File "", line 1, in File "c:\python25\lib\unittest.py", line 209, in __init__ (self.__class__, methodName) ValueError: no such test method in : runTest If I try >>> import _test; t = _test.MyTest(methodName='testIt'); t.run() nothing happens. Thanks, -Emin -------------- next part -------------- An HTML attachment was scrubbed... URL: From Ira.Kovac at gmail.com Fri Jul 27 05:28:27 2007 From: Ira.Kovac at gmail.com (Ira.Kovac at gmail.com) Date: Fri, 27 Jul 2007 02:28:27 -0700 Subject: Filtering content of a text file Message-ID: <1185528507.750436.91140@j4g2000prf.googlegroups.com> Hello All, I'd greatly appreciate if you can take a look at the task I need help with. It'd be outstanding if someone can provide some sample Python code. Thanks a lot, Ira ------------------------------------------------------------------------------- Problem ------------------------------------------------------------------------------- I am working with 30K+ record datasets in flat file format (.txt) that look like this: //-+alibaba sinage //-+amra damian//_9 //-+anix anire//_ //-+borom //-+bokima sun drane //-+ciren //-+cop calestieon eded //-+ciciban //-+drago kimano sole The records start with the same string (in the example //-+) wich is followed by another string of characters taht's changing from record to record. I am working on one file at the time and for each file I need to be able to do the following: a) By looping thru the file the program should isolate all records that have letter a following the //-+ b) The isolated dataset will contain only records that start with //- +a c) Save the isolated dataset as flat flat text file named a.txt d) Repeat a), b) and c) for all letters of english alphabet (a thru z) and numerical values (0 thru 9) CP: An inch of time is an inch of gold but you can't buy that inch of time with an inch of gold. Random Link Generator -------------------------------------------------- http://www.transactioncodes.com -------------------------------------------------- From fckuen at gmail.com Sun Jul 8 23:27:24 2007 From: fckuen at gmail.com (fckuen at gmail.com) Date: Mon, 09 Jul 2007 03:27:24 -0000 Subject: How to override PyGridTableBase.SetColLabelValue()? Message-ID: <1183951644.304339.243210@z28g2000prd.googlegroups.com> Dear all, the doc is missing, and i failed to find the solution on google search. anyone know how to override the function SetColLabel() inside the class PyGridTableBase or the class GridTableBase? my code, #=========================================== class MegaTable(wx.grid.PyGridTableBase): def __init__(...) ..... wx.grid.PyGridTableBase.__init__(self) def SetColLabelValue(self, col, value): value = self.coltags[col] -->how to ??? class MegaGrid(wx.grid.Grid): def __init__(...) ..... wx.grid.Grid.__init__(self, parent, id) self._table = MegaTable(self, .....) self.SetTable(self._table) ..... #=========================================== thanks! From donn at u.washington.edu Mon Jul 2 16:46:48 2007 From: donn at u.washington.edu (Donn Cave) Date: Mon, 02 Jul 2007 13:46:48 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> Message-ID: In article <1i0ikru.1uccqtm1efnzn3N%aleax at mac.com>, aleax at mac.com (Alex Martelli) wrote: > "Dynamic typing is recommended", they conclude, "when programs must be > as flexible as possible". I recommend reading the Agile Manifesto to > understand why maximal flexibility is crucial in most real-world > application programming -- and therefore why, in said real world rather > than in the more academic circles Dr. Van Roy and Dr. Hadidi move in, > dynamic typing is generally preferable, and not such a tiny issue as > they make the difference to be. I guess there may be more than one kind of flexibility. The language I fool around with sometimes that has strong static typing is Haskell. Though a relatively elementary Haskell programmer (the learning curve with this language is something you would have to experience to believe), I feel that the type checking actually helps me program faster. The compiler's check for structural correctness is after all for my benefit, and expedites development and maintenance of code, in my limited experience. The more extensive my changes, the more useful the type checking is - I'm much more casual about significant code revision when writing in Haskell, somewhat more casual when writing in C, and worried when writing Python. This is the kind of flexibility where you make significant changes to something, but the result is as structurally consistent as it would have been if written that way from the start. I have also seen the kind of flexibility where you use expedient hacks to make changes with relatively small amounts of code, and I've seen it in Python applications. It's flexibility when you're doing it, but it paradoxically causes rigidity as the hacks create more points of articulation and more things that aren't obvious to the person making the changes. If that's flexibility, you can have it. Donn Cave, donn at u.washington.edu From the.mindstorm.mailinglist at gmail.com Wed Jul 4 18:52:09 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Wed, 04 Jul 2007 15:52:09 -0700 Subject: MethodType/FunctionType and decorators Message-ID: <1183589529.198694.109440@m36g2000hse.googlegroups.com> Hi all! I am pretty new to Python, so please excuse me if I am missing something. Lately, I've been playing with decorators and I am a bit confused about some behavior. Here is the code that puzzles me: in python shell: def function(): pass class A(object): def method(self): pass from types import MethodType from types import FunctionType if type(function) is FunctionType: print "this is what I expect" if type(A.method) is MethodType: print "this is what I expect" so far so good... everything seems logical. But if a decorator is declared things are becoming different: def deco(function): if type(function) is MethodType: print "MethodType" elif type(function) is FunctionType: print "FunctionType" @deco def function2(): pass # ==> this prints out FunctionType (oke) class A(object): @deco def method(self): pass # ==> this prints out FunctionType (???) Can somebody shed some light on why I am seeing this? (Using Python 2.5.1 on Win XP). TIA, ./alex -- .w( the_mindstorm )p. From fabioztessitore at libero.it Tue Jul 31 16:16:31 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 31 Jul 2007 20:16:31 GMT Subject: Creating a shared object in python References: Message-ID: <46af989f$0$10619$4fafbaef@reader2.news.tin.it> Il Tue, 31 Jul 2007 15:37:26 -0400, Delgado, Edgardo CIV NAVAIR 4.1.4.3 ha scritto: > Is there a way to create a shared object in python? > > Thx, > > Edgar Usually object are shared in Python. i.e. # a list l = [ 1 , 2 , 3 ] # a list containing l m = [ l, 4, 5 ] # now m is [ [1,2,3] , 4 , 5 ] # ok, let's change l l[0] = 10 # now m is changed # NOW m is [ [10,2,3] , 4 , 5 ] From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jul 6 17:04:14 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 06 Jul 2007 23:04:14 +0200 Subject: ImportError: "No Module named xxx" References: <1183750316.740239.257010@m36g2000hse.googlegroups.com> <1183750738.308894.261750@c77g2000hse.googlegroups.com> Message-ID: <5f7p2eF3bm6tuU1@mid.individual.net> Robert Dailey wrote: > The description of -m is confusing in the documentation, what does > it really do? IMHO, it's quite clear. What's unclear with this description: -m module-name Searches sys.path for the named module and runs the corresponding .py file as a script. Regards, Bj?rn -- BOFH excuse #191: Just type 'mv * /dev/null'. From S.Mientki-nospam at mailbox.kun.nl Tue Jul 31 17:26:08 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 31 Jul 2007 23:26:08 +0200 Subject: Reload after an exception, not possible ? Message-ID: 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 ???? please enlighten me, thanks, Stef Mientki From bignose+hates-spam at benfinney.id.au Fri Jul 13 02:26:59 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 13 Jul 2007 16:26:59 +1000 Subject: MaildirMessage References: <1184287592.509355.310110@g4g2000hsf.googlegroups.com> Message-ID: <874pk8kedo.fsf@benfinney.id.au> "Gabriel Genellina" writes: > msg is an instance of MaildirMessage (subclass of Message) - it has > no specific iterator, so "for m in msg" tries to use the sequence > protocol, starting at 0; that is, tries to get msg[0]. Message > objects support the mapping protocol, and msg[0] tries to find a > *header* 0, converting the name 0 to lowercase, and fails miserably. Which is a bug in the 'email.message' module, in my view. If it's attempting to support a mapping protocol, it should allow iteration the same way standard Python mappings do: by iterating over the keys. -- \ "If you continue running Windows, your system may become | `\ unstable." -- Microsoft, Windows 95 BSOD message | _o__) | Ben Finney From diener896092_no_spam_here at bellsouth.net Sat Jul 7 22:30:55 2007 From: diener896092_no_spam_here at bellsouth.net (Edward Diener) Date: Sat, 07 Jul 2007 22:30:55 -0400 Subject: Getting the home directory in Python and a bug in os.path.expanduser In-Reply-To: References: <5aQji.1085$m%.196@newssvr17.news.prodigy.net> <_MRji.11911$K9.9459@bignews6.bellsouth.net> Message-ID: Neil Hodgson wrote: > Edward Diener: > >> Probably most reliable on Windows is a Windows API function, if it >> exists, for getting the home directory, as opposed to using >> environment variables, but I can not find any Windows API for it at >> present. > > Look at SHGetFolderPath(CSIDL_PROFILE, ...) for Windows Me/2000 or > later. CSIDL_APPDATA is probably a better idea than CSIDL_PROFILE (its > equivalent to "%USERPROFILE%\Application Data" and roams) but > %USERPROFILE% (CSIDL_PROFILE) is compatible with previous Python behaviour. > http://msdn2.microsoft.com/en-us/library/ms647764.aspx Thanks, that looks good. For Windows Vista one should evidently use SHGetKnownFolderPath(FOLDERID_Profile,...) instead. From tim at tdw.net Fri Jul 20 08:44:22 2007 From: tim at tdw.net (Tim Williams) Date: Fri, 20 Jul 2007 13:44:22 +0100 Subject: Gmail Error using smtplib In-Reply-To: References: Message-ID: <9afea2ac0707200544y5e377d64j3dcb019a53c58d1b@mail.gmail.com> On 20/07/07, DJ Fadereu wrote: > Hello, can anyone help me with this? What am I doing wrong here? > > (I've changed private info to yyyy/xxxxxx) > I'm getting an authentication error while using a standard script > Gmail: > --------------------------SCRIPT----------------------------- > import smtplib > from email.MIMEText import MIMEText > > msg = MIMEText('Hello, this is fadereu...') > >From = 'yyyyyyyy at gmail.com' > > msg['Subject'] = 'Hello' > msg ['From'] = 'ccccccc at gmail.com' > msg['To'] = 'fffd at xyz.com' > > s = smtplib.SMTP('alt1.gmail-smtp-in.l.google.com') > s.set_debuglevel(1) > s.login('yyyyyyyyy at gmail.com','xxxxxxxxx') > s.sendmail(msg['From'], msg['To'], msg.as_string()) > s.close() > ----------------------------ERROR------------------------------ > Traceback (most recent call last): > File "C:\Documents and Settings\Acer User\Desktop\Code\S60 scripts > \Fadereu's Codez\gmail.py", line 13, in > s.login('yyyyyyy at gmail.com','xxxxxxxxx'') > File "C:\Python25\lib\smtplib.py", line 554, in login > raise SMTPException("SMTP AUTH extension not supported by > server.") > SMTPException: SMTP AUTH extension not supported by server. > The error fairly self-explanitory :) >>SMTPException: SMTP AUTH extension not supported by server. In fact, you are trying to send outbound email through an inbound email server. You need to use GMAIL's outbound server. HTH :) From zentraders at gmail.com Fri Jul 20 19:30:57 2007 From: zentraders at gmail.com (Zentrader) Date: Fri, 20 Jul 2007 16:30:57 -0700 Subject: PDF2ODT In-Reply-To: <1184701671.321156.62040@e16g2000pri.googlegroups.com> References: <1184701671.321156.62040@e16g2000pri.googlegroups.com> Message-ID: <1184974257.008974.257910@m37g2000prh.googlegroups.com> On Jul 17, 12:47 pm, orehon wrote: > Hello, > I need to convert PDF to ODT or PDF to DOC using python! > > I was taking a look athttp://www.kde-apps.org/content/show.php/show.php?content=18638&vote=... > and this project is outdated. > > So any idea? > > Thank you! I have heard of this but have not tried it. Your best bet is to use an existing program, like OpenOffice, and call it with os.system() or one of the popen varieties if you want to do more than copy to a new file. http://freshmeat.net/projects/unoconv/ From goon12 at gmail.com Wed Jul 11 14:20:51 2007 From: goon12 at gmail.com (Joe Riopel) Date: Wed, 11 Jul 2007 14:20:51 -0400 Subject: Tuple vs List: Whats the difference? In-Reply-To: <1184177195.569916.184770@22g2000hsm.googlegroups.com> References: <1184177195.569916.184770@22g2000hsm.googlegroups.com> Message-ID: <6a2ccd190707111120p430aea00ndfec81ac2249e33c@mail.gmail.com> On 7/11/07, Shafik wrote: > I am an experienced programmer, but very new to python (2 days). I > wanted to ask: what exactly is the difference between a tuple and a > list? I'm sure there are some, but I can't seem to find a situation > where I can use one but not the other. The differences are explained pretty good on here. Although, I am pretty new to Python as well. http://diveintopython.org/native_data_types/tuples.html From vivek.kumar.gupt at gmail.com Tue Jul 3 10:11:25 2007 From: vivek.kumar.gupt at gmail.com (Vivek Kumar) Date: Tue, 3 Jul 2007 19:41:25 +0530 Subject: Fwd: Infotech Enterprises Limited In-Reply-To: <73e701c7bd67$ea1ba570$150210ac@esolutions.com> References: <73e701c7bd67$ea1ba570$150210ac@esolutions.com> Message-ID: <18b405220707030711u391f26c8p90e0f404d59698db@mail.gmail.com> ---------- Forwarded message ---------- From: Mahendra Date: Jul 3, 2007 5:17 PM Subject: Infotech Enterprises Limited To: vivek.kumar.gupt at gmail.com Hi Further to our discussions, We are looking for Python developers/ C++ who are willing to work in Hyderabad. Infotech Enterprises Limited is a CMMIL5 company with morethan 5500 professionals working in to Various domains. For further information you can logonto www.Infotech-Enterprises .com Regards Mahendra Rao.A Human Resources Team Infotech Enterprises Limited Email: mahendraraoa at infotechsw.com www.infotech-Enterprises.com Tel : 040 - 23124040 Plotno - 11; Software units Layout Madhapur Hyderabad From tazmaster at rocketmail.com Thu Jul 19 21:28:53 2007 From: tazmaster at rocketmail.com (Jim Langston) Date: Thu, 19 Jul 2007 18:28:53 -0700 Subject: Python version changes, sys.executable does not References: <139v9oe22rihh40@corp.supernews.com> Message-ID: "Jeffrey Froman" wrote in message news:139v9oe22rihh40 at corp.supernews.com... > Hello All, > > I have two python versions installed, one in /usr/bin, and one in > /usr/local/bin. However, when invoking python without a full path, > I get the wrong executable with the right sys.executable string! > ---------------------------------------------------------------------------- > [root at M1 ~]# ls -l /usr/local/bin/python* > -rwxr-xr-x 2 root root 3783810 Jul 19 09:15 /usr/local/bin/python > -rwxr-xr-x 2 root root 3783810 Jul 19 09:15 /usr/local/bin/python2.5 > -rwxr-xr-x 1 root root 1281 Jul 19 09:16 > /usr/local/bin/python2.5-config > lrwxrwxrwx 1 root root 16 Jul 19 09:16 > /usr/local/bin/python-config -> python2.5-config > > [root at M1 ~]# ls -l /usr/bin/python* > -rwxr-xr-x 2 root root 5396 May 2 16:28 /usr/bin/python > lrwxrwxrwx 1 root root 6 Jul 18 12:20 /usr/bin/python2 -> python > -rwxr-xr-x 2 root root 5396 May 2 16:28 /usr/bin/python2.3 > > [root at M1 ~]# which python > /usr/local/bin/python > > [root at M1 ~]# /usr/local/bin/python -c "import sys; print sys.executable; > print sys.version; set()" > /usr/local/bin/python > 2.5 (r25:51908, Jul 19 2007, 09:13:48) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] > > [root at M1 ~]# env python -c "import sys; print sys.executable; print > sys.version; set()" > /usr/local/bin/python > 2.5 (r25:51908, Jul 19 2007, 09:13:48) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] > > [root at M1 ~]# python -c "import sys; print sys.executable; print > sys.version; set()" > /usr/local/bin/python > 2.3.4 (#1, May 2 2007, 19:26:00) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'set' is not defined > --------------------------------------------------------------------------------- > > > On a different machine, with same setup (as far as I can tell), I get the > expected > results: > --------------------------------------------------------------------------------- > [root at M2 ~]# /usr/local/bin/python -c "import sys; print sys.executable; > print sys.version; set()" > /usr/local/bin/python > 2.5 (r25:51908, Feb 8 2007, 16:29:18) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] > > [root at M2 ~]# env python -c "import sys; print sys.executable; print > sys.version; set()" > /usr/local/bin/python > 2.5 (r25:51908, Feb 8 2007, 16:29:18) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] > > [root at M2 ~]# python -c "import sys; print sys.executable; print > sys.version; set()" > /usr/local/bin/python > 2.5 (r25:51908, Feb 8 2007, 16:29:18) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] > --------------------------------------------------------------------------------- > > Can anyone tell me what might be causing the erroneous behavior in the > first example? I think it's because your python directory is in the path before your python2.5 directory. From khemkaamit at gmail.com Fri Jul 6 03:00:01 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Fri, 6 Jul 2007 12:30:01 +0530 Subject: import In-Reply-To: <1183704647.460604.102100@e9g2000prf.googlegroups.com> References: <1183704647.460604.102100@e9g2000prf.googlegroups.com> Message-ID: <1360b7230707060000l667478ebmef914520c9341261@mail.gmail.com> On 7/6/07, jolly wrote: > Hey guys, > > I'm rather new to python and i'm have trouble(as usual) Hope it becomes un-usual with Python ! > > I want to know if it is possible to change where 'import' looks.... > this will save me clogging up my python directory Yes. You can tell python where all to look for importing modules. import sys sys.path.append("/this/is/my/modules/path") > Thanks Welcome ! cheers, -- ---- 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 mail at timgolden.me.uk Mon Jul 2 05:34:40 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 02 Jul 2007 10:34:40 +0100 Subject: ann: Python at the IET Message-ID: <4688C6B0.1000804@timgolden.me.uk> If you're in London around 6.30pm this Thursday evening, July 5th 2007, you might want to drop in on The Institution of Engineering and Technology [1] on the Embankment near Waterloo Bridge [2] for "A Light byte of Python" [3]. Michael Grazebrook, Pete Ryland and I are flying the Python flag for the benefit of technologists who have not yet had the pleasure. Michael will be using ctypes to control a USB-interfaced sensor kit; Pete will be demoing user interfaces; I'll be using BeautifulSoup and sqlite3 to populate a database from a web page and (time permitting) using csv and ReportLab to push it back out again. We're presenting the thing as a bring-a-laptop workshop, and it would be great if we had experienced Pythoneers along to help afterwards (in addition to ourselves). The take-up's been quite high for the event and there's tea & coffee beforehand and sandwiches afterwards. Tim Golden [1] http://www.theiet.org/ [2] http://www.iee.org/OnComms/Branches/UK/england/SEastE/london/Venues/savoy.cfm [3] http://www.iee.org/OnComms/Branches/UK/england/SEastE/london/Events/july.cfm From bj_666 at gmx.net Wed Jul 11 02:06:25 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 11 Jul 2007 06:06:25 GMT Subject: Simple search and Display system, no need for db? References: <1184119048.302574.141810@w3g2000hsg.googlegroups.com> Message-ID: <5fjab0F3d2eqeU1@mid.uni-berlin.de> On Wed, 11 Jul 2007 01:57:28 +0000, flit wrote: > The user goes there: > > - Choose the building -- Department and the user receive an html table > with all names . > > So the user gives two inputs and receive the names. > > Currently we are using this in mysql, This is the reason of the > debate. > > If our list will never change and we are supposing that will be true > for a long time, is it not too much use an mysql? Maybe mysql is really a bit "heavy" for this. If you still want to use an SQL DB then SQLite seems to be a candidate here. It doesn't need a server and comes with Python 2.5. SQLite doesn't handle concurrent updating of data that well, but in the given scenario there seem to be far more queries than updates. If the data is not too large, simple text files would do. Maybe in CSV format. Either with building and department as columns in the files or coded into the file name or path. Another approach would be the JSON_ format. Again, if the data is not too large one might send the whole JSON document to the client browser and use JavaScript on the client side to display and filter the name lists. Then you can slap the Web 2.0 buzz label onto the system. ;-) Ciao, Marc 'BlackJack' Rintsch From justin.mailinglists at gmail.com Wed Jul 4 04:12:43 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Wed, 04 Jul 2007 08:12:43 -0000 Subject: ignoring a part of returned tuples In-Reply-To: <1183536536.324939.236910@c77g2000hse.googlegroups.com> References: <1183536536.324939.236910@c77g2000hse.googlegroups.com> Message-ID: <1183536763.055951.256740@z28g2000prd.googlegroups.com> On Jul 4, 4:08 pm, noamtm wrote: > What I wanted is: > for (dirpath, , filenames) in os.walk(...): > > But that doesn't work. for (dirpath, _, filenames) in os.walk(...): From wildemar at freakmail.de Fri Jul 13 12:49:06 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 13 Jul 2007 18:49:06 +0200 Subject: Understanding python functions - Instant Python tutorial In-Reply-To: <4697AB4F.80708@freakmail.de> References: <4697AB4F.80708@freakmail.de> Message-ID: <4697AD02.3050605@freakmail.de> Wildemar Wildenburger wrote: > x = [1, 2, 3] > y = [1, 2, 3] > id(x), id(y) > x == y > x is y > Ooops! Make that: x = [1, 2, 3] y = [1, 2, 3] id(x); id(y) x == y x is y (had to be a semicolon there) From blake.anderton at gmail.com Tue Jul 17 21:29:27 2007 From: blake.anderton at gmail.com (BAnderton) Date: Wed, 18 Jul 2007 01:29:27 -0000 Subject: accessing javascript variables within psp code Message-ID: <1184722167.222423.273040@z28g2000prd.googlegroups.com> Hello all, Question: Is there any way to access a javascript variable from within psp code? I'm aware of how to do the reverse of this (js_var='<%=psp_var%>'). Here's a non-working example of what I'm trying to do: - - - (begin example) - - - function Test(txt) { a = confirm('Are you sure you want to delete '+txt+'?') if (a) { //The problem is getting the value of js variable 'txt' recognized in "psp space". <% os.remove( os.path.join(os.path.dirname(req.filename), '../notes/'+ %>txt<%) ) %> } } - - - (end example) - - - FYI, I've already found a workaround for the above example (by placing a "get" variable in the URL, reloading the page, and having psp check for the existence of that variable before proceeding with deleting the appropriate file) but I'd still like this general capability for future projects. I've searched several forums, websites, etc. and the answer has aluded me for two days now. I'm new to apache, mod_python, and javascript, so this may be ridiculously simple. Since this is my first post on google groups, I'd also appreciate any helpful suggestions on how to best go about getting answers quickly (so let me know if there's a more appropriate forum/method/etc.) Thanks for any help you can provide. (This is copied from a message I originally posted to the mod_python group.) From nick at craig-wood.com Tue Jul 10 09:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 10 Jul 2007 08:30:03 -0500 Subject: Should I use Python for these programs? References: Message-ID: CC wrote: > I have considerable C and assembly language experience. However, these > are mostly on embedded microcontrollers since I moved away from PC > programming all the way back in 1988 :-O > > I wish to accomplish a few PC programming tasks, and am considering to > learn Python: > > 1. Develop a simple GUI program to run on Linux and Windows which can > send parameters and small blocks of data to an embedded microcontroller > device via RS-232 or USB. Also display simple data (probably single > numbers) sent from the device. > > Note, if it is USB, then the client will be implemented by me using FTDI > chips that appear to the PC as a serial port. No problems - pyserial, wxPython work fine cross platform. You can also use libusb from python from windows and linux also for low level USB stuff. I've managed to use all those things successfully. > I would prefer to be able to write a program that is cross-platform > between Linux and Windows. I realize this might be especially > problematic with the serial comms. On the contrary, pyserial does a very good job of abstracting the serial port away. > I am also confused by the plethora of Python GUI extensions, though > Tkinter seems like a likely candidate. I am uncertain if I will have > difficulty learning how to use this if I don't know Tcl/Tk. Use wxPython would be my advice. tk is OK, but a bit clunky. it does have the advantage that it is built into the language though. > Do you think Python is the right language for these projects? Yes! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From larry.bates at websafe.com Mon Jul 23 15:23:38 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 23 Jul 2007 14:23:38 -0500 Subject: link between python and the windows command prompt In-Reply-To: <1185216281.296805.191660@q75g2000hsh.googlegroups.com> References: <1185216281.296805.191660@q75g2000hsh.googlegroups.com> Message-ID: yadin wrote: > hi! i need to know how i can run ussal commands that i ussally type at > the windows command prompt from a python file. that is for example > from the windows command prompt i ussually type "cd D:\folder\ nec2++ - > i inputfile.nec -o outputfile.out " now how can i execute this > command that i ussually type at the windows command prompt from a > python file? > i know it has to do with the sys and os module but how specifically? > what commands? any references? > You can use os.system or if your needs are more complex, take a look at the subprocess module. import os import sys os.chdir('D:\\folder') os.system('D:\\nec2++ -i inputfile.new -o outputfile.out') -Larry From rschroev_nospam_ml at fastmail.fm Sat Jul 28 18:57:01 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 28 Jul 2007 22:57:01 GMT Subject: How to stop print printing spaces? In-Reply-To: References: Message-ID: <1RPqi.20711$rB1.1018083@phobos.telenet-ops.be> CC schreef: > Hi: > > I've conjured up the idea of building a hex line editor as a first real > Python programming exercise. > > To begin figuring out how to display a line of data as two-digit hex > bytes, I created a hunk of data then printed it: > > ln = '\x00\x01\xFF 456789abcdef' > for i in range(0,15): > print '%.2X ' % ord(ln[i]), > > This prints: > 00 01 FF 20 34 35 36 37 38 39 61 62 63 64 65 > > because print adds a space after each invocation. > > I only want one space, which I get if I omit the space in the format > string above. But this is annoying, since print is doing more than what > I tell it to do. > > What if I wanted no spaces at all? Then I'd have to do something > obnoxious like: > > for i in range(0,15): > print '\x08%.2X' % ord(ln[i]), > > This works: > > import sys > for i in range(0,15): > sys.stdout.write( '%.2X' % ord(ln[i]) ) > > print > > > Is that the best way, to work directly on the stdout stream? It's not a bad idea: print is mostly designed to be used in interactive mode and for quick and dirty logging; not really for normal program output (though I often use it for that purpose). There is another way: construct the full output string before printing it. You can do that efficiently using a list comprehension and the string method join(): >>> print ''.join(['%.2X' % ord(c) for c in ln]) 0001FF20343536373839616263646566 In Python 2.4 and higher, you can use a generator expression instead of a list comprehension: >>> print ''.join('%.2X' % ord(c) for c in ln) 0001FF20343536373839616263646566 BTW, in your examples it's more pythonic not to use range with an index variable in the for-loop; you can loop directly over the contents of ln like this: import sys for c in ln: sys.stdout.write('%.2X' % ord(c)) print -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From Graham.Dumpleton at gmail.com Sun Jul 29 06:07:51 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 29 Jul 2007 10:07:51 -0000 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1185658013.859359.47700@57g2000hsv.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> <1184458002.961657.267830@x35g2000prf.googlegroups.com> <1184466882.446791.127670@x35g2000prf.googlegroups.com> <1185658013.859359.47700@57g2000hsv.googlegroups.com> Message-ID: <1185703671.241103.124780@g12g2000prg.googlegroups.com> On Jul 29, 7:26 am, 7stud wrote: > On Jul 14, 8:34 pm, Graham Dumpleton > wrote: > > > > > On Jul 15, 10:06 am, Graham Dumpleton > > wrote: > > > > On Jul 15, 2:47 am, 7stud wrote: > > > > > Themod_pythonmanual says this under section 2.1 Prerequisites: > > > > > ------ > > > > In order to compilemod_pythonyou will need to have the include files > > > > for both Apache and Python, as well as the Python library installed on > > > > your system. If you installed Python and Apache from source, then you > > > > already have everything needed. However, if you are using prepackaged > > > > software (e.g. Red Hat Linux RPM, Debian, or Solaris packages from > > > > sunsite, etc) then chances are, you have just the binaries and not the > > > > sources on your system. Often, the Apache and Python include files and > > > > libraries necessary to compilemod_pythonare part of separate > > > > ``development'' package. If you are not sure whether you have all the > > > > necessary files, either compile and install Python and Apache from > > > > source, or refer to the documentation for your system on how to get > > > > the development packages. > > > > ----- > > > > > I installed Apache from source using these instructions: > > > > >http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-o... > > > > > but I used a package to install python 2.4. The package was from > > > > here: > > > > >http://www.pythonmac.org/packages/ > > > > > and it's a "Universal binary version of Python that runs natively on > > > > PPC and Intel systems." > > > > > But my mac came with Python 2.3.5 pre-installed, so I wonder if I > > > > already have the necessary "include files for both Apache and Python, > > > > as well as the Python library" already installed. > > > > Have you actually tried to installmod_python? That would be the > > > quickest way of finding out. > > > > Because you are using an alternate Apache than the OS supplied one, > > > you will need to use the --with-apxs option to configure when building > > > Python. > > > Whoops, --with-apxs option is to configure formod_python, not Python. > > > > Unless you really need Python 2.4, it is easier to use the OS > > > supplied version of Python. If you must use an alternate version, use > > > the --with-python option to configure formod_pythonto tell it which > > > version. Depending on where that Python version is installed, you may > > > also have to fiddle the Apache 'envvars' file as well to get it to > > > work. > > > > Graham > > Hi, > > Thanks for the response. Sorry, I didn't respond in a timely manner. > > I thought I would give your suggestion a shot and just try installing > mod_python and see what happens, so I installed mod_python 3.3.1 with > this command: > > $ ./configure --with-apxs=/Library/Apache2/bin/apxs > > Here is the output: > > -------- > checking for gcc... gcc > checking for C compiler default output file name... a.out > checking whether the C compiler works... yes > checking whether we are cross compiling... no > checking for suffix of executables... > checking for suffix of object files... o > checking whether we are using the GNU C compiler... yes > checking whether gcc accepts -g... yes > checking for gcc option to accept ANSI C... none needed > checking for ar... ar > checking for a BSD-compatible install... /usr/bin/install -c > checking whether make sets $(MAKE)... yes > checking for main in -lm... yes > checking for an ANSI C-conforming const... yes > checking your blood pressure... a bit high, but we can proceed > configure: checking whether apxs is available... > checking for --with-apxs... /Library/Apache2/bin/apxs executable, good > checking Apache version... 2.2.4 > checking for Apache libexec directory... /Library/Apache2/modules > checking for Apache include directory... -I/Library/Apache2/include > checking for --with-python... no > checking for python... /Library/Frameworks/Python.framework/Versions/ > Current/bin/python > checking Python version... 2.4 > checking Python install prefix... /Library/Frameworks/Python.framework/ > Versions/2.4 > checking checking where python libraries are installed... /Library/ > Frameworks/Python.framework/Versions/2.4/lib/python2.4 > checking what libraries Python was linked with... -framework > Python -ldl > checking linker flags used to link Python... > checking where Python include files are... -I/Library/Frameworks/ > Python.framework/Versions/2.4/include/python2.4 > checking for --with-python-src... no > checking for --with-mutex-dir... no > Using MUTEX_DIR /tmp > checking for --with-max-locks... no > Using 8 MAX_LOCKS. > checking for --with-flex... no > checking for flex... /usr/bin/flex > found /usr/bin/flex, we'll use this. Use --with-flex to specify > another. > checking flex version... configure: WARNING: Flex version 2.5.4 found. > Version 2.5.31 or greater is required. You can generally ignore > this > warning unless you need to regenerate psp_parser.c from > psp_parse.l. > If you do need regenerate psp_parser.c, use --with-flex to specify > the > location of the correct flex version. See the README for more > information. > configure: creating ./config.status > config.status: creating Makefile > config.status: creating src/Makefile > config.status: creating Doc/Makefile > config.status: creating src/include/mod_python.h > config.status: creating test/Makefile > config.status: creating test/testconf.py > config.status: creating dist/setup.py > config.status: creating dist/Makefile > ----- > > So it looks like it installed fine--although I notice it picked up > python 2.4 and you said it was easier to install mod_python using the > pre-installed python 2.3.3. > > Then I tried to test the installation following the test in the > mod_python manual, which says to add the following to Apache's > http.conf file: > > > AddHandler mod_python .py > PythonHandler mptest > PythonDebug On > > > I did that, but when I started Apache, I got this error: > > --- > Syntax error on line 474 of /Library/Apache2/conf/httpd.conf: > Invalid command 'PythonHandler', perhaps misspelled or defined by a > module not included in the server configuration > --- > > Any ideas what went wrong? Have you got an appropriate LoadModule directive in Apache configuration to load the mod_python module? That you get this error is indicative of mod_python module not being loaded. You can check the Apache error logs to see if mod_python got loaded. See: http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking for more help on debugging. Graham From http Sun Jul 8 20:59:48 2007 From: http (Paul Rubin) Date: 08 Jul 2007 17:59:48 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <468565a0$0$3686$426a74cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: <7x1wfi5r3v.fsf@ruckus.brouhaha.com> Steve Holden writes: > Maybe we just have different styles, and I naturally tend to write in > smaller scopes than you do. It's easy to make errors even in very small scopes. From bdesth.quelquechose at free.quelquepart.fr Sun Jul 15 17:18:53 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 15 Jul 2007 23:18:53 +0200 Subject: Can a low-level programmer learn OOP? In-Reply-To: <6r2i93dcthg5j47nr8nuds5apeomseb2dr@4ax.com> References: <1i17kzo.1kphm951d3jl5dN%aleax@mac.com> <6r2i93dcthg5j47nr8nuds5apeomseb2dr@4ax.com> Message-ID: <469bd0f4$0$21672$426a34cc@news.free.fr> Wayne Brehaut a ?crit : > On Sat, 14 Jul 2007 19:18:05 +0530, "Rustom Mody" > wrote: > > >>On 7/14/07, Alex Martelli wrote: >> >>>OOP can be abused (particularly with deep or intricate inheritance >>>structures). But the base concept is simple and clear: you can bundle >>>state and behavior into a stateful "black box" (of which you may make as >>>many instances, with independent state but equal behavior, as you need). >>> >> >>Many years ago (86??) Wegner wrote a paper in OOPSLA called Dimensions >>of Object Orientation in which he called the 'base concept' of 'bundle >>of state and behavior' as 'object based' programming and >>'object-oriented' as object-based + inheritance. > > > Not quite--according to him: > > object-based + classes => class-based > class-based + class inheritance => object-oriented > > I.e., "object-oriented = objects + classes + inheritance". What about prototype-based languages then ?-) From orsenthil at users.sourceforge.net Tue Jul 17 22:44:41 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Wed, 18 Jul 2007 08:14:41 +0530 Subject: urllib to cache 301 redirections? In-Reply-To: References: <87wsxds6sq.fsf@pobox.com> Message-ID: <20070718024441.GB5654@gmail.com> * John Nagle [2007-07-16 12:34:00]: > That assumes you're reusing the same object to reopen another URL. > > Is this thread-safe? I don't know. I looked into few other cache requests (cache ftp) and saw how it was implemented. I am not getting as how this wont be thread-safe. > > That's also an inefficient way to test for an empty dictionary. > How should it be done, otherwise? I am looking for alternative methods as well. -- O.R.Senthil Kumaran http://uthcode.sarovar.org From gagsl-py2 at yahoo.com.ar Wed Jul 25 20:04:04 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 25 Jul 2007 21:04:04 -0300 Subject: Closures / Blocks in Python References: <1185289112.771239.200260@n60g2000hse.googlegroups.com> <1185291146.753573.280420@n60g2000hse.googlegroups.com> <7tvjn4-qas.ln1@lairds.us> <1185374700.256479.228560@b79g2000hse.googlegroups.com> Message-ID: En Wed, 25 Jul 2007 11:45:00 -0300, Jeff escribi?: > You can create a lexical closure using a Python generator function, > which allows iteration using a block of code while maintaining > internal state. A generator is a regular function which uses yield > (like Ruby) to define the point at which the function should return an > expression to the calling code. For example: > > # Generic counter > def counter(min=None, max): > if not min: > min = 0 > for i in xrange(min, max): > yield i > i = i + 1 > > When called, this function will yield the value of i and remember its > state. The next time it's called, it will increment i, then continue > on another iteration of the loop, yielding the new value of i. > > For example: > > my_counter = counter(0, 10) > my_counter() # <-- 0 > my_counter() # <-- 1 > for i in my_counter(): > print i > # Prints 2-10 (the remaining numbers in xrange(min, max)) Uhmm, I think this won't win the Best Python Code Of The Week Award :) Apart from the already noted syntax error in the function definition, the `i = i + 1` is useless because `i` gets reassigned right on the next loop. And you don't "call" a generator, you have to iterate over it; my_counter() will raise an error. This would be the right way: my_counter = counter(0, 10) my_counter.next() <-- 0 my_counter.next() <-- 1 for value in my_counter: print value <-- 2 to 9 -- Gabriel Genellina From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 3 04:27:45 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 03 Jul 2007 10:27:45 +0200 Subject: Python compilation ?? In-Reply-To: References: Message-ID: <468a0850$0$14120$426a74cc@news.free.fr> Evan Klitzke a ?crit : > On 7/2/07, Cathy Murphy wrote: >> Is python a compiler language or interpreted language. If it is >> interpreter >> , then why do we have to compile it? > > It's an interpreted language. It is compiled into bytecode By this definition, Java is an interpreted language. From erik at myemma.com Sun Jul 15 23:51:42 2007 From: erik at myemma.com (Erik Jones) Date: Sun, 15 Jul 2007 22:51:42 -0500 Subject: How to determine which method was used in an inheritance heirarchy? Message-ID: <1AD8DB09-64C7-43CF-9C57-2A2199B1A709@myemma.com> Say you're given a call event frame for a method call. How can you tell if the code being executed came from a super class of the object or class the method was called on? 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 gherzig at fmed.uba.ar Thu Jul 26 17:29:40 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Thu, 26 Jul 2007 18:29:40 -0300 Subject: SQLObject 0.9.1 In-Reply-To: <20070726143614.GI30176@phd.pp.ru> References: <20070726143614.GI30176@phd.pp.ru> Message-ID: <46A91244.8020408@fmed.uba.ar> Oleg Broytmann wrote: >Hello! > >I'm pleased to announce the 0.9.1 release of SQLObject. > > >What is SQLObject >================= > >SQLObject is an object-relational mapper. Your database tables are described >as classes, and rows are instances of those classes. SQLObject is meant to be >easy to use and quick to get started with. > >SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and >Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also >known as SAPDB). > > > > So..at 11:23 we got version 0.7.8...at 11:30 was version 0.8.5...now there is a 0.9.1 version?? Have a coffe dude, stop programming a little :) From shahmed at sfwmd.gov Fri Jul 13 11:10:20 2007 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Fri, 13 Jul 2007 11:10:20 -0400 Subject: permission denied in shutil.copyfile In-Reply-To: <1184338589.129432.178560@w3g2000hsg.googlegroups.com> Message-ID: <14A2A120D369B6469BB154B2D2DC34D20855ACB9@EXCHVS01.ad.sfwmd.gov> Is there any way to copy a file from src to dst if the dst is exclusively open by other users. I am using src = 'c:\mydata\data\*.mdb' dst = 'v:\data\all\*.mdb' shutil.copyfile(src,dst) but getting error message permission denied. Any help is highly appreciated. Thanks sh From jstroud at mbi.ucla.edu Wed Jul 11 22:49:29 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 11 Jul 2007 19:49:29 -0700 Subject: Where does str class represent its data? In-Reply-To: <1184196082.903895.176020@n60g2000hse.googlegroups.com> References: <1184196082.903895.176020@n60g2000hse.googlegroups.com> Message-ID: <%Egli.5395$rL1.3818@newssvr19.news.prodigy.net> ChrisEdgemon at gmail.com wrote: > I'd like to implement a subclass of string that works like this: > > >>>>m = MyString('mail') >>>>m == 'fail' > > True > >>>>m == 'mail' > > False > >>>>m in ['fail', hail'] > > True > > My best attempt for something like this is: > > class MyString(str): > def __init__(self, seq): > if self == self.clean(seq): pass > else: self = MyString(self.clean(seq)) > > def clean(self, seq): > seq = seq.replace("m", "f") > > but this doesn't work. Nothing gets changed. > > I understand that I could just remove the clean function from the > class and call it every time, but I use this class in several > locations, and I think it would be much safer to have it do the > cleaning itself. > The "flat is better than nested" philosophy suggests that clean should be module level and you should initialize a MyString like such: m = MyString(clean(s)) Where clean is def clean(astr): return astr.replace('m', 'f') Although it appears compulsory to call clean each time you instantiate MyString, note that you do it anyway when you check in your __init__. Here, you are explicit. Such an approach also eliminates the obligation to clean the string under conditions where you know it will already be clean--such as deserialization. Also, you don't return anything from clean above, so you assign None to self here: self = MyString(self.clean(seq)) Additionally, it has been suggested that you use __new__. E.g.: py> class MyString(str): ... def __new__(cls, astr): ... astr = astr.replace('m', 'f') ... return super(MyString, cls).__new__(cls, astr) ... py> MyString('mail') 'fail' But this is an abuse of the str class if you intend to populate your subclasses with self-modifying methods such as your clean method. In this case, you might consider composition, wherein you access an instance of str as an attribute of class instances. The python standard library make this easy with the UserString class and the ability to add custom methods to its subclasses: py> from UserString import UserString as UserString py> class MyClass(UserString): ... def __init__(self, astr): ... self.data = self.clean(astr) ... def clean(self, astr): ... return astr.replace('m', 'f') ... py> MyClass('mail') 'fail' py> type(_) This class is much slower than str, but you can always access an instance's data attribute directly if you want fast read-only behavior. py> astr = MyClass('mail').data py> astr 'fail' But now you are back to a built-in type, which is actually the point--not everything needs to be in a class. This isn't java. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From franciscodg at gmail.com Wed Jul 18 13:39:21 2007 From: franciscodg at gmail.com (franciscodg) Date: Wed, 18 Jul 2007 17:39:21 -0000 Subject: help with create menu in wxpython Message-ID: <1184780361.171375.133400@j4g2000prf.googlegroups.com> hi group: I have the following code: ...... ...... #MENU menuFile = wx.Menu() menuFile.Append(14, "E&xit","Sale del programa") menuHelp = wx.Menu() menuHelp.Append(41, "&about Mutamatic","Informacion de Mutamatic") menuBar = wx.MenuBar() menuBar.Append(menuFile, "&File") menuBar.Append(menuHelp, "&Help") #THIS IR IS THE PROBLEM!!! self.SetMenuBar(menuBar) self.sb = self.CreateStatusBar(1, wx.ST_SIZEGRIP) #menu help self.Bind(wx.EVT_MENU, self.OnAbout, id=41) ..... .... .... The question is the following: how can put the menu "HELP" in right part of the window? for example: ------------------------------------- |FILE| |HELP| ------------------------------------- | windows | | | ------------------------------------- Exist some attribute or function that does it?? thank you very much... greeting From zentraders at gmail.com Thu Jul 19 18:11:40 2007 From: zentraders at gmail.com (Zentrader) Date: 19 Jul 2007 15:11:40 -0700 Subject: really small values In-Reply-To: References: Message-ID: <1184882848.709077.168490@m37g2000prh.googlegroups.com> On Jul 17, 2:13 pm, "Dee Asbury" wrote: > In multiplying a value of xe^-325 with ye^-4, Python is returning zero. How > do I get it to give me back my tiny value? > > Thanks! > Dee Also, Python's decimal class allows theoretically unlimited precision. I have extremely limited knowledge here. It gives the following for 2**-325. I have no idea if the answer is correct. You'll have to see if gmpy or decimal works better for this. One piece of advice is to use whichever exclusively. If you use a float and then covert to either one, the result will be corrupted. import decimal decimal.getcontext().prec = 375 ## set precision at 375 print "2**-325 =", decimal.Decimal(str(2**-325)) 2**-325 = 1.46302386084E-98 From cai.haibin at gmail.com Mon Jul 23 04:13:03 2007 From: cai.haibin at gmail.com (james_027) Date: Mon, 23 Jul 2007 08:13:03 -0000 Subject: decorators tutorials Message-ID: <1185178383.499234.299850@z24g2000prh.googlegroups.com> Hi, I am learning python by learning django, and I stumble upon decorator which is very cool, any beginners resources for python decorators, although I can google it, I just want to get a good tutorial for this topic. Thanks james From siwiak at gmail.com Thu Jul 12 16:44:24 2007 From: siwiak at gmail.com (siwiak at gmail.com) Date: Thu, 12 Jul 2007 13:44:24 -0700 Subject: wx.App console window [Windows] Message-ID: <1184273064.350399.152490@o61g2000hsh.googlegroups.com> Hi All, I'm looking for a way to hide console window created by wx.App class. examplary code below: import wx class Gui(wx.App): def __init__(self, *pargs, **kwargs): wx.App.__init__(self, *pargs, **kwargs) if __name__ == "__main__": app = Gui() app.MainLoop() produces a blank console window (than dies). What shall I do to make wx.App run without raising console window? thanks in advance From lucaberto at libero.it Tue Jul 3 08:25:52 2007 From: lucaberto at libero.it (luca72) Date: Tue, 03 Jul 2007 05:25:52 -0700 Subject: unify els database In-Reply-To: <1183446552.345276.44930@k29g2000hsd.googlegroups.com> References: <1183383335.842730.41600@q69g2000hsb.googlegroups.com> <1183446552.345276.44930@k29g2000hsd.googlegroups.com> Message-ID: <1183465552.876190.66910@o61g2000hsh.googlegroups.com> Hello and thanks for your answer, the unify db is on unix-sco and i need to connect with linux machine with python Regards Luca From gagsl-py2 at yahoo.com.ar Mon Jul 9 04:12:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Jul 2007 05:12:35 -0300 Subject: having problems in changing directories doing ftp in python References: <1183812119.335649.292470@w3g2000hsg.googlegroups.com> Message-ID: En Sat, 07 Jul 2007 09:41:59 -0300, tedpottel at gmail.com escribi?: > I'm trying to write a ftp in python to send files to my webserverr. > Curtly I will change the directory to the folder name, down load the > file, then do a chnag dir ..\ to go back to the root diretory, chnag > the directory, save the file, do a ../. > > Instad of going back one directory by doing ..\, could I just go to > the root directory? Currtly I get a error saying file does not exist. Use the pwd command to see exactly which is your current directory. > When I log onto my server using my ftp program, > The current path reads /home/admin/ > I change the directory to mainwebsite_html. > The line that tells you the current directory now reads VAR/WWW/HTML. > > When I use python, I > 1. change the directory to mainwebsite_html > 2. change the directory to ted > 3. try to go back by changing the directory to "var/www/html" in which > I get an error saying it does not exist. If your server file system is case sensitive (likely if it's a linux/unix server), VAR/WWW/HTML is not the same thing as var/www/html -- Gabriel Genellina From martin at v.loewis.de Wed Jul 4 01:28:06 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Jul 2007 07:28:06 +0200 Subject: import mysteries In-Reply-To: References: Message-ID: <468b2fe6$0$1900$9b622d9e@news.freenet.de> > Yeah, of course. I just don't think anything that perverse is > happening in these cases. Take, for another example, > http://trac.edgewall.org/ticket/5646#comment:3 [that perverse == putting a name into globals()] When you do gettext.install(...), it will put the name _ into the __builtins__. Apparently, the trac code relies on that. Regards, Martin From nogradi at gmail.com Wed Jul 11 03:17:38 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 11 Jul 2007 09:17:38 +0200 Subject: Dynamic method In-Reply-To: <46939ba9$0$32159$426a74cc@news.free.fr> References: <46939ba9$0$32159$426a74cc@news.free.fr> Message-ID: <5f56302b0707110017s79a25442r4d3fa60b75247020@mail.gmail.com> > >> I have an issue I think Python could handle. But I do not have the > >> knowledge > >> to do it. > >> > >> Suppose I have a class 'myClass' and instance 'var'. There is function > >> 'myFunc(..)'. I have to add (or bind) somehow the function to the > >> class, or > >> the instance. Any help, info or point of reference is wellcome.... > > > > How about this (note the first argument 'self' which is the instance > > itself in the second case): > > > > > > > > def method_for_instance( message ): > > print message > > > > def method_for_class( self, message ): > > print message > > > > class myClass( object ): > > pass > > > > inst = myClass( ) > > inst.method = method_for_instance > > > > inst.method( 'hello' ) > > This won't work as expected: > > class Bidule(object): > def __init__(self, name): > self.name = name > > def greet(self, who): > print "hello %s, my name is %s" % (who, self.name) > > b = Bidule('Bruno') > b.greet = greet > b.greet('Daniel') > > => > Traceback (most recent call last): > File "", line 1, in > File "/tmp/python-23258Nq5.py", line 10, in > b.greet('Daniel') > TypeError: greet() takes exactly 2 arguments (1 given) Well, I thought the name method_for_instance and method_for_class are clear enough that if you want to 'attach' one of them to an instance then method_for_instance should be used :) And method_for_instance has only one argument and so will work as in the example I gave (I guess you just overlooked them). > The point is that Python functions are descriptor objects that, when > looked up, return a (bound or unbound) method object wrapping > themselves. So to attach functions as method *on a per-instance basis*, > you either need to use new.instancemethod (as explained by Alex), or > directly use the descriptor protocol, ie: > > b.greet = greet.__get__(b) > b.greet('Daniel') > => hello Daniel, my name is Bruno > > Note that you don't need this to attach a function as method to a class > - the descriptor protocol will then JustWork(tm). I agree that in general the solution explained by Alex and you is better. From steve at holdenweb.com Mon Jul 2 18:03:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Jul 2007 18:03:29 -0400 Subject: Python compilation ?? In-Reply-To: <20070702202448.4947.2088004513.divmod.quotient.6059@ohm> References: <20070702202448.4947.2088004513.divmod.quotient.6059@ohm> Message-ID: <46897631.8020102@holdenweb.com> Jean-Paul Calderone wrote: > On Mon, 02 Jul 2007 16:14:41 -0400, Steve Holden wrote: >> Evan Klitzke wrote: >>> On 7/2/07, Cathy Murphy wrote: >>>> Is python a compiler language or interpreted language. If it is interpreter >>>> , then why do we have to compile it? >>> It's an interpreted language. It is compiled into bytecode (not >>> machine code) the first time a script is run to speed up subsequent >>> executions of a script. >>> >> While the flavor of this answer is correct, in strict point of fact >> Python *doesn't* compile the scripts it executes, only the modules that >> are imported. >> >> That's why you will occasionally see a very small Python program that >> just calls functions imported from much larger modules. This avoids >> spending the time that would otherwise have to be spent recompiling a >> large script at each execution. > > Hey Steve, > > To nit pick :) Wouldn't you say it is more accurate to say that it > does compile the scripts (by which we mean the "main" file - either > the one passed as an argument to the interpreter on the command line, > or the one with a #! at the top which gets respected, or the .py file > on Windows which is associated with python.exe as its interpreter), > but that it doesn't save the results of this compilation to a file to > be used next time? > > Jean-Paul Absolutely. I should, of course, have said that only imported modules have the results of the compilation stored as a .pyc file. One must presume this is to save the file write time during development when the program is almost always different fro the last time you ran 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 eopadoan at altavix.com Wed Jul 4 20:14:14 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Wed, 4 Jul 2007 21:14:14 -0300 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <740c3aec0707041605w3ef468c8g38cec3ae7feee984@mail.gmail.com> References: <1182448413.966430.299590@m36g2000hse.googlegroups.com> <7xhcp0fom4.fsf@ruckus.brouhaha.com> <87tzt0tgol.fsf@benfinney.id.au> <1182533987.715191.159850@m36g2000hse.googlegroups.com> <740c3aec0707041605w3ef468c8g38cec3ae7feee984@mail.gmail.com> Message-ID: On 7/4/07, BJ?rn Lindqvist wrote: > On 6/22/07, Eduardo EdCrypt O. Padoan wrote: > > Remember that pure CPython has no different "compile time" and > > runtiime. But Psyco and ShedSkin could use the annotations the way > > they want. > ..... > > def compile(source: "something compilable", > > filename: "where the compilable thing comes from", > > mode: "is this a single statement or a suite?"): > > I think the above would make an annotation-enhanced Psyco or ShedSkin > very confused. This example was to show that annotations are for documentation too, not only type checking or optimization. It is from the PEP. ---- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From cousinstanley at hotmail.com Mon Jul 9 15:47:06 2007 From: cousinstanley at hotmail.com (Cousin Stanley) Date: Mon, 09 Jul 2007 14:47:06 -0500 Subject: Decorating instance methods References: Message-ID: <1184010426_64087@sp12lax.superfeed.net> > .... > Try this: > .... Sesame __Street__ Version .... ''' NewsGroup .... comp.lang.python Subject ...... Decorating instance methods Post_By ...... Alexander Draeger Reply_By ..... Duncan Booth Edit_By ...... Stanley C. Kitching ''' def logging( f ) : def deco( self , *args , **kw ) : print " %s in da house !" % self.name return f( self , *args , **kw ) return deco class A( object ) : def __init__( self , name ) : self.name = name @logging def hello( self ) : print ' Yo, %s .... \n' % self.name def test_01() : print list_names = [ 'Bert' , 'Cookie Monster' , 'Count Dracula' , 'Ernie' ] list_objects = [ A( this_name ) for this_name in list_names ] for this_object in list_objects : this_object.hello() if __name__ == '__main__' : test_01() -- 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 huliang25 at yahoo.com Thu Jul 5 08:22:12 2007 From: huliang25 at yahoo.com (HangZhou Monty Boy) Date: Thu, 05 Jul 2007 12:22:12 -0000 Subject: Chat programs Message-ID: <1183638132.939925.43350@x35g2000prf.googlegroups.com> I'd like to think of building a chat program, could you advise me if python is good enough for people to get all of my source code ? Thanks From tedpottel at gmail.com Sat Jul 7 08:34:45 2007 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Sat, 07 Jul 2007 05:34:45 -0700 Subject: How to FTP a ASCII file In-Reply-To: References: <1183417366.036607.233910@n60g2000hse.googlegroups.com> Message-ID: <1183811685.707497.298910@g4g2000hsf.googlegroups.com> On Jul 2, 7:07 pm, Adonis Vargas wrote: > tedpot... at gmail.com wrote: > > Hi, > > > My program has the following code to transfer a binary file > > > f = open(pathanme+filename,'rb') > > print "start transfer" > > self.fthHandle.storbinary('STOR '+filename, f) > > > How can I do anASCIIfile transfer?????? > > -Ted > > Taken from online documentation: > > http://docs.python.org/lib/ftp-objects.html > > storlines(command, file) > > Store a file inASCIItransfer mode. command should be an appropriate > "STOR" command (see storbinary()). Lines are read until EOF from the > open file object file using its readline() method to provide the data to > be stored. > > Hope this helps. > > Adonis Thank you it waqs soooo simple, works fine now!!!! From nick-news at net4u.hr Sat Jul 14 13:47:22 2007 From: nick-news at net4u.hr (Nikola Skoric) Date: Sat, 14 Jul 2007 17:47:22 +0000 (UTC) Subject: getting text inside the HTML tag Message-ID: I'm using sgmllib.SGMLParser to parse HTML. I have successfuly parsed start tags by implementing start_something method. But, now I have to fetch the string inside the start tag and end tag too. I have been reading through SGMLParser documentation, but just can't figure that out... can somebody help? :-) -- "Now the storm has passed over me I'm left to drift on a dead calm sea And watch her forever through the cracks in the beams Nailed across the doorways of the bedrooms of my dreams" From gagsl-py2 at yahoo.com.ar Sun Jul 22 04:57:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 22 Jul 2007 05:57:52 -0300 Subject: simpleJSON pack binary data References: Message-ID: En Sat, 21 Jul 2007 23:13:22 -0300, Andrey escribi?: > Is it possible to pack binary data into simplejson? json does not provide any direct "binary" type; strings are Unicode strings. Try encoding your data using Base64 for example, or transform it into an array of numbers. -- Gabriel Genellina From tjreedy at udel.edu Thu Jul 19 23:35:10 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 19 Jul 2007 23:35:10 -0400 Subject: Efficiently removing duplicate rows from a 2-dimensional Numeric array References: <76EEE12626B7A84EBACE67EC513AE53D060F8CE9@WIN-MSG-20.wingroup.windeploy.ntdev.microsoft.com> Message-ID: "Alex Mont" wrote in message news:76EEE12626B7A84EBACE67EC513AE53D060F8CE9 at WIN-MSG-20.wingroup.windeploy.ntdev.microsoft.com... I have a 2-dimensional Numeric array with the shape (2,N) and I want to remove all duplicate rows from the array. For example if I start out with: [[1,2], [1,3], [1,2], [2,3]] I want to end up with [[1,2], [1,3], [2,3]]. ================================================= If you can define a 1-1 map of rows to ints (or even float or strings), you can put intsnumbers into a set and then convert (unique) items back to rows. For example above, the obvious 10*r[0] + r[1] would do. So would chr(r[0]) + chr(r[1]). More generally, you need the min and max of the second numbers and not have them be too far apart/ tjr From sjdevnull at yahoo.com Fri Jul 20 05:18:47 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Fri, 20 Jul 2007 02:18:47 -0700 Subject: class C: vs class C(object): In-Reply-To: References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> Message-ID: <1184923127.990359.288920@d55g2000hsg.googlegroups.com> Aahz wrote: > In article , > James Stroud wrote: > >Aahz wrote: > >> In article , > >> Steven D'Aprano wrote: > >>> > >>>It isn't wrong to use the old style, but it is deprecated, [...] > >> > >> > >> Really? Can you point to some official documentation for this? AFAIK, > >> new-style classes still have not been integrated into the standard > >> documentation. Maybe I missed something, though. > >> > >> Note very carefully that "going away eventually" is *not* the same as > >> deprecation. > > > >How about "broke" instead of "deprecated": > > > > > > >>> class Old: > >... def __init__(self): > >... self._value = 'broke' > >... value = property(lambda self: self._value) > >... > > How is this broken? Properties are not supported for old-style classes. > They may not support features introduced in new-style classes, but that's > hardly the same as "broken". In particular, old-style classes are noticeably faster than new-style classes for some things (I think it was attribute lookup that surprised me recently, possibly related to the property stuff...) From tim at tdw.net Wed Jul 18 08:38:14 2007 From: tim at tdw.net (Tim Williams) Date: Wed, 18 Jul 2007 13:38:14 +0100 Subject: Copy List In-Reply-To: References: Message-ID: <9afea2ac0707180538r7479e09mba24b6841d5a9fd2@mail.gmail.com> On 18/07/07, Robert Rawlins - Think Blue wrote: > > What's the best way to create a copy of a list? I've seen several method and > I'm not sure what to use. This will be in a class and one method creates a > list which I then want to move to the self scope, like so: > listB = listA[:] hth :) From ptmcg at austin.rr.com Sun Jul 8 20:35:01 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 08 Jul 2007 17:35:01 -0700 Subject: socket.makefile() buggy? In-Reply-To: References: <1183892789.434028.15370@x35g2000prf.googlegroups.com> Message-ID: <1183941301.268249.207000@c77g2000hse.googlegroups.com> On Jul 8, 8:54 am, Steve Holden wrote: > That's a pretty pejorative subject line for someone who's been > programming Python [guessing by the date of your first post] for about a > month. > > Perhaps "Incomprehensible behavior from socket.makefile()", or "I have > written a buggy network application"? That would at least show that you > are considering the possibility you yourself are the cause of the > problem ;-) > > Python has been around for a long time, so you should ask yourself how > likely it is that you would be the first to discover such a fundamental > flaw? I'd be very surprised if someone doesn't point you at an article > on "how to ask smart questions", but I will content myself with that > oblique reference. > > > > > > ahlongxp wrote: > > socket.makefile() may lose data when "connection reset by peer". > > and socket.recv() will never lose the data. > > > change the "1" to "0" in the client code to see the difference. > > > confirmed on both windows and linux. > > > so I guess there is a problem with makefile(). > > > # Echo server program > > import socket > > > HOST = '' # Symbolic name meaning the local host > > PORT = 50007 # Arbitrary non-privileged port > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) > > s.bind((HOST, PORT)) > > s.listen(1) > > while(1): > > conn, addr = s.accept() > > print 'Connected by', addr > > conn.settimeout(1) > > toread = 99 > > retrytime = 0 > > reads = 0 > > while reads < toread and retrytime < 10: > > try: > > data = conn.recv(min(32,toread-reads)) > > if not data: continue > > print data > > reads += len(data) > > except: > > retrytime += 1 > > print "timeout %d" % retrytime > > continue > > #conn.shutdown(socket.SHUT_RD)#no more read > > if reads == toread: > > conn.send("OK") > > else: > > conn.send("NOT OK") > > conn.close() > > > # Echo client program > > import socket > > > HOST = 'localhost' # The remote host > > PORT = 50007 # The same port as used by the server > > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s.connect((HOST, PORT)) > > for i in range(12): > > print "time %d" % i > > try: > > s.send('0123456789') > > except socket.error, e: > > print "socket error:", e > > break > > #data = s.recv(1024) > > #print "data %d" %i, data > > #s.shutdown(socket.SHUT_WR)#no more write > > > ''' > > try changing 1 to 0. > > ''' > > if 1: > > data=s.recv(1024) > > else: > > rf = s.makefile("rb") > > data = rf.read() > > rf.close() > > s.close() > > print 'Received', repr(data) > > The big problem here seems to be that your server is closing the socket > after reading 99 bytes, but the client is actually sending 120. If you > change the "99" in the server to "120" you will see that the client > works when it uses the makefile().read(). I can't be bothered to debug > the exact reason why the 21 bytes of buffered data doesn't cause a > problem with the recv() version, but I wouldn't regard the error you are > getting as a bug in Python, rather as a bug in your application. > > The underlying cause of all this appears to be your failure to > understand that network protocols should ideally allow the endpoints to > determine when a complete message has been transmitted, and to consume > all transmitted data. > > You can't just ignore some or all of a client request and expect it not > to cause problems. If you look at some of the better-known TCP-based > application protocols you will see they take pains to ensure that > clients and servers can deterministically parse each others' messages. > > In summary, a better protocol design will cause you rather less grief > and a little more humility will result in less acidity from crabby old > geeks like 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 -------------- Hide quoted text - > > - Show quoted text - I don't think you're crabby, Steve. -- Paul From will at willNOmcguganSPAM.com Tue Jul 3 11:36:55 2007 From: will at willNOmcguganSPAM.com (Will McGugan) Date: Tue, 03 Jul 2007 16:36:55 +0100 Subject: error return without exception set Message-ID: <468a6d19$0$27861$db0fefd9@news.zen.co.uk> Hi, Can anyone suggest a likely cause for the following exception... Exception exceptions.SystemError: 'error return without exception set' in ignored Thanks Will McGugan From urbangabo at gmail.com Tue Jul 31 04:46:39 2007 From: urbangabo at gmail.com (Gabor Urban) Date: Tue, 31 Jul 2007 10:46:39 +0200 Subject: Simple question about logging module. Message-ID: Hullo, I have started to use Python's logging, and got a problem. I have created some loggers and wrote some lines in the log. The problem is, that most of the lines appear doubled in the log, and some lines do not appear at all. Any ideas or comments are wellcome, Gabor Here is the code: import sys import logging l = logging.getLogger('XmlTester') handler = logging.StreamHandler(sys.stderr) l.addHandler(handler) formatter = logging.Formatter("%(name)s %(asctime)s %(filename)s %(lineno)d %(levelname)s %(message)s") handler.setFormatter(formatter) la = logging.getLogger('XmlTester.XmlParser') handler = logging.StreamHandler(sys.stderr) la.addHandler(handler) handler.setFormatter(formatter) lb = logging.getLogger('XmlTester.TestExecutor') handler = logging.StreamHandler(sys.stderr) lb.addHandler(handler) handler.setFormatter(formatter) l.setLevel(logging.DEBUG) la.setLevel(logging.DEBUG) lb.setLevel(logging.DEBUG) l.debug("Start") la.debug("Start la") lb.debug("This debug") lb.info("This started.") l.info("Info written") l.warning("This is a warning") l.error("Error occured") test = "Info.pck" la.info("Hi there!") la.critical("No file named '%s'"%test) l.critical("End of all") Here is the output: XmlTester.XmlParser 2007-07-31 10:34:12,303 plogtest.py 21 DEBUG Start la XmlTester.XmlParser 2007-07-31 10:34:12,303 plogtest.py 21 DEBUG Start la XmlTester.TestExecutor 2007-07-31 10:34:12,319 plogtest.py 22 DEBUG This debug XmlTester.TestExecutor 2007-07-31 10:34:12,319 plogtest.py 22 DEBUG This debug XmlTester.TestExecutor 2007-07-31 10:34:12,319 plogtest.py 23 INFO This started. XmlTester.TestExecutor 2007-07-31 10:34:12,319 plogtest.py 23 INFO This started. XmlTester.XmlParser 2007-07-31 10:34:12,319 plogtest.py 28 INFO Hi there! XmlTester.XmlParser 2007-07-31 10:34:12,319 plogtest.py 28 INFO Hi there! XmlTester.XmlParser 2007-07-31 10:34:12,319 plogtest.py 29 CRITICAL No file named 'Info.pck' XmlTester.XmlParser 2007-07-31 10:34:12,319 plogtest.py 29 CRITICAL No file named 'Info.pck' XmlTester 2007-07-31 10:34:12,319 plogtest.py 30 CRITICAL End of all -------------- next part -------------- An HTML attachment was scrubbed... URL: From samwyse at gmail.com Sun Jul 8 08:53:13 2007 From: samwyse at gmail.com (samwyse) Date: Sun, 08 Jul 2007 12:53:13 -0000 Subject: allow scripts to use .pth files? In-Reply-To: References: Message-ID: <1183899193.766331.13210@22g2000hsm.googlegroups.com> On Jul 3, 9:35 am, Alan Isaac wrote: > Suppose I have a directory `scripts`. > I'd like the scripts to have access to a package > that is not "installed", i.e., it is not on sys.path. > On this list, various people have described a variety > of tricks they use, but nobody has proposed a > pretty way to allow this. > I am therefore assuming there is not one. (?) > > How about allowing a `scripts.pth` file in such a `scripts` > directory, to work like a path configuration file? > (But to be used only when __name__=="__main__".) > Drawbacks? > > Alan Isaac before i can adequately shoot down your proposal, i need more information. first, how does the interpreter know to look in 'scripts' for your 'scripts.pyh' file and not in '.' or '~' or sys.argv[0] or someplace else? and you do know, don't you, that if you run 'scripts/ myscript.py' then 'scripts' is automagically prepended to the search path for modules? second, what's for format of this proposed file? does it contain the name of a single directory? is it one directory name per line? is it intended to be os-specific or will the same file work on windows, unix, vms and macos? third, is there anything special about the name? should i put a myscripts.pyh file in the myscripts directory? what if i have multiple .pyh files? if i may make some assumptions about the answers to the above, then this incantation might do somewhat more than what you've asked for (but what you actually want may be different): if __name__ == '__main__': import sys from os.path import split, join, expanduser for d in '.', split(sys.argv[0])[0], expanduser('~'): scripts_pyh = join(d, 'scripts.pyh') try: for each_line in open(scripts_pyh).readlines(): sys.path.append(each_line) except: pass personally, though, i would be more likely to use this and skip all of that 'scripts.pyh' nonsense: if __name__ == '__main__': import sys, os.path for d in '.', os.path.expanduser('~'): if os.path.isdir(d): sys.path.append(d) From rustompmody at gmail.com Wed Jul 18 09:55:45 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 18 Jul 2007 19:25:45 +0530 Subject: The Modernization of Emacs: exists already In-Reply-To: <469E1837.9000106@freakmail.de> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272678.877166.209640@j4g2000prf.googlegroups.com> <1184764620.778937.264760@m37g2000prh.googlegroups.com> <469E1837.9000106@freakmail.de> Message-ID: Eh? Me? you?? Who??? Did I say something offensive? Sorry if I did... but I dont understand... I must say that I found the earlier post useful to me as an old-time emacs user who's not quite upto all the latest stuff. However it was quite off topic for a python list. The flame war that followed was quite a waste of time and bandwidth: -- one person who seems to know little blowing his trumpet -- others who know a great deal (of emacs) not acknowledging the room for improvement All off topic for a python list Sorry once again if I said something offensive. On 7/18/07, Wildemar Wildenburger wrote: > Rustom Mody wrote: > > But how does posting an emacs related question help on a python mailing list?? > > > One Word: Ego. > Don't reply. > > /W > -- > http://mail.python.org/mailman/listinfo/python-list > From bearophileHUGS at lycos.com Tue Jul 24 06:19:53 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: Tue, 24 Jul 2007 03:19:53 -0700 Subject: From D Message-ID: <1185272393.484032.125180@22g2000hsm.googlegroups.com> There are various things I like about the D language that I think Python too may enjoy. Here are few bits (mostly syntactical ones): 1) (we have discussed part of this in the past) You can put underscores inside number literals, like 1_000_000, the compiler doesn't enforce the position of such underscores, so you can also put them like this: 1_00_000. You can put them in literals of decimals, binary, hex, etc. I think it's quite useful, because when in Python code I have a line like: for i in xrange(1000000): I need some time to count the zeros, because the lower levels of my visual systems can't count/group them quickly (perceptually). While in a syntax like: for i in xrange(1_000_000): my eyes help me group them at once. 2) Base 2 number literals, and base 2 "%b" printing with the writefln. Base-2 numbers are less common in Python code, but once in a while I use them. For example: import std.stdio; void main() { auto x = 0b0100_0011; writefln("%b", x); writefln("%.8b", x); writefln(x); } Prints: 1000011 01000011 67 3) All string literals are multi line. So you can write: a = "how are you"; There's no need for """ """. 4) With D I have created an xsplit() generator, and from my tests it's quite faster than the split(), expecially if the string/lines you want to split are few hundred chars long or more (it's not faster if you want to split very little strings). So I think Python can enjoy such string method too (you can probably simulate an xsplit with a regular expression, but the same is true for some other string methods too). Bye, bearophile From bj_666 at gmx.net Wed Jul 25 15:11:34 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Jul 2007 19:11:34 GMT Subject: is_iterable function. References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> Message-ID: <5gplj6F3gg2e0U3@mid.uni-berlin.de> On Wed, 25 Jul 2007 11:58:40 -0700, danmcleran at yahoo.com wrote: > You can use the built-in dir() function to determine whether or not > the __iter__ method exists: Doesn't work: In [58]: is_iterable('hello') Out[58]: False But strings *are* iterable. And just calling `iter()` doesn't work either: In [72]: class A: ....: def __getitem__(self, key): ....: if key == 42: ....: return 'answer' ....: raise KeyError ....: In [73]: iter(A()) Out[73]: In [74]: a = iter(A()) In [75]: a.next() --------------------------------------------------------------------------- Traceback (most recent call last) /home/bj/ in () /home/bj/ in __getitem__(self, key) : So there's no reliable way to test for "iterables" other than actually iterate over the object. Ciao, Marc 'BlackJack' Rintsch From dennis.varghese at wipro.com Mon Jul 23 08:29:01 2007 From: dennis.varghese at wipro.com (pycraze) Date: Mon, 23 Jul 2007 05:29:01 -0700 Subject: Need Help with base64 Message-ID: <1185193741.420611.302290@z28g2000prd.googlegroups.com> Hi , I am currently trying to implement base64 encoding and decoding scheme in C . Python has a module , base64 , that will do the encoding and decoding with ease . I am aware of OpenSSL having support for base64 encoding and decoding , but i will have to now implement both in C without using the openssl libraries . I was able to download a code w.r.t. base 64 encoding and decoding . I am attaching the code below . void encodeblock( unsigned char cin[3], unsigned char cout[4], int nlen ) { cout[0] = cb64[ cin[0] >> 2 ]; cout[1] = cb64[ ((cin[0] & 0x03) << 4) | ((cin[1] & 0xf0) >> 4) ]; cout[2] = (unsigned char) (nlen > 1 ? cb64[ ((cin[1] & 0x0f) << 2) | ((cin[2] & 0xc0) >> 6) ] : '='); cout[3] = (unsigned char) (nlen > 2 ? cb64[ cin[2] & 0x3f ] : '='); } void decodeblock( unsigned char cin[4], unsigned char cout[3] ) { cout[ 0 ] = (unsigned char ) (cin[0] << 2 | cin[1] >> 4); cout[ 1 ] = (unsigned char ) (cin[1] << 4 | cin[2] >> 2); cout[ 2 ] = (unsigned char ) (((cin[2] << 6) & 0xc0) | cin[3]); } int base641_decodestring(char* pcstr,int size,char** ppcdest) { unsigned char cin[4] = {""}; unsigned char cout[3] = {""}; unsigned char cv = 0; int ni = 0; int nlen = 0; char* cptr = pcstr; *ppcdest = malloc(sizeof(char)*160); if (!*ppcdest) { return 1; } memset(*ppcdest,0,sizeof(char)*160); char* pcstring = malloc( sizeof(char) * SIZE); if (!pcstring) { aps_log("APS_log.txt","\nbae64.c:base64encode:malloc failed \n"); return 1; } memset(pcstring,'\0',SIZE); for( nlen = 0, ni = 0; ni < 4; ni++ ) { cv = 0; while( cv == 0 ) { cv = (unsigned char) *cptr; cv = (unsigned char) ((cv < 43 || cv > 122) ? 0 : cd64[ cv - 43 ]); if( cv ) { cv = (unsigned char) ((cv == '$') ? 0 : cv - 61); } } if( cptr++ ) { nlen++; if( cv ) { cin[ ni ] = (unsigned char) (cv - 1); } } else { cin[ni] = 0; } } if( nlen ) { decodeblock( cin, cout ); } memcpy(*ppcdest,cout,160); return 0; }/*end of base64_decode */ char* base64_encode(char* pcstr) { unsigned char cin[3] = {""}; unsigned char cout[4] = {""}; int ni = 0; int nlen = 0; int flag = 1; char* cptr = pcstr; char* pcstring = malloc( sizeof(char) * SIZE); if (!pcstring) { aps_log("APS_log.txt","\nbae64.c:base64encode:malloc failed \n"); return (void*)0; } memset(pcstring,'\0',SIZE); while( flag ) { for( ni = 0; ni < 3; ni++ ) { cin[ni] = (unsigned char)*cptr; if( *++cptr != '\0' ) nlen++; else { cin[ni] = 0; flag = 0; break; } } encodeblock(cin, cout,nlen); strcat(pcstring,cout); } return pcstring; }/* end of base64_encode */ But this code gives different hex values as compared to the python base64.encodestring and base64.decodestring respectively . I need some help on this matter . I need some pointers on where is the mistake for the above file . From leena_kirank at yahoo.com Wed Jul 11 17:12:41 2007 From: leena_kirank at yahoo.com (Kan) Date: Wed, 11 Jul 2007 14:12:41 -0700 Subject: Direct Client - Sr.Soft Engineer-Python and Linux Message-ID: <1184188361.426169.234040@j4g2000prf.googlegroups.com> Hello, We have requirement for Sr.Software Engineer in San Jose CA with very strong experinece in PYTHON AND LINUX . If your skills and experience matches with the same, send me your resume asap with contact # and rate. Locals only pls apply The details of the openings are:- Strong in Python and Linux Good in Java C++ Kan BTech Inc Recruiter 510-438-6834 www.tbiinc.org From Graham.Dumpleton at gmail.com Thu Jul 12 22:28:32 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Fri, 13 Jul 2007 02:28:32 -0000 Subject: Client-side cookies on Python in Mac OSX In-Reply-To: <1184292844.383002.128420@n2g2000hse.googlegroups.com> References: <1184292844.383002.128420@n2g2000hse.googlegroups.com> Message-ID: <1184293712.607084.27310@g37g2000prf.googlegroups.com> On Jul 13, 12:14 pm, Adrian Petrescu wrote: > Hi, all. I'm writing an app for OS X; therefore I'd prefer to use only > the default python install that comes with Tiger. For the moment, > however, this means: > > NaviOSX:~ adrianpetrescu$ python -V > Python 2.3.5 > > Therefore, I was not surprised to find out that cookielib did not > exist here, since I knew that it was a 2.4+ feature. > > However, I *was* shocked to find out that ClientCookie, which I'd > thought was a Python 2.0+ feature, also cannot be found: > > >>> import ClientCookie > > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named ClientCookie > > Why would Apple go out of their way to remove this functionality from > their shipped version of Python? More importantly, considering I need > to programatically access a website that uses cookies for > authentication, how can I do this in OSX's Python install? Do they > provide some other library they'd prefer you to use? > > I'm sure SOMEONE in the world has used cookies on Macs so I'm hoping > there is a solution for this... They didn't remove it, it was never there in the first place. The ClientCookie site says 'Python 2.0 or above is required'. It doesn't say it is included with Python distributions. The package still has to be installed separately. See: http://wwwsearch.sourceforge.net/ClientCookie/ Graham From steve at REMOVE.THIS.cybersource.com.au Tue Jul 24 19:08:37 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 25 Jul 2007 09:08:37 +1000 Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> Message-ID: On Tue, 24 Jul 2007 20:09:00 +0200, Bjoern Schliessmann wrote: > Stargaming wrote: >> On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote: > >>> While in a syntax like: >>> for i in xrange(1_000_000): >>> my eyes help me group them at once. >> >> Sounds like a good thing to be but the arbitrary positioning >> doesnt make any sense. > > Checking underscore positions would only add complexity. Why not > just ignore them, no matter where they are? Underscores in numerics are UGLY. Why not take a leaf out of implicit string concatenation and allow numeric literals to implicitly concatenate? Python already does: "hello-" "world" => "hello-world" Propose: 123 456 789 => 123456789 123.456 789 => 123.456789 -- Steven. From kay.schluehr at gmx.net Sat Jul 21 13:51:54 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Sat, 21 Jul 2007 10:51:54 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xbqe7ox9n.fsf@ruckus.brouhaha.com> References: <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <7x8x9lwka9.fsf@ruckus.brouhaha.com> <7xbqe7ox9n.fsf@ruckus.brouhaha.com> Message-ID: <1185040314.501879.266230@22g2000hsm.googlegroups.com> On Jul 20, 6:28 pm, Paul Rubin wrote: > As the Intel FDIV bug > incident reminds us, even billions of test inputs are not enough to > show that the routine does the right thing for EVERY input. When I remember correctly the FDIV bug was due to a wrongly filled lookup table and occurred only for certain bitpattern in the divisor. I'm not sure how a formal proof on the structure of the algorithm could help here? Intel repaired the table i.e. the data not the algorithm that acted upon it. From steven at REMOVE.THIS.cybersource.com.au Wed Jul 11 01:10:08 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Jul 2007 05:10:08 GMT Subject: bool behavior in Python 3000? References: Message-ID: On Tue, 10 Jul 2007 17:47:47 -0600, Steven Bethard wrote: >> I mean, really, does anyone *expect* True+True to give 2, or that >> 2**True even works, without having learnt that Python bools are ints? I >> doubt it. >> >> And the old Python idiom for an if...then...else expression: >> >> ["something", "or other"][True] >> >> tends to come as a great surprise to most newbies. So I would argue >> that bools being ints is more surprising than the opposite would be. > > I disagree. I think you'd get just as many odd stares if: > > True + True == True Well, sure, if you're talking about people with no programming experience whatsoever, or at least those who aren't at all familiar with the concept of operator overloading. But we don't prohibit "foo" + "bar" because of the existence of non-programmers. > But I think all you're really saying is that newbies don't expect things > like +, -, *, etc. to work with bools at all. Which I agree is probably > true. No, what I am saying is that True and False being integers under the hood is a surprising implementation detail. It has no _inherent_ benefit: it is merely a practical way to bring bools into the language while remaining backward compatible. For Python 2.x, that was the least bad solution to the issue "oops, we should have included a bool type". Python 3 is allowed to break backwards compatibility, and there is no reason I can see to keep the current hack. -- Steven. From horpner at yahoo.com Fri Jul 13 15:29:27 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 13 Jul 2007 19:29:27 GMT Subject: Can a low-level programmer learn OOP? References: Message-ID: On 2007-07-13, Chris Carlen wrote: > John Nagle wrote: >> You can sometimes get better performance in C++ than in C, >> because C++ has "inline". Inline expansion happens before >> optimization, so you can have abstractions that cost nothing. > > That's interesting. But why is this any different than using > preprocessor macros in C? This is OT, however: inline functions have a few benefits over preprocessor macros. 1. They are type-safe. 2. They never evaluate their arguments more than once. 3. They don't require protective parentheses to avoid precedence errors. 4. In C++, they have the additional benefit of being defined in a namespace, rather than applying globally to a file. As an experienced C programmer you're probably used to coping with the problems of preprocessor macros, and may even take advantage of their untyped nature occasionally. Even C++ programmers still use the advisedly. > I will keep an open mind however, that until I work with it for > some time there is still the possibility that I will have some > light go on about OOP. So don't worry, I'm not rejecting your > input. In my opinion OOP is usefully thought of as a type of design rather than a means of implementation. You can implement an OO design in a procedural langauge just fine, but presumably an OO programming language facilitates the implementation of an OO design better than does a procedural language. Going back to the stack machine question, and using it as an example: Assume you design your program as a state machine. Wouldn't it be easier to implement in a (hypothetical) state-machine-based programming language than in a procedural one? I think John was insinuating that a state-machine is more like an object than it is like a procedure. -- Neil Cerutti From jeffober at gmail.com Wed Jul 25 15:34:47 2007 From: jeffober at gmail.com (Jeff) Date: Wed, 25 Jul 2007 19:34:47 -0000 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <1185379218.286977.124040@19g2000hsx.googlegroups.com> <1185384306.104549.287510@19g2000hsx.googlegroups.com> <1185384793.577650.256310@d55g2000hsg.googlegroups.com> Message-ID: <1185392087.385728.255920@q75g2000hsh.googlegroups.com> On Jul 25, 3:05 pm, "Eduardo \"EdCrypt\" O. Padoan" wrote: > def flatten(listOfLists): > return list(chain(*listOfLists)) > > >Fromhttp://www.python.org/doc/2.4/lib/itertools-recipes.html > > -- > EduardoOPadoan (eopadoan->altavix::com) > Bookmarks:http://del.icio.us/edcrypt That doesn't necessarily work: import itertools x = (1, 2, [3, 4, (5, 6)]) y = ([1, 2, (3, 4)], 5, 6) z = (1, [2, 3, (4, 5)], 6) def flatten(listOfLists): return list(itertools.chain(*listOfLists)) print flatten(x) print flatten(y) print flatten(z) ==> TypeError: chain argument #1 must support iteration From vasudevram at gmail.com Mon Jul 16 14:46:42 2007 From: vasudevram at gmail.com (vasudevram) Date: Mon, 16 Jul 2007 18:46:42 -0000 Subject: Technology solutions for Ruby? In-Reply-To: <1184606739.054580.197740@g37g2000prf.googlegroups.com> References: <469B059C.2050802@cesmail.net> <1184606739.054580.197740@g37g2000prf.googlegroups.com> Message-ID: <1184611602.414529.41090@i38g2000prf.googlegroups.com> On Jul 16, 10:25 pm, vasudevram wrote: > [ Though the OP posted his message to comp.lang.ruby, I'm cross- > posting it to comp.lang.python, since he mentions Python as a possible > alternative he's looking at, and also because I've recommended Python > for his stated needs. Also, interested to see what other Pythonistas > have to say in response to my reply. > - Vasudev] > > > On Jul 16, 2007, at 2:21 AM, Michael Reiland wrote: > > At the heart of the issue is the fact that I refuse to use Java for this > > project, I prefer not to use .Net because of the portability issues, > and > I'd like to get away from C++ for obvious reasons. > > > To me this means Ruby, Python, or, as mentioned above, Perl. If anyone > > can tell me of a way to meet the above requirements in either Python > or > Perl, I'm all ears (I just prefer Ruby). > > Yes, I think it would be really great for the Ruby community and for > the growth of the language if wxRuby was more mature as a GUI toolkit. > (Not knocking the wxRuby developers at all, its great that they've > even done what they have - I know that creating other language (like > Ruby) bindings to a C++ lib is a non-trivial task). > > My suggestion: Python + wxPython + Python DBI + (Py2Exe + InnoSetup) > *might* meet all your needs. (As with any decision about what software > technologies to use, you'll have to evaluate the suggested options to > see if they fit your needs.) > > Note: I've used and like both Ruby and Python (saying this after using > many, though not all, language features and libraries of both > languages), and am not trying to discourage you from using Ruby for > your needs; its just that, based on your needs as described, it looks > to me as if Python meets them better than Ruby at present: > > > 1. GUI - Native Look and Feel. According to wxRuby the bindings aren't > > mature enough for production use. Does anyone have any experience > with > this and/or can you offer alternatives that provide a native look and > feel (I > > I don't know enough about wxRuby to comment. > > wxPython has this (Native Look and Feel), I think (used it some, a > while ago), not 100% sure, you can check on the site - http:/www.wxpython.org > - to make sure. The site does say that it is cross-platform: > > "wxPython is a cross-platform toolkit. This means that the same > program will run on multiple platforms without modification. Currently > supported platforms are 32-bit Microsoft Windows, most Unix or unix- > like systems, and Macintosh OS X. > " > > but that doesn't necessarily mean that it will have native look and > feel on all supported platforms. (The two are not the same thing.) > That's why you will need to check. > > wxPython pros: Its fairly easy to learn, at least for simple GUI apps > (e.g. a few widgets / controls and a file dialog or two). I was able > to build these simple ones - see the code, article and screenshots > available here (or from links from here): > > http://www.packtpub.com/article/Using_xtopdf > > - in quite a short time, starting from zero knowledge of wxPython (I > did know some Python from before), just by looking at the sample apps, > and some reading of the docs. > > See the quotes about wxPython:http://www.wxpython.org/quotes.php > > >2. Databases - contemplating using ActiveRecord, but I would like to use > > ODBC to support multiple types of DB's in a uniform way (if you know > of > alternatives to ODBC or ActiveRecord, please let me know). > > I think, but again, not sure, that Python DBI + appropriate database > drivers, may meet this need. Basically Python DBI is similar to ODBC > (roughly), and to Perl DBI + DBD, as I understand. There's also ODBC > support in the Win32 extensions package for Python - IIRC, Google for > 'win32all' to get it. Its also available as a link from the Python for > Win32 MSI installer on python.org. > I've used Python ODBC some, it works and is easy to use. > See this for a simple example: > > http://jugad.livejournal.com/2006/07/07/ > > (See the second post at that page, titled "Publishing ODBC database > content as PDF > ". The code shown in the post is not indented as per proper the Python > syntax (LiveJournal messed up the indentation), sorry about that, but > its trivial to correct if you know Python indenting rules). Also read > the Python ODBC docs and examples, of course. > > >3. Binary - Are there any utilities for compiling Ruby into a binary > > executable? The issue is twofold, speed, and not handing the > customer > the source :) > > For Python, there is py2exe (for Windows only). I used py2exe recently > and it works well enough for the simple cases that I tried. (I tried > building EXEs for a simple Python hello-world program, and for a > simple wxPython GUI app based on my xtopdf toolkit. Both worked ok.) > For cross-platform (Windows and Linux, IIRC), there is PyInstaller > (Google for it), haven't tried it out yet, just downloaded it > recently. > > I don't think you'll gain much speed by this compiling step, though > (over and above what Python gives you itself, when it compiles > your .py files to .pyc files). The purpose of py2exe is more to hide > the source code than to speed it up, as I understand (could be wrong). > > Note: py2exe only creates an EXE and DLLs needed, from your source and > its required Python modules. To create an installer, try InnoSetup > (for Windows only). I recently tried it out, version 5, again, it > worked well. Could create Windows SETUP.EXE-type installers for the > two EXEs described above. Worked ok. > > I first learned Python, have been using it for some time for various > projects, and then learned Ruby, and have done some projects with Ruby > too. > > I've been reading both the Ruby Cookbook and the Python Cookbook > rather thoroughly in the last few weeks (and trying out and modifying > many of the recipes), and what I've observed is that the two languages > are roughly similar in features. For basic features common to most > languages (constants, variables, arrays, hashes/dictionaries, file I/ > O, classes, objects, modules/libraries, etc. - they work roughly in > the same fashion - though syntax obviously differs, you can mostly do > what you can in one of them, in the other as well. (Note that I'm not > talking about libraries here - this will obviously differ as each > language will have its own set of libraries for doing various tasks, > like networking and other areas - though even here there is a good > amount of overlap/similarity.) > > For more advanced language features related to object-orientation, > metaclasses / metaprogramming, both have some support, but you might > or might not be able to do in one, what you can do in the other. > > HTH > Vasudev Ram > Site:http://www.dancingbison.com > PDF toolkit (in Python):http://sourceforge.net/projects/xtopdf > Blog:http://jugad.livejournal.com P.S.: Some more thoughts: If you'd really prefer to work in Ruby, but find after investigation, that the wxPython recommendation I've made is worth pursuing, you could check out this other approach: - Write the GUI in Python + wxPython - Write the rest of the app - the back end - in Ruby. - Connect the two via any one of the following distributed computing technology options: - sockets (lowest level, more coding needed, need to create your own proprietary, application-specific (though not necessarily very difficult) "protocol" on top of the sockets layer - XML-RPC (less coding than sockets, fairly easy to code with, supports most/all basic scalar data types (string, int) of Python/ Ruby, also supports 'structs' and arrays. XML-RPC structs are not really structs in the C sense, they more or less map to hashes/ dictionaries of Ruby/Python respectively. A Binary XML-RPC data type is also available, it works by Base-64 encoding your binary data. Have tried out this type as well as the simple scalar types, they work. (E.g. I could generate a PDF file on the server in response to a client method call, and send the PDF back to the client as the method response, using the Binary data type.) In XML-RPC you can either use the register_instance or register_function functions to register your class's callable methods or your standalone callable functions so the client can call them. Each of these approaches (register_function vs. register_instance) has its pros and cons - e.g. IIRC, you can register any number of functions, but you can only register one instance of an object - so if using this approach, you'd need to either a) have all your callable code in one class, or make that one class a manager/controler class that delegates to other classes to do the needed work. - SOAP. Ruby's stdlib has SOAP support. Python has SOAPpy and a few others, not sure whether those projects are active and supported currently. You will need to check this out. Comments similar to those for XML-RPC above. - ICE from ZeroC - www.zeroc.com . This is like a lighter CORBA. Some of the key developers are prior CORBA experts, like Michi Henning who wrote a well-known C++/CORBA book. But check out the licenses for ICE; IIRC, the open source version is under the GPL. You have to pay for a commercial license. ICE supports Python for both client and server, has Ruby support (need to check if both client and server, or client only). - HTTP calls. Use Webrick or Mongrel HTTP server libraries - you can "mount" instances of classes into the HTTP servers that these libraries allow you to create and run. (This is similar to Java servlets running inside a Java servlet container.) "Call" the methods of these instances from the Python + wxPython GUI front end via the appropriate HTTP client library (urllib or urllib2 or httplib2) for Python, open-uri for Ruby. I've checked this out (briefly), it works, and is a neat and somewhat powerful technique, IMO. (What this implies is that the client for your HTTP server, need not be a browser - it can be a command-line or GUI client; and, though you're using HTTP, you need not use HTML, and in particular, you need not render HTML in your client; you can, for instance, use XML and generate/parse it at either end.) HTH Vasudev www.dancingbison.com From morphine at despammed.com Sun Jul 1 16:13:34 2007 From: morphine at despammed.com (morphine) Date: Sun, 01 Jul 2007 22:13:34 +0200 Subject: how to send files via bluetooth with python to a mobile References: <1183294323.556314.293860@m36g2000hse.googlegroups.com> <1183305873.736724.116680@c77g2000hse.googlegroups.com> <1183306850.712226.313800@m36g2000hse.googlegroups.com> <1183310919.771396.268760@q69g2000hsb.googlegroups.com> <5eq94iF3a5b8bU1@mid.uni-berlin.de> Message-ID: <46880a0b$0$37195$4fafbaef@reader3.news.tin.it> Diez B. Roggisch wrote: > Wrap this > > http://www.zuckschwerdt.org/apidocs/ seams that python bindings are already there? http://dev.zuckschwerdt.org/openobex/wiki/ObexFtpExampleClientPython -- morphine From vedrandekovic at v-programs.com Thu Jul 26 15:32:46 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Thu, 26 Jul 2007 12:32:46 -0700 Subject: code indentation In-Reply-To: References: <1185297657.186852.136950@k79g2000hse.googlegroups.com> <87lkd5jt83.fsf@benfinney.id.au> <1185357861.989194.117000@r34g2000hsd.googlegroups.com> <1185387723.155661.311510@b79g2000hse.googlegroups.com> Message-ID: <1185478366.910475.110490@19g2000hsx.googlegroups.com> On 26 srp, 13:43, Steve Holden wrote: > Thorsten Kampe wrote: > > * (Wed, 25 Jul 2007 11:22:03 -0700) > >> On 25 srp, 17:31, Wildemar Wildenburger wrote: > >>> vedrandeko... at v-programs.com wrote: > >>>>> And while we're on the topic of communication: The original poster > >>>>> would do well to learn that increasing the number of consecutive > >>>>> punctuation marks (!!!, ???) is a sure way to turn away many people > >>>>> who would otherwise be helpful. Sentences need at most one '!' or '?', > >>>>> adding more does not improve the chances of being taken seriously. > >>>> And if you can help me than please help me , but if you can't then > >>>> please don't leave me some stupid messages > >>> Whats stupid about this? It's sane advice. > > >>> Which looks more serious to you: > > >>> this: > >>> I can't do it!!!! Can you PLEASE help me????!!!?! > > >>> or this: > >>> I don't know the answer. Can you please help me? > > >>> Even if it makes no difference to you, to many people it does. So Ben is > >>> right: People *will* take your posts more seriously if you restrict your > >>> use of punctuation (if only because its easier to read). > >>> Don't feel offended, nobody was trying to put you down. > >> On this group I ask for serious help and now we talk about > >> communication. Then I you don't know how to help me then please DON'T > >> SAY ANYTHING > > > You already got serious help even though you haven't realised that > > yet. > > We should be making allowances for this particular poster on account of > relative youth: I hadn't realised earlier, but we are dealing with a > fourteen-year-old. Since fourteen-year-olds already know everything we > should be honored we are being asked for 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 ------------- Hi again, Just one more question, can I maybe do this indentation with string e.g here is my failed example of try with string: kl="n=90;if n==90:print'kajmakimar'" for line in kl.split(";"): li=[] m=li.append(line) if line.endswith(':'): m.append("\n\t\t\t\t\t\t\t\t") print m .....so maybe if you can help me with this? Regards, Vedran (http://www.v-programs.com) From nogradi at gmail.com Sat Jul 14 05:08:40 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 14 Jul 2007 11:08:40 +0200 Subject: how to install pygame package? In-Reply-To: <1184381853.115531.122440@g37g2000prf.googlegroups.com> References: <1184303076.915138.43310@o11g2000prd.googlegroups.com> <1184381853.115531.122440@g37g2000prf.googlegroups.com> Message-ID: <5f56302b0707140208k6e465e0dt3c4fe91140deac79@mail.gmail.com> > There seems to be some problem. For the tar version, initial steps > execute OK, but after typing: > [root at localhost pygame-1.7.1release]# ./configure > bash: ./configure: No such file or directory > > So i don't hav a configure file? What should i do now? Sorry, instead of ./configure do this: python setup.py install It's a python package after all :) But first I would recommend reading http://pygame.org/install.html From mensanator at aol.com Fri Jul 13 16:46:28 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Fri, 13 Jul 2007 13:46:28 -0700 Subject: Fastest way to convert a byte of integer into a list In-Reply-To: <1184321842.921823.317470@k79g2000hse.googlegroups.com> References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> <1184321842.921823.317470@k79g2000hse.googlegroups.com> Message-ID: <1184359588.648337.24830@m3g2000hsh.googlegroups.com> On Jul 13, 5:17 am, Paul McGuire wrote: > On Jul 12, 5:34 pm, Godzilla wrote: > > > Hello, > > > I'm trying to find a way to convert an integer (8-bits long for > > starters) and converting them to a list, e.g.: > > > num = 255 > > numList = [1,1,1,1,1,1,1,1] > > > with the first element of the list being the least significant, so > > that i can keep appending to that list without having to worry about > > the size of the integer. I need to do this because some of the > > function call can return a 2 lots of 32-bit numbers. I have to find a > > way to transport this in a list... or is there a better way? > > Standing on the shoulders of previous posters, I put this together. > > -- Paul But aren't we moving backwards? The OP did ask for the fastest way. I put this together (from other posters and my own): import gmpy import time y = 2**177149 - 1 # init list of tuples by byte bytebits = lambda num : [num >> i & 1 for i in range(8)] bytes = [ tuple(bytebits(i)) for i in range(256) ] # use bytes lookup to get bits in a 32-bit integer bits = lambda num : sum((bytes[num >> i & 255] for i in range(0,32,8)), ()) # use base-2 log to find how many bits in an integer of arbitrary length from math import log,ceil log_of_2 = log(2) numBits = lambda num : int(ceil(log(num)/log_of_2)) # expand bits to integers of arbitrary length arbBits = lambda num : sum((bytes[num >> i & 255] for i in range(0,numBits(num),8)),()) t0 = time.time() L = arbBits(y) t1 = time.time() print 'Paul McGuire algorithm:',t1-t0 t0 = time.time() L = [y >> i & 1 for i in range(177149)] t1 = time.time() print ' Matimus algorithm:',t1-t0 x = gmpy.mpz(2**177149 - 1) t0 = time.time() L = [gmpy.getbit(x,i) for i in range(177149)] t1 = time.time() print ' Mensanator algorithm:',t1-t0 ## Paul McGuire algorithm: 17.4839999676 ## Matimus algorithm: 3.28100013733 ## Mensanator algorithm: 0.125 From JHoover at fbi.gov Thu Jul 19 00:52:48 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Thu, 19 Jul 2007 00:52:48 -0400 Subject: idiom for RE matching Message-ID: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> I have some code which relies on running each line of a file through a large number of regexes which may or may not apply. For each pattern I want to match I've been writing gotit = mypattern.findall(line) if gotit: gotit = gotit[0] ...do whatever else... This seems kind of clunky. Is there a prettier way to handle this? I've also been assuming that using the re functions that create match objects is slower/heavier than dealing with the simple list returned by findall(). I've profiled it and these matches are the biggest part of the running time of the program, so I really would rather not use anything slower. From edreamleo at charter.net Tue Jul 3 11:59:12 2007 From: edreamleo at charter.net (Edward K Ream) Date: Tue, 3 Jul 2007 10:59:12 -0500 Subject: ANN: Leo 4.4.3.1 released Message-ID: Leo 4.4.3.1 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.3.1: ---------------------------- - Fixed a few minor bugs reported since Leo 4.4.3 was released. - Added better support for unit testing in Leo. 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 -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From yoav.goldberg at gmail.com Tue Jul 24 10:08:22 2007 From: yoav.goldberg at gmail.com (Yoav Goldberg) Date: Tue, 24 Jul 2007 17:08:22 +0300 Subject: for line in file('filename'): Message-ID: I use the idiom "for line in file('filename'): do_something(line)" quite a lot. Does it close the opened file at the end of the loop, or do I have to explicitly save the file object and close it afterward? Yoav -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Tue Jul 24 16:17:58 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 24 Jul 2007 22:17:58 +0200 Subject: Cleaning up a string References: Message-ID: James Stroud wrote: > I dashed off the following function to clean a string in a little > program I wrote: > > def cleanup(astr, changes): > for f,t in changes: > atr = astr.replace(f, t) > return astr > > where changes would be a tuple, for example: > > changes = ( > ('%', '\%'), > ('$', '\$'), > ('-', '_') > ) > > > If these were were single replacements (like the last), string.translate > would be the way to go. As it is, however, the above seems fairly > inefficient as it potentially creates a new string at each round. Does > some function or library exist for these types of transformations that > works more like string.translate or is the above the best one can hope > to do without writing some C? I'm guessing that "if s in astr" type > optimizations are already done in the replace() method, so that is not > really what I'm getting after. unicode.translate() supports this kind of replacement... >>> u"a % b $ c-d".translate(dict((ord(a), unicode(b)) for a, b in changes)) u'a \\% b \\$ c_d' and re.compile(...).sub() accepts a function: >>> def replace(match, lookup=dict(changes)): ... return lookup[match.group()] ... >>> re.compile("([$%-])").sub(replace, "a % b $ c-d") 'a \\% b \\$ c_d' Peter From yoav.goldberg at gmail.com Sat Jul 21 13:00:27 2007 From: yoav.goldberg at gmail.com (Yoav Goldberg) Date: Sat, 21 Jul 2007 20:00:27 +0300 Subject: importing a module from a specific directory Message-ID: I'm using python for research related programming, and so I write many experimental small pieces of code. I would like to organize them into directory structure in which there is a 'main' directory, and under it directories for specific sub-tasks, or sub-experiments, I'm running (let's call them 'A', 'B', 'C'). I would like to have some common library code sit in 'main', and then use it from scripts in the sub-tasks directories. I also want the code in the sub-tasks to be quick-and-dirty fast to write, so things like 'import sys; sys.append('..');' on the top of each script is a bit awkward. Is there a neat clean way of achieving the code organization? How do you organize your code in such settings? Thanks, Yoav -------------- next part -------------- An HTML attachment was scrubbed... URL: From oneelkruns at hotmail.com Mon Jul 2 22:01:39 2007 From: oneelkruns at hotmail.com (rtk) Date: Mon, 02 Jul 2007 19:01:39 -0700 Subject: Tiny/small/minimalist Python? In-Reply-To: <468997c7$0$327$e4fe514c@news.xs4all.nl> References: <1183332951.122782.212720@o11g2000prd.googlegroups.com> <7xved3satm.fsf@ruckus.brouhaha.com> <1183389420.175712.59460@z28g2000prd.googlegroups.com> <7xmyyeizf8.fsf@ruckus.brouhaha.com> <468997c7$0$327$e4fe514c@news.xs4all.nl> Message-ID: <1183428099.746633.252870@m37g2000prh.googlegroups.com> On Jul 2, 6:26 pm, Irmen de Jong wrote: > Back in the days my port of Python to the Commodore Amiga machine ran > quite comfortably on a 50 mhz CPU with 4 Mb of RAM. (ok ok it was > Python 1.5.2, that has to be said). > Python started in about 5 seconds on that Amiga if I remember > correctly. I'm quite sure your 'ancient' DEC Alpha box is way more > powerful than my Amiga back then. Yes, I agree (the box in question is an AlphaServer 1000 4/200), but the killer is the fact that the Alpha is emulating *machine instructions* that are part of the Python image which are not part of the instruction set of that Alpha. That's what kills performance. When I asked about it on the VMS Python forum I was told to give my Alpha to a museum and get a more powerful machine :) I did look briefly at Python 1.5.2, since it is simpler, but I'm taking the trouble I've had as an excuse to learn a new language. So far, I'm liking Lua, save the big pet peeve of starting indices at 1 and not 0 as all sane people do. I'm currently using Python quite a bit for other projects, so it won't be neglected. Ron From kj7ny at nakore.com Mon Jul 9 20:51:18 2007 From: kj7ny at nakore.com (kj7ny) Date: Mon, 09 Jul 2007 17:51:18 -0700 Subject: How do I remotely access Scheduled Tasks from Windows XP to Windows Server 2003? In-Reply-To: <1183226243_18235@sp12lax.superfeed.net> References: <1183152711.161151.285960@i13g2000prf.googlegroups.com> <1183226243_18235@sp12lax.superfeed.net> Message-ID: <1184028678.497589.268020@z28g2000prd.googlegroups.com> On Jun 30, 10:55 am, "Roger Upole" wrote: > "kj7ny" wrote: > > How can I access and manipulateScheduledTasksin Windows using > > Python? > > > I have a Windows XP workstation running Python 2.4.4 using the > > win32all modules to control the windows services on multiple Windows > > 2003 servers. It works great. > > > However, I also need to remotely collect the settings for the > >scheduledtasks(on those same Windows 2003 servers) and then > > manipulate those task settings. > > > At the very least, I need to find out which ones are enabled and then > > be able to disable and re-enable thosetasksat will. It would be > > better to be able to also detect the account each task runs as so that > > I could only disable selectedtasks, but I'll any help I can get. > > > Thanks, > > Pywin32 comes with a module that lets you do this, win32com.taskscheduler. > You can use PyITaskScheduler.SetTargetComputer to accesstaskson remote > machines. > > Roger > > ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----http://www.newsfeeds.comThe #1 Newsgroup Service in the World! >100,000 Newsgroups > ---= East/West-Coast Server Farms - Total Privacy via Encryption =--- I FINALLY found taskscheduler (with the help of your post). I found it under ...\Python243\Lib\site-packages\win32comext\taskscheduler ... and, there seems to be a /test/ directory with some examples. Haven't tried them yet, but they should get me started. Thanks, From see at signature.invalid Thu Jul 12 13:56:30 2007 From: see at signature.invalid (Douglas Wells) Date: Thu, 12 Jul 2007 13:56:30 -0400 (EDT) Subject: asyncore and OOB data References: <1184172867.420979.215300@q75g2000hsh.googlegroups.com> <1184206297.813178.141000@n2g2000hse.googlegroups.com> Message-ID: In article <1184206297.813178.141000 at n2g2000hse.googlegroups.com>, billiejoex writes: > Douglas Wells wrote: > > > Second, when I look at the FTP specification, I don't find the > > concept of OOB anywhere. So, it's not clear what OOB data would > > mean in terms of the defined FTP commands in any case. > > Steve Holde wrote: > > > You are correct, however, in stating that the FTP > > protocol doesn't support or implement out-of-band > > data transmissions. > > Wait a sec. RFC959 [1], on chapter 4.1.3 says: > > [ ... ] > > I believe that the TCP "urgent" flag, activated by using > socket.MSG_OOB, should be set when client must send the "Sync" signal > (RFC854 [2] talks about it). I think that you do not find references > of OOB in RFC959 (FTP) just because it is specified into RFC854 > (Telnet). The point that I was trying to make, which Steve made more clearly that I did in the referenced paragraph, is that FTP doesn't support OOB data transmission, not that RFP doesn't require the use of OOB information (in the form of the Telnet Synch signal). Note that FTP limits the commands that may be issues while a data transfer in progress. The RFC isn't totally explicit, but the general notion is that issuing a data transfer command (such as STOR or RETR) is not allowed while another data transfer is in progress. - dmw -- . Douglas Wells . Connection Technologies . . Internet: -sp9804- -at - contek.com- . From S.Mientki-nospam at mailbox.kun.nl Mon Jul 16 15:23:03 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 16 Jul 2007 21:23:03 +0200 Subject: running a Delphi part from Python ? In-Reply-To: <1184598145.577779.209070@w3g2000hsg.googlegroups.com> References: <889c1$469b275c$d443bb3a$2876@news.speedlinq.nl> <469b2b65$0$21672$426a74cc@news.free.fr> <86c61$469b30d1$d443bb3a$15805@news.speedlinq.nl> <469b3530$0$26995$426a74cc@news.free.fr> <47dce$469b3a07$d443bb3a$26795@news.speedlinq.nl> <1184598145.577779.209070@w3g2000hsg.googlegroups.com> Message-ID: > > Of course You can always write one, that's succicient for Your needs, > and make it available under GPL. ;-) Why not BSD ? But I've to read all the licenses of the used components first ;-) cheers, Stef Mientki From siegfried at heintze.com Thu Jul 5 09:54:58 2007 From: siegfried at heintze.com (Siegfried Heintze) Date: Thu, 5 Jul 2007 07:54:58 -0600 Subject: IDEs for COM scripting: C# v. Python v. Iron Python v. JPython References: Message-ID: Can someone suggest some criterion for selecting Python, JPython or Iron Python for COM Scripting? I have not looked: I assume there are multiple eclipse plugins for Python/JPython/Iron Python. Could someone recommend one? I'll also try out eric that was mentioned previously. I figured out my problem with Groovy/COM/Eclipse scripting: I had outlook running in another remote desktop session and discovered that if I run my script in the same session as I am running outlook in, it works. I assume the situation would be the same with Python. Since Groovy/COM/Eclipse works for this purpose, I assume JPython with JaWin/Jacob would work too. Thanks, Siegfried From gh at ghaering.de Tue Jul 17 19:32:38 2007 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 18 Jul 2007 01:32:38 +0200 Subject: [ANN] pysqlite 2.3.5 released Message-ID: <469D5196.5060004@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 pysqlite 2.3.5 released ======================= I'm pleased to announce the availability of pysqlite 2.3.5. This is a bugfix release. Go to http://pysqlite.org/ for downloads, online documentation and reporting bugs. What is pysqlite? pysqlite is a DB-API 2.0-compliant database interface for SQLite. SQLite is a relational database management system contained in a relatively small C library. It is a public domain project created by D. Richard Hipp. Unlike the usual client-server paradigm, the SQLite engine is not a standalone process with which the program communicates, but is linked in and thus becomes an integral part of the program. The library implements most of SQL-92 standard, including transactions, triggers and most of complex queries. pysqlite makes this powerful embedded SQL engine available to Python programmers. It stays compatible with the Python database API specification 2.0 as much as possible, but also exposes most of SQLite's native API, so that it is for example possible to create user-defined SQL functions and aggregates in Python. If you need a relational database for your applications, or even small tools or helper scripts, pysqlite is often a good fit. It's easy to use, easy to deploy, and does not depend on any other Python libraries or platform libraries, except SQLite. SQLite itself is ported to most platforms you'd ever care about. It's often a good alternative to MySQL, the Microsoft JET engine or the MSDE, without having any of their license and deployment issues. pysqlite can be downloaded from http://pysqlite.org/ - Sources and Windows binaries for Python 2.5, 2.4 and Python 2.3 are available. ======= CHANGES ======= Ticket #203: Using mappings and sequences as parameters works now too. I hope this doesn't encourage you to actually use that "feature". It's actually possible to build a layer on top of the DB-API instead of cramming everything into it. Ticket #97: We now know about implicit ROLLBACKs that the SQLite engine issued. Removed paragraph in docs about ON CONFLICT ROLLBACK not working. It works now. Performance optimizations that pay off especially for mass DML operations (inserts, updates, deletes). Performance here is on par with apsw now. See http://initd.org/tracker/pysqlite/wiki/PysqliteTwoBenchmarks for a benchmark of all pysqlite 2.x releases so far. Last two: pysqlite 2.3.4 average insert time: 7.037440 seconds average fetch time: 3.066811 seconds -------------------------------------------------- pysqlite 2.3.5 average insert time: 2.788332 seconds average fetch time: 3.095180 seconds -------------------------------------------------- - - A Python 2.3 compatibility fix in the test suite. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.6 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFGnVGWdIO4ozGCH14RAkgQAKCTcumGWSTrQn+zK59kR2RUj29ZFACfcPVB 0WBUZOhw8ett2MPw+0qlPjw= =d+mW -----END PGP SIGNATURE----- From donn at u.washington.edu Thu Jul 12 13:20:59 2007 From: donn at u.washington.edu (Donn Cave) Date: Thu, 12 Jul 2007 10:20:59 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: In article , Steve Holden wrote: > Donn Cave wrote: > > Someday we will look at "variables" like we look at goto. > > > How very functional. I believe some people naturally think in terms of > state transformations and some in terms of functional evaluation. I am > pretty firmly in the former camp myself, so variables are a natural > repository for state to me. Don't worry - there will be a state transformation monad for you! Nature or nurture? it would be interesting to see some identical twin studies on novice programmers. Since few of us were exposed first to strictly functional programming, though, you have to wonder. In its day, goto was of course very well loved. Donn Cave, donn at u.washington.edu From nospam-abuse at ilyaz.org Wed Jul 11 18:04:35 2007 From: nospam-abuse at ilyaz.org (Ilya Zakharevich) Date: Wed, 11 Jul 2007 22:04:35 +0000 (UTC) Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: [A complimentary Cc of this posting was sent to Martin Gregorie ], who wrote in article : > >> Its in "A Short History of Time". Sorry I can't quote chapter or page, > >> but a friend borrowed my copy and lent me Dawkins "Climbing Mount > >> Improbable" before vanishing, never to be seen since. Not an equal > >> exchange: I preferred ASHOT to CMI. > Oops - I should have written "A Brief History of Time". It was the first > edition, so I don't know if it was altered/edited out of later versions. > > I would prefer a reference to a peer-reviewed paper. ;-) > Sure, but I don't think you'll find one. It was in a descriptive, rather > than rigorous, passage. But then, the book famously had only one > equation in it. [I've heard about this book.] My point is that attributing something to SH due to it appearing in ABHoT is like attributing it to you since it was mentioned in your post... Hope this helps, Ilya From garrickp at gmail.com Thu Jul 19 12:21:54 2007 From: garrickp at gmail.com (Falcolas) Date: Thu, 19 Jul 2007 09:21:54 -0700 Subject: Copy List In-Reply-To: References: <-29831789359750479@unknownmsgid> <6a2ccd190707180544k4909ad3enc6a962917a26f43d@mail.gmail.com> Message-ID: <1184862114.094387.257580@i13g2000prf.googlegroups.com> On Jul 18, 6:56 am, "Rustom Mody" wrote: > This is shallow copy > If you want deep copy then > from copy import deepcopy What will a "deep copy" of a list give you that using the slice notation will not? From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jul 10 17:36:13 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 10 Jul 2007 23:36:13 +0200 Subject: bool behavior in Python 3000? References: Message-ID: <5ficedF3cram2U1@mid.individual.net> Alan Isaac wrote: > Hoping the bool type will be fixed will be fixed, Is there any type named "bool" in standard Python? Regards, Bj?rn -- BOFH excuse #207: We are currently trying a new concept of using a live mouse. Unfortunately, one has yet to survive being hooked up to the computer.....please bear with us. From horpner at yahoo.com Wed Jul 4 12:41:11 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 04 Jul 2007 16:41:11 GMT Subject: what is wrong with that r"\" References: <5f1ehiF3a62csU1@mid.uni-berlin.de> <%UPii.36166$G23.16677@newsreading01.news.tds.net> Message-ID: On 2007-07-04, Neil Cerutti wrote: > On 2007-07-04, Marc 'BlackJack' Rintsch wrote: >> On Wed, 04 Jul 2007 11:21:14 +0000, Neil Cerutti wrote: >> >>> If the escaped quotes didn't function in raw strings, I'd be >>> unable to construct (with a single notation) a regex that >>> included both kinds of quotes at once. >>> >>> re.compile(r"'\"") >> >> Where's the problem!? :: >> >> re.compile(r''''"''') > > That incurs the problem that you can't end with a '. So you > can't end with *something* either way. I take that back. With good planning, you can end with whichever you need by choosing the other delimiter. Oh well. It seemed like a good explanation at first. -- Neil Cerutti From nospam at williamsdurkin.co.uk Sun Jul 1 02:47:49 2007 From: nospam at williamsdurkin.co.uk (Martin Durkin) Date: 1 Jul 2007 06:47:49 GMT Subject: Reversing a string References: <1182997438.541012.54100@o61g2000hsh.googlegroups.com> Message-ID: ptn wrote in news:1182997438.541012.54100 @o61g2000hsh.googlegroups.com: > >>>> def rev(x): > mylist = [] > for char in x: > mylist.append(char) > mylist.reverse() > for letter in mylist: > print letter > > However, compare the incredible difference in clarity and elegance > between that and: > >> >>> print "\n".join("spam"[::-1]) > OK, maybe I'm missing the point here as I'm new to Python. The first one seems clearer to me. What am I missing? Martin From pydecker at gmail.com Tue Jul 10 09:39:08 2007 From: pydecker at gmail.com (Peter Decker) Date: Tue, 10 Jul 2007 09:39:08 -0400 Subject: highly einteractive editor for python In-Reply-To: References: Message-ID: On 7/10/07, Atul Bhingarde wrote: > What I want to see is that it is possible to create a python based > application in a environment where I can see the results as I am creating > it, specifically gui widgets (from say TK). This will provide a robust > mechanism to see gui layout as well. This isn't for Tk, but for wxPython-based development, but you might want to look at Dabo's visual tools. Their Class Designer allows you to visually develop your application's windows, allowing you to focus on coding the logic instead of having to guess how what your UI will look like. Check out the screencasts (hey, how else can you see the advantage of a visual tool?) at http://dabodev.com/documentation. The best ones to start with are the two on 'Building a Database App in the Class Designer'. They show some of the database connectivity stuff, too, but that's not required. I create apps without databases all the time with Dabo. -- # p.d. From gh at ghaering.de Tue Jul 17 19:52:35 2007 From: gh at ghaering.de (=?UTF-8?B?R2VyaGFyZCBIw6RyaW5n?=) Date: Wed, 18 Jul 2007 01:52:35 +0200 Subject: sqlite3 db update extremely slow In-Reply-To: <1184627356.324577.257470@g4g2000hsf.googlegroups.com> References: <1184613750.873464.312390@r34g2000hsd.googlegroups.com> <1184627356.324577.257470@g4g2000hsf.googlegroups.com> Message-ID: coldpizza wrote: > Thanks a lot, Roel, adding a single commit() at the end did solve the > speed problem. > > Another question is do I have to explicitly close the DB connection, > or is it automatically garbage collected? Is it Ok to no have any > cleanup code? > > Another question would be how to define the encoding for newly added > records? > And how do set the encoding for the retrieved records? Is it always > utf-8 by default? SQLite databases store text in UTF-8 encoding. If you use pysqlite, and always use unicode strings, you will never have any problems with that. pysqlite does not rap on your knuckles if you store arbitrary encodings in the database, but you will feel sorry once you try to fetch the data: >>> from pysqlite2 import dbapi2 as sqlite >>> con = sqlite.connect(":memory:") >>> binary_rubbish = chr(130) + chr(200) >>> con.execute("create table foo(bar)") >>> con.execute("insert into foo(bar) values (?)", (binary_rubbish,)) >>> # so far, so good ... ... # watch now ... >>> con.execute("select bar from foo") Traceback (most recent call last): File "", line 1, in pysqlite2.dbapi2.OperationalError: Could not decode to UTF-8 column 'bar' with text '??' >>> HTH -- Gerhard From missive at hotmail.com Fri Jul 27 20:17:01 2007 From: missive at hotmail.com (Lee Harr) Date: Sat, 28 Jul 2007 00:17:01 GMT Subject: curses/urwid simple menu References: Message-ID: > SGVsbG8uIENvdWxkIHlvdSBoZWxwIG1lLi4uSSBuZWVkIHRvIGNyZWF0ZSBhcHBsaWNhdGlvbiB3 > aXRoIHVyd2lkIG9yIGN1cnNlcwpzdXBwb3J0LiBIYXZlIHlvdSBnb3QgYSBwcmV0dHkgc2ltcGxl > IGV4YW1wbGUgd2l0aCBpdD8KCgotLSAKUG96ZHJhd2lhbSBMZXN6ZWsgTWm2Ck5vdGhpbmcgaXMg > c2VjdXJlLCBwYXJhbm9pYSBpcyB5b3VyIGZyaWVuZC4K >>> s = '''SGVsbG8uIENvdWxkIHlvdSBoZWxwIG1lLi4uSSBuZWVkIHRvIGNyZWF0ZSBhcHBsaWNhdGlvbiB3 ... aXRoIHVyd2lkIG9yIGN1cnNlcwpzdXBwb3J0LiBIYXZlIHlvdSBnb3QgYSBwcmV0dHkgc2ltcGxl ... IGV4YW1wbGUgd2l0aCBpdD8KCgotLSAKUG96ZHJhd2lhbSBMZXN6ZWsgTWm2Ck5vdGhpbmcgaXMg ... c2VjdXJlLCBwYXJhbm9pYSBpcyB5b3VyIGZyaWVuZC4K''' >>> print s.decode('base64') Hello. Could you help me...I need to create application with urwid or curses support. Have you got a pretty simple example with it? I recommend that you post in plain text, since your message comes through like the above in my reader, and probably to other people also. Here is the first hit googling for python curses: http://www.amk.ca/python/howto/curses/ Here is an urwid tutorial: http://excess.org/urwid/tutorial.html From roger.miller at nova-sol.com Thu Jul 19 17:36:22 2007 From: roger.miller at nova-sol.com (Roger Miller) Date: Thu, 19 Jul 2007 14:36:22 -0700 Subject: idiom for RE matching In-Reply-To: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> Message-ID: <1184880982.831654.308200@e16g2000pri.googlegroups.com> On Jul 18, 6:52 pm, Gordon Airporte wrote: > ... > I've also been assuming that using the re functions that create match > objects is slower/heavier than dealing with the simple list returned by > findall(). I've profiled it and these matches are the biggest part of > the running time of the program, so I really would rather not use > anything slower. My guess would be that searching for more matches after finding the first would be more expensive than creating a match object. But that would probably depend on the nature of your data and REs, so you need to test it both ways if you are concerned about performance. It would be nice if findall() had an optional parameter to limit the number of matches, similar to the maxsplit parameter of string.split(). From deets at nospam.web.de Fri Jul 27 05:53:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 27 Jul 2007 11:53:10 +0200 Subject: Submit form, open result in a browser In-Reply-To: References: Message-ID: <5gttk9F3gcccvU1@mid.uni-berlin.de> Tina I schrieb: > Hi, > > Is there a way to submit a form and then open the resulting page in the > default browser? (Writing the form submission code is not a problem by > the way) > I guess what I'm asking is how I can get the resulting URL and feed it > to the webbrowser module. > I need to do it this way because the site owners will not let me parse > the page and show the result inside my application... loss of > advertising revenue I guess. And since it's just a small added feature > to the application, opening it in a browser is fine. I just need to get > an idea on how to do it... That's not how HTTP works. Either you use e.g. urllib to make a http call and save the resulting html into a temporary file - and then you point your webbrowser to that. Or you open the webbrowser with the url + parameters. But there is no "result url" Diez From lance at augustmail.com Thu Jul 19 17:33:22 2007 From: lance at augustmail.com (Lance Hoffmeyer) Date: Thu, 19 Jul 2007 21:33:22 GMT Subject: win32com ppt embedded object numbers reverting back to original numbers Message-ID: Hey all, I have a script that takes numbers from XL and inserts them into an embedded MSGRAPH dataset in PPT. The problem is that when I reopen the modified document that has been saved as a new filename and activate the embedded datasheet the new numbers that were inserted disappear and the old, original numbers come back? I thought that adding these lines and resetting these variables was supposed to prevent this from happening? del oGraph del PWB del oHEADER del oVALUE Anyone had experience with this and know what I need to do to keep the embedded datasheet from reverting back to it's original numbers after modification? Thanks in advance, Lance ################################################################################################################################################################################# ################################################################################################################################################################################# # ADD THIS INTO A MODULE IN PPT TO OBTAIN THE PROG ID OF A SLIDE #Sub test() #MsgBox "The Slide ID of the current slide is:" & _ # ActiveWindow.View.Slide.SlideID #End Sub ################################################################################################################################################################################# def attributesbyID(row,base,slideID,spreadsheet): sh = wb.Worksheets (spreadsheet) sh.Select() LIST = xlparams(row, base) ################ POWERPOINT SECTION ###################### for shape in WB.Slides.FindBySlideID(slideID).Shapes: if (shape.Type== 7): for oXLROW,oXLBASE,oXLLASTCOL,oPPTCELL,oPPTHEADERCELL in LIST: oVALUE = sh.Cells(oXLROW,oXLLASTCOL).Value oHEADER = sh.Cells(base-1,oXLLASTCOL).Value + " (n=" + str(int(sh.Cells(oXLBASE,oXLLASTCOL).Value)) + ")" PWB = WB.Slides.FindBySlideID(slideID).Shapes(shape.Name) oGraph = PWB.OLEFormat.Object oGraph.Application.datasheet.Range(oPPTCELL).Value = oVALUE oGraph.Application.datasheet.Range(oPPTHEADERCELL).Value = oHEADER oGraph.Application.datasheet.Font.Bold=False del oGraph del PWB del oHEADER del oVALUE ########################################################### ################################################################################################################################################################################# ################################################################################################################################################################################# ################################################################################################################################################################################# def xlparams(row, base): lastcol=LASTCOL ############### EXCEL SECTION TO GET NUMBERS ############# thelist=((row,base,lastcol,"A13","013"),(row,base,lastcol-1,"A14","014"),(row,base,lastcol-2,"A15","015"),(row,base,lastcol-3,"A16","016"), (row+20,base+20,lastcol,"A9","09"),(row+20,base+20,lastcol-1,"A10","010"),(row+20,base+20,lastcol-2,"A11","011"),(row+20,base+20,lastcol-3,"A12","012"), (row+40,base+40,lastcol,"A5","05"),(row+40,base+40,lastcol-1,"A6","06" ), (row+40,base+40,lastcol-2,"A7","07" ), (row+40,base+40,lastcol-3,"A8","08" ), (row+60,base+60,lastcol,"A1","01"),(row+60,base+60,lastcol-1,"A2","02" ), (row+60,base+60,lastcol-2,"A3","03" ), (row+60,base+60,lastcol-3,"A4","04" )) ########################################################## return thelist ## attribute(ROW NUMBER, BASE ROW NUMBER, SLIDE NUMBER) attributesbyID(14,12,839,"Attributes(116-144)") # This medication has a convenient dosing frequency From irstas at gmail.com Sun Jul 22 03:06:50 2007 From: irstas at gmail.com (irstas at gmail.com) Date: Sun, 22 Jul 2007 07:06:50 -0000 Subject: Regex doesn't support MULTILINE? In-Reply-To: References: Message-ID: <1185088010.129464.213440@k79g2000hse.googlegroups.com> On Jul 22, 7:56 am, Gilles Ganault wrote: > On Sat, 21 Jul 2007 22:18:56 -0400, Carsten Haese > > wrote: > >That's your problem right there. RE is not the right tool for that job. > >Use an actual HTML parser such as BeautifulSoup > > Thanks a lot for the tip. I tried it, and it does look interesting, > although I've been unsuccessful using a regex with BS to find all > occurences of the pattern. > > Incidently, as far as using Re alone is concerned, it appears that > re.MULTILINE isn't enough to get Re to include newlines: re.DOTLINE > must be added. > > Problem is, when I add re.DOTLINE, the search takes less than a second > for a 500KB file... and about 1mn30 for a file that's 1MB, with both > files holding similar contents. > > Why such a huge difference in performance? > > pattern = "(\d+:\d+).*?" That .*? can really slow it down if the following pattern can't be found. It may end up looking until the end of the file for proper continuation of the pattern and fail, and then start again. Without DOTALL it would only look until the end of the line so performance would stay bearable. Your 1.5MB file might have for example '13:34< /span>'*10000 as its contents. Because the < /span> doesn't match , it would end up looking till the end of the file for and not finding it. And then move on to the next occurence of '
    ), you could maybe use negated char range: "(\d+:\d+)[^<]*" This pattern should be very fast for all inputs because the [^<]* can't match stuff indefinitely until the end of the file - only until the next HTML element comes around. Or if you don't care about anything but those numbers, you should just match this: "(\d+:\d+)" From afriere at yahoo.co.uk Tue Jul 10 04:44:11 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 10 Jul 2007 01:44:11 -0700 Subject: Comparing modified elements in Sets In-Reply-To: <1184011034.839268.116730@r34g2000hsd.googlegroups.com> References: <1184011034.839268.116730@r34g2000hsd.googlegroups.com> Message-ID: <1184057051.278634.25170@x35g2000prf.googlegroups.com> On Jul 10, 5:57 am, ChrisEdge... at gmail.com wrote: > I'd like to be able to compare set 1 with set 2 and have it match > filename1 and filename3, or compare set 1 with 3 and get back > filename1, filename2. etc. > > Is there a way for me to do this inside the compare function, rather > than having to make duplicate copies of each set? Is there a will? Inevitably there is a way! Whether you should take it is another question entirely. ;) Assuming by 'compare' function you mean such methods as 'difference,' 'symetric_difference', 'intersection' and the like... here's a nasty little hack (using the old-school Set from sets.py) It's not to spec (you get the tails back in the result, but that's easily fixed), and it only implements a replacement method for 'difference' (called 'tailess_difference). I apologise if the google groups mailer kludges the indentation ... ----- from sets import Set from itertools import ifilterfalse from os.path import splitext class BodgySet (Set) : def tailess_difference (self, other) : """Return, as a new BodgySet, the difference of two sets, where element identity ignores all characters from the last stop (period). NOTE: As currently implemented all elements of said sets must be strings (fix this in self.has_key)!!! """ assert other.__class__ is self.__class__ result = self.__class__() data = result._data value = True for elt in ifilterfalse(other.has_key, self) : data[elt] = value return result def has_key (self, target) : thead, ttail = splitext(target) for key in self._data.keys() : khead, ktail = splitext(key) if thead == khead : return True ----- Using this hacked set: >>> a = BodgySet(['a1.txt', 'a2.txt']) >>> b = BodgySet(['a1.xml', 'a2.xml', 'a3.xml']) >>> b.tailess_difference(a) BodgySet(['a3.xml']) Is that the kind of thing you had in mind? While it can be done, I would prefer to make copies of the sets, with a cast list comprehension something like: set([os.path.splitext(x)[0] for x in orig_set]). Much better readibility and probably greater efficiency (I haven't bothered timing or dissing it mind). From dlomsak at gmail.com Mon Jul 2 09:53:25 2007 From: dlomsak at gmail.com (dlomsak) Date: Mon, 02 Jul 2007 06:53:25 -0700 Subject: object references/memory access In-Reply-To: <1i0kq0f.1m7ykg7xajggbN%aleax@mac.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1i0kq0f.1m7ykg7xajggbN%aleax@mac.com> Message-ID: <1183384405.586233.259150@k29g2000hsd.googlegroups.com> Okay, Im back at work and got to put some of these suggestions to use. cPickle is doing a great job a hiking up the serialization rate and cutting out the +=data helped a lot too. The entire search process now for this same data set is down to about 4-5 seconds from pressing 'search' to having the records posted to the browser. Only a fraction of a second is spent transmitting the data now. Some of the time is spent waiting for the sockets to actually make their connection. I'll be now looking into FastCGI to see how much more time I can trim off the total process. Once again I would like to say thanks to everyone for the help and taking the time out to give me some example code to study. I'm glad that what I thought I wanted to do is not necessary and that the sockets can send at the speed I hoped they could. This was my first posting in this group and I plan to remain active and try to help out where I can. I am fully statisfied with the responses and consider my problem solved. From bj_666 at gmx.net Sun Jul 22 05:10:42 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Jul 2007 09:10:42 GMT Subject: simpleJSON pack binary data References: Message-ID: <5ggl8iF3g1e4eU1@mid.uni-berlin.de> On Sat, 21 Jul 2007 19:13:22 -0700, Andrey wrote: > My question is, anyone will suggest a workaround to this error? > i really like to pack my raw image data into the JSON, so my other > programming script can read the array easily JSON is a text format so you have to encode the binary data somehow. I'd use base64. It's available as codec for `str.encode()`/`str.decode()`. In [10]: '\x00\xff\xaa' Out[10]: '\x00\xff\xaa' In [11]: '\x00\xff\xaa'.encode('base64') Out[11]: 'AP+q\n' In [12]: _.decode('base64') Out[12]: '\x00\xff\xaa' Ciao, Marc 'BlackJack' Rintsch From jeffober at gmail.com Wed Jul 25 13:33:13 2007 From: jeffober at gmail.com (Jeff) Date: Wed, 25 Jul 2007 17:33:13 -0000 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <1185384306.104549.287510@19g2000hsx.googlegroups.com> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <1185379218.286977.124040@19g2000hsx.googlegroups.com> <1185384306.104549.287510@19g2000hsx.googlegroups.com> Message-ID: <1185384793.577650.256310@d55g2000hsg.googlegroups.com> Here's a quick flatten() function: def flatten(obj): if type(obj) not in (list, tuple, str): raise TypeError("String, list, or tuple expected in flatten().") if len(obj) == 1: if type(obj[0]) in (tuple, list): return flatten(obj[0]) else: return [obj[0]] else: return [obj[0]] + flatten(obj[1:]) x = [1, 2, (3, 4)] y = (1, 2, [3, 4]) z = "It even works with strings!" d = {"foo": "bar", "baz": "bat"} print flatten(x) print flatten(y) print flatten(z) print flatten(d) From Eric_Dexter at msn.com Tue Jul 24 19:26:35 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Tue, 24 Jul 2007 16:26:35 -0700 Subject: From D In-Reply-To: <1185272393.484032.125180@22g2000hsm.googlegroups.com> References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> Message-ID: <1185319595.330135.48130@57g2000hsv.googlegroups.com> On Jul 24, 5:19 am, bearophileH... at lycos.com wrote: > There are various things I like about the D language that I think > Python too may enjoy. Here are few bits (mostly syntactical ones): > > 1) (we have discussed part of this in the past) You can put > underscores inside number literals, like 1_000_000, the compiler > doesn't enforce the position of such underscores, so you can also put > them like this: 1_00_000. You can put them in literals of decimals, > binary, hex, etc. I think it's quite useful, because when in Python > code I have a line like: > for i in xrange(1000000): > I need some time to count the zeros, because the lower levels of my > visual systems can't count/group them quickly (perceptually). While in > a syntax like: > for i in xrange(1_000_000): > my eyes help me group them at once. > > 2) Base 2 number literals, and base 2 "%b" printing with the writefln. > Base-2 numbers are less common in Python code, but once in a while I > use them. For example: > import std.stdio; > void main() { > auto x = 0b0100_0011; > writefln("%b", x); > writefln("%.8b", x); > writefln(x);} > > Prints: > 1000011 > 01000011 > 67 > > 3) All string literals are multi line. So you can write: > a = "how are > you"; > There's no need for """ """. > > 4) With D I have created an xsplit() generator, and from my tests it's > quite faster than the split(), expecially if the string/lines you want > to split are few hundred chars long or more (it's not faster if you > want to split very little strings). So I think Python can enjoy such > string method too (you can probably simulate an xsplit with a regular > expression, but the same is true for some other string methods too). > > Bye, > bearophile I think there is a language bridge so that you can compile d for python.. looks realy easy but I have python 2.5 and panda and it try's to go for the panda instalation. It looks much easier than c to use with python in fact.. I don't know if that would change the speed of it though to be in a library. https://sourceforge.net/projects/dex-tracker From bravo.loic at gmail.com Mon Jul 16 06:29:56 2007 From: bravo.loic at gmail.com (bravo.loic at gmail.com) Date: Mon, 16 Jul 2007 03:29:56 -0700 Subject: Compiling python2.5 on IBM AIX Message-ID: <1184581796.377610.98230@o61g2000hsh.googlegroups.com> hi, I'm trying to make a local install of python 2.5 on AIX and I'm getting some trouble with _curses. Here is how I tried to compile it : export BASE=/usr/local/python251 cd Python.2.5.1 ./configure --prefix=${BASE}/\ LDFLAGS="-L\${BASE}/lib/"\ PPFLAGS="-I\${BASE}/include/"\ make make test make altinstall and the compilation stop with the following pb : ld: 0711-317 ERROR: Undefined symbol: _unctrl ld: 0711-317 ERROR: Undefined symbol: .__fixsfsi ld: 0711-317 ERROR: Undefined symbol: .setsyx ld: 0711-317 ERROR: Undefined symbol: ._setqiflush ld: 0711-317 ERROR: Undefined symbol: .initscr32 ld: 0711-317 ERROR: Undefined symbol: wacs_map ld: 0711-317 ERROR: Undefined symbol: ._getsyx ld: 0711-317 ERROR: Undefined symbol: .getattrs ld: 0711-317 ERROR: Undefined symbol: .w32attrset ld: 0711-317 ERROR: Undefined symbol: .w32insch ld: 0711-317 ERROR: Undefined symbol: .p32echochar ld: 0711-317 ERROR: Undefined symbol: .w32echochar ld: 0711-317 ERROR: Undefined symbol: .box32 ld: 0711-317 ERROR: Undefined symbol: .w32addch ld: 0711-317 ERROR: Undefined symbol: .w32attroff ld: 0711-317 ERROR: Undefined symbol: .w32attron ld: 0711-345 Use the -bloadmap or -bnoquiet option to obtain more information. *** WARNING: renaming "_curses" since importing it failed: No such file or directory error: No such file or directory make: 1254-004 The error code from the last command is 1. Stop. I've compiled ncurses-5.6 in ${BASE}/lib but this haven't solved the pb. Any clue ? Best regards -- BL From duncan.booth at invalid.invalid Tue Jul 17 03:38:05 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jul 2007 07:38:05 GMT Subject: In a dynamic language, why % operator asks user for type info? References: <1184631007.920803.147790@j4g2000prf.googlegroups.com> <1184631512.329438.90050@i13g2000prf.googlegroups.com> <1184632433.980754.189240@d30g2000prg.googlegroups.com> <1184634387.15828.47.camel@blackwidow.nbk> Message-ID: marduk wrote: > By design, %s "converts any python object using str()". OTOH it does > not specify that %d, for example, calls int(). No, but it does say that the 'd' is a conversion type meaning 'signed integer decimal', and indeed anything which has an __int__ method may be passed to the %d formatter: >>> class C: def __int__(self): return 42 >>> "%d" % C() '42' >>> "%d" % 3.5 '3' From erik at myemma.com Mon Jul 16 10:50:32 2007 From: erik at myemma.com (Erik Jones) Date: Mon, 16 Jul 2007 09:50:32 -0500 Subject: How to determine which method was used in an inheritance heirarchy? In-Reply-To: References: <1184559788.712146.238190@q75g2000hsh.googlegroups.com> <1184565220.674041.270790@o61g2000hsh.googlegroups.com> <4BC3DC93-5F57-4B24-BE82-EB2D5FD679AF@myemma.com> Message-ID: <865D7C6C-F76B-46F0-9E4C-848E896A1627@myemma.com> On Jul 16, 2007, at 3:37 AM, Gabriel Genellina wrote: > En Mon, 16 Jul 2007 03:56:18 -0300, Erik Jones > escribi?: > >> Perhaps an even better example of what I'm trying to do would be in >> order (this is minus any exception handling): >> >> import sys >> >> def mytrace(frame, event, arg): >> if event == 'call': >> func_name = frame.f_code.co_name >> >> if func_name in frame.f_locals['self'].__class__.__dict__: >> print frame.f_locals['self'].__class__.__name__ >> else: >> for base in frame.f_locals['self'].__class__.__bases__: >> if func_name in base.__dict__: >> print base.__name__ >> break >> >> >> class A(object): >> def __init__(self): >> pass >> >> class B(A): >> def __init__(self): >> A.__init__(self) >> >> sys.settrace(mytrace) >> B() >> >> This will output: >> >> B >> B > > If you don't mind post-processing the results, you can log the > function > name and source module (from frame.f_code.co_name and co_filename) and > current line number (frame.f_lineno). Later, obtaining the class > name from > those is a bit tricky (and not even the inspect module does it > right), but > perhaps using the tokenizer module, watching for lines that contain > "class" is enough. I was afraid of that. I used pretty much that tokenizer trick for a unit test generator I wrote in php a while back and felt like that was pretty clunky then. 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 erik at myemma.com Sat Jul 21 17:43:08 2007 From: erik at myemma.com (Erik Jones) Date: Sat, 21 Jul 2007 16:43:08 -0500 Subject: Python in Nashville In-Reply-To: <1184988127.644107.64420@22g2000hsm.googlegroups.com> References: <1184988127.644107.64420@22g2000hsm.googlegroups.com> Message-ID: <6602B8A5-B19E-4CB5-9BD7-6340B8CD2ABF@myemma.com> Me! Did you just move here? On Jul 20, 2007, at 10:22 PM, Patrick Altman wrote: > Anyone on this group writing Python code in Nashville, TN? > > -- > http://mail.python.org/mailman/listinfo/python-list 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 carl.dhalluin at gmail.com Wed Jul 11 18:21:50 2007 From: carl.dhalluin at gmail.com (carl.dhalluin at gmail.com) Date: Wed, 11 Jul 2007 15:21:50 -0700 Subject: atexit, sys.exit, sys.exitfunc, reaching end of source code Message-ID: <1184192510.343401.13860@57g2000hsv.googlegroups.com> Hi, I am playing with the atexit module but I don't find a way to see the difference between a script calling sys.exit() and the interpreting arriving at the end of the source code file. This has a semantic difference for my applications. Is there a way to determine in an exithandler (that is registered using atexit.register) how I exited? Second question: is there a way to determine in my exithandler what the return code was. atexit doesn't seem to support that Third question: I can solve part of my problem by reassigning sys.exit = myfunction Is that a wise idea? It seems that an interpreter (python 2.4) reaching end of source code, calls sys.exitfunc instead of sys.exit ? Thanks Carl D'Halluin www.qlayer.com From claird at lairds.us Mon Jul 2 13:05:57 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 2 Jul 2007 17:05:57 +0000 Subject: Probably simple syntax error References: <1183351228.878746.233430@o61g2000hsh.googlegroups.com> <1183352843.803263.82140@57g2000hsv.googlegroups.com> Message-ID: In article <1183352843.803263.82140 at 57g2000hsv.googlegroups.com>, Mark Peters wrote: . . . >Square brackets indicate the index into a sequence (like a list) > I'm wary of this line, especially in isolation. I hope it reduces, rather than exacerbates, the original questioner's confusion, for me to observe that [] *also* mark dereferencing into a dictionary (hash, associative array, ...), which is distinct from list indexing. From KREUZRSK at DFW.WA.GOV Mon Jul 23 19:55:39 2007 From: KREUZRSK at DFW.WA.GOV (Randy Kreuziger) Date: Mon, 23 Jul 2007 16:55:39 -0700 Subject: Maintaining leading zeros with the lstrip string function? Message-ID: Thanks for the basename suggestion. That almost works. I'm running into a problem with some of the directory names when they include \800x\ see below. ?----------------------------------------------------------------------------- import sys, os, string teststring = 'C:\shoreline\dvd\prep area\800x\060623_00001.jpg' print os.path.basename(teststring) ?----------------------------------------------------------------------------- Results in 800x0623_00001.jpg But it needs to be 060623_00001.jpg -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at mac.com Thu Jul 5 23:19:24 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 5 Jul 2007 20:19:24 -0700 Subject: The best platform and editor for Python References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183646799.400176.144570@k79g2000hse.googlegroups.com> <1183655933.475488.157270@m36g2000hse.googlegroups.com> <1183670009.035673.256680@w5g2000hsg.googlegroups.com> Message-ID: <1i0so61.10qnto712c7dhpN%aleax@mac.com> Kay Schluehr wrote: ... > half of the community is happy with Emacs and the other half wants to > program in a VS-like environment, neither consensus nor progress has Calling all vi/vim users (and we'll heartily appreciate the support of TextMate fans, BBEdit ones, etc, etc) -- we're at risk being defined out of existence, since we're neither happy with Emacs nor wanting anything like Visual Studio, and yet Kay claims that people in either category make up the whole (one half plus the other half) and so that WE DON'T EXIST!!! A ridiculous claim to be sure, but we'd better let Herr Schluehr know that in no uncertain terms... Alex From bj_666 at gmx.net Fri Jul 27 08:33:17 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jul 2007 12:33:17 GMT Subject: Filtering content of a text file References: <1185528507.750436.91140@j4g2000prf.googlegroups.com> <46a9c5a5$0$9208$426a34cc@news.free.fr> Message-ID: <5gu70dF3i0lfsU3@mid.uni-berlin.de> On Fri, 27 Jul 2007 12:15:25 +0200, Bruno Desthuilliers wrote: > 4/ print "//-+alibaba sinage"[4:].startswith('a') print "//-+alibaba sinage".startswith('a', 4) This does not create an extra string from the slicing. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Mon Jul 9 04:27:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Jul 2007 05:27:03 -0300 Subject: Htmllib help References: <070620070644.2754.468DE4C400077E4F00000AC222007348300D010C0E06A10407020E@comcast.net> Message-ID: En Fri, 06 Jul 2007 03:44:20 -0300, escribi?: > Thats right I don't need the output any where so I don't need to use the > writer. I can remove it wowever will the formater work since it needs > writer? Maybe I can use the Null writer? Exactly. Look at the HTMLParser module too; depending on your needs, it may be easier to use. > -------------- Original message ---------------------- > From: "Gabriel Genellina" >> En Thu, 05 Jul 2007 20:23:08 -0300, escribi?: >> > >> > Even though I don't use any print statements, the htmllib seems to be >> > throwing parts of the html page on to the standard out(my screen in >> this >> > case). Is there a way to disable the output? >> > >> > import htmllib >> > w = formatter.DumbWriter() >> >> Change the above line. From >> http://docs.python.org/lib/writer-impls.html: >> "class DumbWriter([file[, maxcol = 72]]) >> Simple writer class which writes output on the file object passed in as >> file or, if file is omitted, on standard output." -- Gabriel Genellina From mark.dufour at gmail.com Tue Jul 10 10:58:10 2007 From: mark.dufour at gmail.com (mark.dufour at gmail.com) Date: Tue, 10 Jul 2007 07:58:10 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <1183662184.771664.242970@g37g2000prf.googlegroups.com> References: <8180ef690703310255q55572efaqc512b968504e2c1b@mail.gmail.com> <1183662184.771664.242970@g37g2000prf.googlegroups.com> Message-ID: <1184079490.536241.125630@22g2000hsm.googlegroups.com> hi mike, > Great work. You might want to advertise this on the main site > (currently it states that this is impossible). yes, thank you for reminding me. > You've said somewhere that you didn't/don't plan on working on this > aspect, but it is surely the "killer feature" of shed skin needed to > for it to be able to be used as pyrex is currently (optimizing bits of > larger projects). no I agree it is a very useful feature :-) I was just waiting for someone to step in and help out. when that happened I was motivated enough to fill in the details. > I wish I had time to help, I know it's a bit boring, but I'm always glad to receive bug reports :) A few hours of help looking into adding custom classes to the extension module support, or implementing some library functions, can be very useful too.. (I'm currently getting practically no help at all). >But there is such a large gap betwixt the >twain that such dreaming is but an excercise in fantasy (there's >always pypy). yes, pypy will solve all problems, including world hunger ^^ thanks, mark dufour - shed skin author From leszek.mis at gmail.com Wed Jul 25 18:36:54 2007 From: leszek.mis at gmail.com (crony) Date: Thu, 26 Jul 2007 00:36:54 +0200 Subject: curses/urwid simple menu Message-ID: Hello. Could you help me...I need to create application with urwid or curses support. Have you got a pretty simple example with it? -- Pozdrawiam Leszek Mi? Nothing is secure, paranoia is your friend. -------------- next part -------------- An HTML attachment was scrubbed... URL: From irnyad at gmail.com Tue Jul 31 08:30:55 2007 From: irnyad at gmail.com (Jason Ward) Date: Tue, 31 Jul 2007 14:30:55 +0200 Subject: Nasm_with_C++_with_Python Message-ID: <1ea031080707310530j42eaf925w38909bf7580caf15@mail.gmail.com> I am wanting to write a library in nasm and call it from python. Because python can call c++ libraries. And nasm can be used in c++. So I was wondering how I would go about using nasm in python? -------------- next part -------------- An HTML attachment was scrubbed... URL: From stargaming at gmail.com Fri Jul 13 00:37:19 2007 From: stargaming at gmail.com (Stargaming) Date: Fri, 13 Jul 2007 06:37:19 +0200 Subject: Most efficient way to evaluate the contents of a variable. In-Reply-To: <1184300936.115235.121980@g12g2000prg.googlegroups.com> References: <1184300936.115235.121980@g12g2000prg.googlegroups.com> Message-ID: <46970180$0$13186$9b622d9e@news.freenet.de> bdude schrieb: > Hey, I'm new to python and am looking for the most efficient way to > see if the contents of a variable is equal to one of many options. > > Cheers, > Bryce R > if var in ('-h', '--hello', '-w', '--world'): pass Most maintenance-efficient, that is. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 24 11:44:30 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 24 Jul 2007 17:44:30 +0200 Subject: Closures / Blocks in Python In-Reply-To: <1185289112.771239.200260@n60g2000hse.googlegroups.com> References: <1185289112.771239.200260@n60g2000hse.googlegroups.com> Message-ID: <46a61e56$0$25349$426a74cc@news.free.fr> treble54 a ?crit : > Does anyone know a way to use closures or blocks in python like those > used in Ruby? Particularly those used in the { } braces. > Instead of looking for what you think is the solution, you'd be better explaining your concrete problem. From samper.d at gmail.com Sat Jul 21 12:53:59 2007 From: samper.d at gmail.com (Dave Sampson) Date: Sat, 21 Jul 2007 09:53:59 -0700 Subject: Python Subprocess module In-Reply-To: References: Message-ID: <1185036839.344637.289600@w3g2000hsg.googlegroups.com> > You probably mean:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 > > Why is that not sufficient? It will allow interaction with a called > subprocess, in a cross-platform manner, etc. > > - Josiah Sorry maybe 'not sufficient' was the wrong excuse. Maybe the right thing to say is that when I look at it I don't know if I'm supposed to copy paste in my own module, or paste into a seprate module, or use it in a pre-existing module. Does the liscence for the content through ASPN even allow reuse of code. or Am I supposed to modify it? If I use, how is it to be used?. Wher eare the exmpales and documentation. By sufficient I mean I don't have sufficient info from the site to implement it. And I don't have sufficient know how to implement it base don the comments in the source code. IN SHORT... IT'S SCARY.... So if you can answer any of those questions I am open. From raims at dot.com Wed Jul 18 09:48:02 2007 From: raims at dot.com (Lawrence Oluyede) Date: Wed, 18 Jul 2007 15:48:02 +0200 Subject: best SOAP module References: Message-ID: <1i1gehv.vouems1z8emeN%raims@dot.com> Sells, Fred wrote: > I need to talk to a vendor side via SOAP, Googling is overwhelming and many > hits seem to point to older attempts. > > Can someone tell me which SOAP module is recommended. I'm using Python 2.4. Try soaplib: -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From steve at holdenweb.com Mon Jul 30 06:38:23 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Jul 2007 06:38:23 -0400 Subject: wxGlade: Who knows how to drive this application? In-Reply-To: <200707300646.l6U6k03P029079@dit.unitn.it> References: <200707300646.l6U6k03P029079@dit.unitn.it> Message-ID: <46ADBF9F.3040404@holdenweb.com> Alberto Griggio wrote: >> Here are some things I can think of, in no particular order: > > Thanks! I can't promise I'll take care of all of them (some are nontrivial > to implement, and would probably take a lot of time), but this list is > definitely valuable (e.g. I can circulate it through the other developers > to see if there's any volunteer...) > Roel's list is clearly based on much more experience than I have with wxGlade, and is pretty much a superset of mine. You are right, that is valuable feedback for a developer. Sorry ny own comments were less directed. 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 miridian at nerdshack.com Mon Jul 30 06:11:11 2007 From: miridian at nerdshack.com (miridian) Date: Mon, 30 Jul 2007 12:11:11 +0200 Subject: import struct in Python z/OS Message-ID: <46ADB93F.4020109@nerdshack.com> Hi, I'm porting a Python program from Linux to z/OS using this Python port http://www.teaser.fr/~jymengant/mvspython/mvsPythonPort.html I get the following Python 2.4.1 (#43, Apr 23 2005, 23:35:50) [C] on mvs Type "help", "copyright", "credits" or "license" for more information. >>> import struct Traceback (most recent call last): File "", line 1, in ? ImportError: No module named struct as far as I can see the module struct (and a lot of other, like time, math etc.) is compiled as dll ./build/lib.os390-10.00-7060-2.4/struct.dll but not configured correctly. :-( Any hint ? Thank you in advance. From shafik23 at gmail.com Wed Jul 11 14:06:35 2007 From: shafik23 at gmail.com (Shafik) Date: Wed, 11 Jul 2007 18:06:35 -0000 Subject: Tuple vs List: Whats the difference? Message-ID: <1184177195.569916.184770@22g2000hsm.googlegroups.com> Hello folks, I am an experienced programmer, but very new to python (2 days). I wanted to ask: what exactly is the difference between a tuple and a list? I'm sure there are some, but I can't seem to find a situation where I can use one but not the other. Thanks in advance, --Shafik From jefishman at gmail.com Fri Jul 27 23:25:35 2007 From: jefishman at gmail.com (anethema) Date: Fri, 27 Jul 2007 20:25:35 -0700 Subject: Imported globals? In-Reply-To: <1185562865.896992.112860@w3g2000hsg.googlegroups.com> References: <1185562865.896992.112860@w3g2000hsg.googlegroups.com> Message-ID: <1185593135.322082.215150@m37g2000prh.googlegroups.com> > It seems that in the first case change_value() called in module_b.py > ignores the global statement. Is it so? Why? What happens in the second > case? I really don't get it. The key is that it doesn't ignore the global statement, but that global specifically points to the variable 'value' in module A's namespace. That is, even though you call change_it() from module B, it acts on the variable in module A, not B, even though 'value' exists in B. consider the following modules: module_a.py value = 'initial' def change_it(): global value value = 'changed' def print_it(): print "In module A:", value print_it() module_b.py from module_a import value, change_it, print_it as a_print_it() def print_it(): print "In module B:", value print_it() change_it() a_print_it() print_it() $> python module_b.py In module A: initial In module B: initial In module A: changed In module B: initial Here we see that a) print_it() was executed in module A before the code in module B ran; This happens at import. b) after change_it() was executed, 'value' in module A was changed, while 'value' in module B was left alone. This demonstrates how the modules have separate namespaces, but also hinges on the fact that strings are immutable, as star.public mentions. 'value' in both namespaces do refer to the same object. What's significant is the action on the method change_it(). For example, def change_it(): value = 'changed' this would do no good at all, as you may have realized, as it merely assigns the string 'changed' to the name/variable 'value' in the function namespace. If there is an assignment to a variable in a function (not an attribute of some other variable), such as 'a = 2', the interpreter assumes that the function is declaring a new variable. We need to explicitly declare the variable global first. If we don't, and try to treat it global, the above useless function can result, or the following def change_it(): if value == 'initial': value = 'changed' which results in a UnboundLocalError, since, defaulting to using 'value' as a local variable (since we have the assign statement `value = 'changed'`), and we attempt to use the local var before assigning it a value. For mutable objects, such as a list, or classes (and their attributes), the result would be different. module_a.py value = ['initial'] def change_it(): value[0] = 'initial' # don't need the 'global value', since we're accessing attributes # of 'value', not directly accessing value def print_it(): print "In module A:", value[0] print_it() module_b.py from module_a import value, change_it, print_it as a_print_it def print_it(): print "In module B:", value[0] print_it() change_it() a_print_it() print_it() $> python module_b.py In module A: initial In module B: initial In module A: changed In module B: changed In this case, the two module namespaces still each contain a reference to the same object. What we did differently is change the object itself, instead of the reference. If change_it() assigned to value, `value = ['changed']`, we would see no different behavior than in the first case. Sorry if that was overly winded. scope and namespaces are tricky (at least for me) to explain. - Jeremy From jeff at jmcneil.net Wed Jul 25 16:13:49 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 25 Jul 2007 16:13:49 -0400 Subject: first, second, etc line of text file In-Reply-To: <5f56302b0707251244p24080f1ct87a5f459cb175dae@mail.gmail.com> References: <5f56302b0707251244p24080f1ct87a5f459cb175dae@mail.gmail.com> Message-ID: <82d28c40707251313i6bdce5bfj5a7f01b374d96b71@mail.gmail.com> Depending on the size of your file, you can just use file.readlines. Note that file.readlines is going to read the entire file into memory, so don't use it on your plain-text version of War and Peace. >>> f = open("/etc/passwd") >>> lines = f.readlines() >>> lines[5] '# lookupd DirectoryServices \n' >>> You can also check out the fileinput module. That ought to be sightly more efficient and provides some additional functionality. I think there are some restrictions on accessing lines out of order, though. -Jeff On 7/25/07, Daniel Nogradi wrote: > A very simple question: I currently use a cumbersome-looking way of > getting the first, second, etc. line of a text file: > > for i, line in enumerate( open( textfile ) ): > if i == 0: > print 'First line is: ' + line > elif i == 1: > print 'Second line is: ' + line > ....... > ....... > > I thought about f = open( textfile ) and then f[0], f[1], etc but that > throws a TypeError: 'file' object is unsubscriptable. > > Is there a simpler way? > -- > http://mail.python.org/mailman/listinfo/python-list > From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jul 12 16:31:47 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 12 Jul 2007 22:31:47 +0200 Subject: bool behavior in Python 3000? References: <5ficedF3cram2U1@mid.individual.net> Message-ID: <5fnhdjF3dkobnU1@mid.individual.net> Alan Isaac wrote: > Bjoern Schliessmann wrote: >> Is there any type named "bool" in standard Python? >>>> type(True) > Thanks anyway, but I remembered it shortly after sending. Thus the cancel (seems to have failed a bit). Regards, Bj?rn -- BOFH excuse #384: it's an ID-10-T error From hey at mikehowarth.co.uk Mon Jul 30 12:49:55 2007 From: hey at mikehowarth.co.uk (Mike Howarth) Date: Mon, 30 Jul 2007 09:49:55 -0700 (PDT) Subject: Database objects? Persistence? Sql Server woes Message-ID: <11866779.post@talk.nabble.com> I've been having a few problems with connecting to SQL Server, initially I was using dblib however found some problems with returning text fields whereby all text fields were ignored and it bawked at multiline sql statements. Having found these major stumbling blocks I've started using pymssql which seems less flaky. One problem I've stumbled across is that I seem to reach my max connections on the database fairly easily (given how my script was written) and therefore have used the singleton pattern on my database object. Great problem solved, or so I thought. Using the following code I'm finding that the Set is now also being enforced as a singleton as well. class Set(Database,Product): def __init__(self, *args, **kw): Database.__init__(self) Product.__init__(self) def dosomething(self): cu = self.c.cursor() Having sat back and thought about it, its easy to understand why this is occurring given I'm indicating that Set belongs to Database and therefore this is a singleton as well. Being relatively new to Python I'm unsure on how to then go about using a database object between each class. Can anyone advise me on how they approach this, and whether there is a common approach to this? -- View this message in context: http://www.nabble.com/Database-objects--Persistence--Sql-Server-woes-tf4171199.html#a11866779 Sent from the Python - python-list mailing list archive at Nabble.com. From python at jayloden.com Tue Jul 31 01:10:55 2007 From: python at jayloden.com (Jay Loden) Date: Tue, 31 Jul 2007 01:10:55 -0400 Subject: Reading a two-column file into an array? In-Reply-To: <1185857837.610635.206270@e9g2000prf.googlegroups.com> References: <1185857837.610635.206270@e9g2000prf.googlegroups.com> Message-ID: <46AEC45F.6080705@jayloden.com> Nagarajan wrote: > On Jul 31, 9:03 am, Gilles Ganault wrote: >> Hello >> >> I'm sure there's a much easier way to read a two-column, CSV file into >> an array, but I haven't found it in Google. >> >> Should I use the Array module instead? [...snip] > a = [] > import csv > reader = csv.reader(open("filename", "r"), delimiter='\t' ) > for row in reader: > a.append( row ) > > ---------------------------- > I don't think you can have multidimensional arrays. > Did you test you program? It did not work for me. > I think mine would suit your requirements as the output is a list of > lists. I am similarly confused as to the nature of the original request, but for completeness' sake, I went by the same assumption of building a list of lists, and came up with this (which does not use the csv module). Nagarajan's code is more concise and just as readable IMO, but here's my take anyway: a = [] b = [] handle = open(filename, 'r') for line in handle.xreadlines(): col1,col2 = line.split('\t') a.append(col1) b.append(col2) columns = [a, b] -Jay From joshua at eeinternet.com Tue Jul 24 18:28:11 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Tue, 24 Jul 2007 14:28:11 -0800 Subject: Reading a Directory of Emails - Problems References: <72fc09510707241038s367aaa3bqd6a221074291d3d@mail.gmail.com> Message-ID: On Tuesday 24 July 2007 09:38, Ryan Rosario wrote: > Hi, > > I have a directory that contains a bunch of email messages and I would > like to parse them using the email and mailbox packages. The emails were > exported from Apple Mail. From what I gather, I need to use MHMailbox, but > I can't get it to do anything useful and I cannot find any examples of how > to use this particular mailbox type. > > mbox = > mailbox.MHMailbox('stat_inbox.mbox/Messages',email.message_from_file) for > msg in mbox: > print msg.keys() #just to see if anything is happening > > I get an error. AttributeError: MHMailbox instance has no attribute > 'keys'. Yet this works when using PortableUnixMailbox (on an mbox file, > not a directory of emails). I fought with this a while back. It seems it is nested one level lower. You might have to get at the message by doing something like real_message = msg[0] Instead of print msg.keys(), just do a 'print msg' and see what data structure is returned. That will tell you a lot. j -- Joshua Kugler Lead System Admin -- Senior Programmer http://www.eeinternet.com PGP Key: http://pgp.mit.edu/ ?ID 0xDB26D7CE From steve at holdenweb.com Thu Jul 5 08:36:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Jul 2007 08:36:52 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xzm2budfv.fsf@ruckus.brouhaha.com> References: <5dveb4F360un0U1@mid.individual.net> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > John Nagle writes: >> This has been tried. Original K&R C had non-enforced static typing. >> All "struct" pointers were equivalent. It wasn't pretty. >> >> It takes strict programmer discipline to make non-enforced static >> typing work. I've seen it work in an aerospace company, but the Python >> crowd probably doesn't want that level of engineering discipline. > > I think even enforced static types wouldn't cure what I see as the > looseness in Python. There is not enough composability of small > snippets of code. For example, the "for" statement clobbers its index > variable and then leaks it to the outside of the loop. That may be > more of a culprit than dynamic types. Perl and C++ both fix this with > syntax like > > for (my $i in ...) ... (perl) or > for (int i = 0; i < n; i++) ... (C++, Java) > > making a temporary scope for the index variable. Python even leaks > the index variable of list comprehensions (I've mostly stopped using > them because of this), though that's a recognized wart and is due to > be fixed. > Wow, you really take non-pollution of the namespace seriously. I agree it's a wart, but it's one I have happily worked around since day one. > Python would be helped a lot by some way to introduce temporary > scopes. We had some discussion of this recently, concluding that > there should be a compiler warning message if a variable in a > temporary scope shadows one from a surrounding scope. Yeah, well the approach to scoping could really be improved, but if you keep your namespaces small it's not difficult to keep things straight. I have always been rather guarded in my approach to accessing non-local scopes because the coupling is rather less than obvious, and is subject to variation due to non-local changes. 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 justin.mailinglists at gmail.com Mon Jul 2 22:47:08 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: Tue, 03 Jul 2007 02:47:08 -0000 Subject: The file executing In-Reply-To: <1183426846.550981.11910@m36g2000hse.googlegroups.com> References: <1183426846.550981.11910@m36g2000hse.googlegroups.com> Message-ID: <1183430828.997331.84340@e9g2000prf.googlegroups.com> On Jul 3, 9:40 am, Benjamin wrote: > How does one get the path to the file currently executing (not the > cwd). Thank you os.path.dirname(sys.argv[0]) From fabiofz at gmail.com Wed Jul 18 11:38:27 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 18 Jul 2007 12:38:27 -0300 Subject: Pydev 1.3.8 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.8 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights in Pydev Extensions: ----------------------------------------------------------------- * Code-analysis: Detects mixing of spaces and tabs. * Code-analysis: Reimport not flagged when inside of try..except ImportError. Release Highlights in Pydev: ---------------------------------------------- * Fixed problems related to the pydev package explorer that appeared when using java 1.6 (ConcurrentModificationException) * Other minor bug-fixes What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From nogradi at gmail.com Fri Jul 13 04:58:37 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 13 Jul 2007 10:58:37 +0200 Subject: how to install pygame package? In-Reply-To: <1184303076.915138.43310@o11g2000prd.googlegroups.com> References: <1184303076.915138.43310@o11g2000prd.googlegroups.com> Message-ID: <5f56302b0707130158l6b9a067co9cbf1796d2c76c2@mail.gmail.com> > Im working in red hat linux 9.0. I've downloaded the pygame package > but i dont know how to install it. If anybody has the time to detail > the steps sequentially... thanx! > > P.S. I've downloaded both the tar and the rpm packages... First you can try the rpm package: su (give the root password) rpm -i Or with the tar package: tar xzvf cd (the name of the created directory) ./configure make su (give the root password) make install HTH. From jimxu at google.com Sun Jul 8 04:55:09 2007 From: jimxu at google.com (jimxu) Date: Sun, 8 Jul 2007 01:55:09 -0700 Subject: what is wrong with that r"\" In-Reply-To: References: <27kr83lv67n38fmirvs5vvh5f80cr27joi@4ax.com> Message-ID: Yeah, that's a good point... On Jul 8, 2007, at 1:48 AM, Tim Roberts wrote: > i3dmaster wrote: >> >> Then you can use other chars as the delimiter, r at a@b@ or r!a!b!, >> etc... The import thing is so long as the interpreter doesn't get >> confused on the data and the delimiter. > > That limits the number of valid delimiters to a relatively small > set. You > couldn't use any valid operator: > > x = r*a*b > > Is that a one character raw string appended to a string called "b", > or is > that to multiplications? > >> sed also allows for >> arbitrary delimiters too as long as you maintain the integrity of the >> original meaning... > > sed can do that because its commands are one character long. Whatever > follows an "s" must a delimiter because it can't be anything else. > -- > Tim Roberts, timr at probo.com > Providenza & Boekelheide, Inc. > -- > http://mail.python.org/mailman/listinfo/python-list From rustyhowell at gmail.com Mon Jul 30 20:25:40 2007 From: rustyhowell at gmail.com (rustyhowell at gmail.com) Date: Tue, 31 Jul 2007 00:25:40 -0000 Subject: Pysqlite storing file as blob example Message-ID: <1185841540.275571.161640@g4g2000hsf.googlegroups.com> I'm trying to store binary data in a sqlite database and call into the db using pysqlite 3. What I've got so far is this: import sqlite con = sqlite.connect(DB_PATH) cur = con.cursor() query = """create table t1( ID INTEGER PRIMARY KEY, data BLOB );""" cur.execute(query) con.commit() b = buffer('/path/to/binary/file') query = 'insert into table (ID,data) values (1,?);' result = cur.execute(query,(b)) con.commit() The error message I get is : Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.5/site-packages/sqlite/main.py", line 255, in execute self.rs = self.con.db.execute(SQL % parms) TypeError: not all arguments converted during string formatting I also read about using adapters, but I haven't found any clear info on how to use them. Does anyone have an example of storing binary data (image) in sqlite using pysqlite? From gagsl-py2 at yahoo.com.ar Tue Jul 24 21:58:17 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Jul 2007 22:58:17 -0300 Subject: Base class for file-like objects? (a.k.a "Stream" in Java) References: <1185317490.607920.100200@z24g2000prh.googlegroups.com> Message-ID: En Tue, 24 Jul 2007 19:51:30 -0300, Boris Du?ek escribi?: > in Java, when I want to pass input to a function, I pass > "InputStream", which is a base class of any input stream. > > In Python, I found that "file" objects exist. While specifying > argument types in Python is not possible as in Java, it is possible to > check whether an object is an instance of some class and that's what I > need - I need to check if an argument is a "file"-like object, and if > yes, behave accordingly, if not, treat the argument as string with > URL. No, it's not what you need, it's what you *think* you need :) > P.S.: The code should finally look in esence something like this: Posting this is much better that saying what you think you need. > if isinstance(f, file): > pass > elif isinstance(f, string): > f = urllib.urlopen(f) > else: > raise "..." > process_stream(f) I can imagine that process_stream is something like this: def process_stream(f): ... data = f.read() ... or similar. Then, you dont need a file object: you need something with a read() method. So, this is what you should check in your code above. if hasattr(f, "read"): pass elif isinstance(f, basestring): f = urllib.urlopen(f) else: raise TypeError, "Expecting either a readable file-like object or an URL" process_stream(f) Or perhaps: if isinstance(f, basestring): f = urllib.urlopen(f) process_stream(f) and just let the exception happen below at f.read - which explains itself rather well. -- Gabriel Genellina From exarkun at divmod.com Mon Jul 2 16:24:48 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 2 Jul 2007 16:24:48 -0400 Subject: Python compilation ?? In-Reply-To: Message-ID: <20070702202448.4947.2088004513.divmod.quotient.6059@ohm> On Mon, 02 Jul 2007 16:14:41 -0400, Steve Holden wrote: >Evan Klitzke wrote: >> On 7/2/07, Cathy Murphy wrote: >>> Is python a compiler language or interpreted language. If it is interpreter >>> , then why do we have to compile it? >> >> It's an interpreted language. It is compiled into bytecode (not >> machine code) the first time a script is run to speed up subsequent >> executions of a script. >> >While the flavor of this answer is correct, in strict point of fact >Python *doesn't* compile the scripts it executes, only the modules that >are imported. > >That's why you will occasionally see a very small Python program that >just calls functions imported from much larger modules. This avoids >spending the time that would otherwise have to be spent recompiling a >large script at each execution. Hey Steve, To nit pick :) Wouldn't you say it is more accurate to say that it does compile the scripts (by which we mean the "main" file - either the one passed as an argument to the interpreter on the command line, or the one with a #! at the top which gets respected, or the .py file on Windows which is associated with python.exe as its interpreter), but that it doesn't save the results of this compilation to a file to be used next time? Jean-Paul From marduk at nbk.hopto.org Mon Jul 16 21:06:27 2007 From: marduk at nbk.hopto.org (marduk) Date: Mon, 16 Jul 2007 20:06:27 -0500 Subject: In a dynamic language, why % operator asks user for type info? In-Reply-To: <1184632433.980754.189240@d30g2000prg.googlegroups.com> References: <1184631007.920803.147790@j4g2000prf.googlegroups.com> <1184631512.329438.90050@i13g2000prf.googlegroups.com> <1184632433.980754.189240@d30g2000prg.googlegroups.com> Message-ID: <1184634387.15828.47.camel@blackwidow.nbk> On Mon, 2007-07-16 at 17:33 -0700, Karthik Gurusamy wrote: > Thanks. The above surprised me as I didn't expect that %s will accept > 42. > > Looks like the implicit conversion doesn't work the other way. > > >>> '%s' % 42 > '42' > >>> '%d' % '42' > Traceback (most recent call last): > File "", line 1, in > TypeError: int argument required > >>> > > Looks like %s can be used even when I'm sending non-strings. > >>> '%s foo %s bar' % (25, 25.34) > '25 foo 25.34 bar' > >>> > > So %s seems to serve the multi-type placeholder. According to the docs: http://docs.python.org/lib/typesseq-strings.html By design, %s "converts any python object using str()". OTOH it does not specify that %d, for example, calls int(). From horpner at yahoo.com Sat Jul 28 08:45:07 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 28 Jul 2007 12:45:07 GMT Subject: Where do they tech Python officialy ? References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> Message-ID: On 2007-07-28, Omari Norman wrote: > On Mon, Jul 23, 2007 at 10:48:10PM -0700, Paul Rubin wrote: > >> If you're having trouble with Python because you're new at >> programming, I can sympathize--I don't think it's the most >> beginner-friendly of languages despite the efforts in that direction >> by the designers. > > Just curious--what language would you recommend as most > beginner-friendly? I recommend the symbolic logo-like Scheme used in _Simply Scheme_. It works with sentences and words polymorphically. (first smith) s (first '(smith jones cooper)) smith The books exercises revolve around writing functions like pig-latin, reverse, palindrom?, and other word and sentence manipulations. Real Scheme primitives are not introduced until lots of programming ideas have been conveyed. http://www.amazon.com/Simply-Scheme-Introducing-Computer-Science/dp/0262082810 > In college I had a programming course that used C++. Big > mistake in my view, and we didn't learn much in the way of true > principles (in retrospect it would have been nice if they had > us use GCC rather than Borland on Windows.) I can imagine a course using C++ that taught basic programming concepts; it would teach the rudiments of using the STL to start, and work with vectors, lists and maps. See _Accelerated C++_ for a great example. But most C++ courses start with the lowest level functionality of C++, soon embroiling inexperienced programmers with the difficulties of manual dynamic memory management. That's a big side-show. -- Neil Cerutti From moranar at gmail.com Sat Jul 7 18:21:40 2007 From: moranar at gmail.com (Adriano Varoli Piazza) Date: Sat, 07 Jul 2007 15:21:40 -0700 Subject: FreeBSD/Linux X11 determine which window manager is active In-Reply-To: References: Message-ID: <1183846900.210759.270720@22g2000hsm.googlegroups.com> Rod Person ha escrito: > I'm looking for a way to determine which window manager is running using > python. I can't seem to find a system variable that hold this info. I don't think one exists. You could check which process is running, but that would be so web 1.0 (think javascript) it makes me sick just to think about it. A better alternative could be to code with the extended WM hints (see http://standards.freedesktop.org/wm-spec/wm-spec-latest.html ), that should cover many needs. As with the web, (this might be something you already know, I apologise in that case), try to code to functionality, not names. Check if the WM can do what you want, not its name or version HTH -- Saludos Adriano From shabda.raaj at gmail.com Tue Jul 17 04:35:15 2007 From: shabda.raaj at gmail.com (shabda raaj) Date: Tue, 17 Jul 2007 08:35:15 -0000 Subject: Implementaion of random.shuffle In-Reply-To: References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> <1184597148.692325.36590@x35g2000prf.googlegroups.com> Message-ID: <1184661315.551490.227570@j4g2000prf.googlegroups.com> Ah, thanks I get it now! --Shabda On Jul 17, 7:52 am, Steven D'Aprano wrote: > On Mon, 16 Jul 2007 14:45:48 +0000,shabdaraaj wrote: > > On Jul 16, 5:53 pm, Steve Holden wrote: > >>shabdaraaj wrote: > >> > I was going through the docs for module-random > >> > And I came through > >> > this, > > >> > * shuffle*( x[, random]) > > >> > Shuffle the sequence x in place. The optional argument random is > >> > a 0-argument function returning a random float in [0.0, 1.0); by > >> > default, this is the function random(). > > >> > Note that for even rather small |len(x)|, the total number of > >> > permutations of x is larger than the period of most random number > >> > generators; this implies that most permutations of a long > >> > sequence can never be generated. > > [snip] > > > Oh, I wasn't aware that I could see the source of all python modules. I > > guess, then the implementation is correct(its just the knuth shuffle, > > moving downward), its just the doc which is in error. Might be we should > > log a doc bug for this? > > No, it is not a doc error, you are confused. > > Suppose you have a random number generator that has the tiny period of > 120. (Obviously that's a really lousy RNG, but it will do for an > example.) That means it can only produce 120 different results (the > current number, plus the state the generator it is in) before repeating. > > Note that the period is not the same as the spread of values returned, > the two are independent, although naturally the period must be at least > equal to the number of unique values returned. > > If you have a list of just six items, there are 6! = 720 possible > permutations of the list, so AT BEST the random number generator can > produce 120/720 or 17% of the permutations. > > That's an example of the pigeonhole principle, one of the most simple yet > powerful mathematical principles around. If you've got more items than > pigeonholes to put them in, either some will double up or some will miss > out. > > In the case of CPython, the current implementation uses the Mersenne > Twister, which has a huge period of 2**19937. However, 2081! is larger > than that number, which means that at best a list of 2081 items or longer > can't be perfectly shuffled (not every permutation can be selected by the > algorithm). > > -- > Steven. From sundol at sfc.keio.ac.jp Fri Jul 27 09:55:58 2007 From: sundol at sfc.keio.ac.jp (Hyunchul Kim) Date: Fri, 27 Jul 2007 22:55:58 +0900 Subject: [python-list] pdf read & write Message-ID: <1185544558.11085.13.camel@hckim-desktop> Dear all, How can I read a pdf file and add invisible comment? I want to make a script which read a pdf file and add tags inside the file invisibly. Then, I will make a script for managing tags of given pdf files. I know "referencer" can manage tags for pdf file but it seems store tag information to additional file outside pdf file. Any suggestion are welcome. Best, Hyunchul Kim From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 20 03:39:10 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 20 Jul 2007 09:39:10 +0200 Subject: "The basics" difficulties In-Reply-To: <1184784835.875577.69000@i13g2000prf.googlegroups.com> References: <1184784835.875577.69000@i13g2000prf.googlegroups.com> Message-ID: <46a0669a$0$26410$426a34cc@news.free.fr> MooMooBunnyLips at gmail.com a ?crit : > I'm trying to get this basic sample to work: > http://docs.python.org/ext/dnt-basics.html > > When I get to the last step: > $ python setup.py build > > I get this error: > error: Python was build with Visual Studio version 8.0 and > extensions need to be built with the same version of the compiler, > but it isn't installed. > > This is bogus, as I do have VS8 installed. I used it to compile > the python stuff actually. So you may want to check why the setup script does'nt detect it. From steve at REMOVE.THIS.cybersource.com.au Mon Jul 30 19:34:31 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 31 Jul 2007 09:34:31 +1000 Subject: What is the "functional" way of doing this? References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> Message-ID: On Mon, 30 Jul 2007 22:48:10 +0000, beginner wrote: > 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. Seems like a perfectly good function to me :) I don't know about "functional", but that's crying out to be written as a generator: def f(n): while n > 0: n, x = divmod(n, 26) yield x And in use: >>> for x in f(1000): ... print x ... 12 12 1 >>> list(f(1000)) [12, 12, 1] -- Steven. From deets at nospam.web.de Wed Jul 25 12:51:21 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 25 Jul 2007 18:51:21 +0200 Subject: 16-bit colour representation References: <1185364424.797757.84620@22g2000hsm.googlegroups.com> <5gp03nF3hl7siU1@mid.uni-berlin.de> Message-ID: <5gpdc9F3gg1elU1@mid.uni-berlin.de> >> v = 0x0bcd >> b = v & 0xf >> v >>= 4 >> g = v & 0xf >> v >>= 4 >> r = v & 0xf >> print r, g, b >> >> > Alternatively, using 5-bit colors you would use > > b = v & 0x1f > g = (v >> 5) & 0x1f > r = (v >> 10) & 0x1f Darn. I knew I missed _something_... Diez From musiccomposition at gmail.com Mon Jul 9 08:29:15 2007 From: musiccomposition at gmail.com (Benjamin) Date: Mon, 09 Jul 2007 12:29:15 -0000 Subject: The file executing In-Reply-To: References: <1183426846.550981.11910@m36g2000hse.googlegroups.com> <1183430828.997331.84340@e9g2000prf.googlegroups.com> <1183470421.012591.243300@k79g2000hse.googlegroups.com> <1183752922.290253.8600@q75g2000hsh.googlegroups.com> Message-ID: <1183984155.335922.123830@r34g2000hsd.googlegroups.com> On Jul 9, 6:42 am, "Gabriel Genellina" wrote: > En Fri, 06 Jul 2007 17:15:22 -0300, Benjamin > escribi?: > > >> > > > How does one get the path to the file currently executing (not the > >> > > > cwd). Thank you > > So: > > if __name__ == "main": > > currentDir = os.path.dirname(sys.argv[0]) > > else: > > currentDir = os.path.dirname(__file__) > > I think you meant to test for "__main__", but anyway, this should be Yes > enough: > currentDir = os.path.dirname(__file__) > or perhaps os.path.dirname(os.path.abspath(__file__)). Try to determine > that early in your program because __file__ may contain a relative path > (and will give a wrong result after changing the current directory). I do it right at the top of the first module. Thanks for the help. > > -- > Gabriel Genellina From josiah.carlson at sbcglobal.net Sun Jul 15 21:06:08 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sun, 15 Jul 2007 18:06:08 -0700 Subject: Python Subprocess module In-Reply-To: References: Message-ID: Dave Sampson wrote: > I am supposed to be able to entre 'y' and return for the program to > continue if I agree with what I see in the stdout. > > A problem exists though that I have tried > 'y' > 'y\n' > 'y\r' Depending on the platform, you may need to send '\r\n'. > ASPN Python cookbok provided some code for a new Popen Class that allows > for interaction but I don't think I need to go that root.... You probably mean: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 Why is that not sufficient? It will allow interaction with a called subprocess, in a cross-platform manner, etc. - Josiah From andre.roberge at gmail.com Sat Jul 28 19:13:05 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Sat, 28 Jul 2007 23:13:05 -0000 Subject: Crunchy security advisory Message-ID: <1185664385.106256.59250@o61g2000hsh.googlegroups.com> A security hole has been uncovered in Crunchy (version 0.9.1.1 and earlier). Anyone using Crunchy to browse web tutorials should only visit sites that are trustworthy. We are working hard at fixing the hole; a new release addressing the problems that have been found should be forthcoming shortly. Andr? ----- The security problem is as follows: In theory, a web page could contain some javascript code (or link to such code) that would bypass Crunchy's filter to be executed by the browser. If that is the case, the javascript code could be designed to send some Python code directly to the Python backend (i.e. without the Crunchy user pressing a button, or having the chance to view the code to be executed) so that it is executed. Such code could result in deleting the entire files or installing some virus on the user's machine. At the moment, the risk is pretty low. Crunchy already removes all obvious (and most non-obvious) javascript code, links to such code, etc. The holes found require the use of some uncommon combination of html and css code, with a particular knowledge of Firefox. (Note that browsers other than Firefox are likely to be even more vulnerable). Furthermore, Crunchy is not that well known that it is likely to be a target by a cracker that would 1) write a "tutorial" interesting enough to lure current Crunchy users (who, at this point, are likely to include only advanced Python users) and 2) write some fairly involved javascript code to bypass the second security layer (where the commands enabling communication between the browser and crunchy are made up of random string generated uniquely at each new Crunchy session). If anyone is interested in security issues related to Crunchy, feel free to contact me directly. From sjmachin at lexicon.net Sun Jul 8 16:53:42 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 08 Jul 2007 13:53:42 -0700 Subject: allow scripts to use .pth files? In-Reply-To: <1183899193.766331.13210@22g2000hsm.googlegroups.com> References: <1183899193.766331.13210@22g2000hsm.googlegroups.com> Message-ID: <1183928022.719873.49470@i38g2000prf.googlegroups.com> On Jul 8, 10:53 pm, samwyse wrote: > On Jul 3, 9:35 am, Alan Isaac wrote: > > > Suppose I have a directory `scripts`. > > I'd like the scripts to have access to a package > > that is not "installed", i.e., it is not on sys.path. > > On this list, various people have described a variety > > of tricks they use, but nobody has proposed a > > pretty way to allow this. > > I am therefore assuming there is not one. (?) > > > How about allowing a `scripts.pth` file in such a `scripts` > > directory, to work like a path configuration file? > > (But to be used only when __name__=="__main__".) > > Drawbacks? > > > Alan Isaac > > before i can adequately shoot down your proposal, i need more > information. > > first, how does the interpreter know to look in 'scripts' for your > 'scripts.pyh' file and not in '.' or '~' or sys.argv[0] or someplace > else? I got the impression that the OP was suggesting that the interpreter look in the directory in which it found the script. > and you do know, don't you, that if you run 'scripts/ > myscript.py' then 'scripts' is automagically prepended to the search > path for modules? I got the impression that the problem was that the package was not only not on sys.path but also not in the same directory as the script that wanted to import it. Otherwise the OP's script.p?h file need only contain ".\n" (or the path to the directory in which it resided!!), and I doubt that he was proposing something so silly. I'm curious whether you think that the OP's use of ".pth" was a typo, and whether you have read this: http://docs.python.org/lib/module-site.html Cheers, John From kbk at shore.net Wed Jul 18 02:30:16 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Wed, 18 Jul 2007 02:30:16 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200707180630.l6I6UGld029215@hampton.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 394 open ( +2) / 3827 closed (+35) / 4221 total (+37) Bugs : 1046 open ( +4) / 6773 closed (+16) / 7819 total (+20) RFE : 262 open ( -1) / 293 closed ( +1) / 555 total ( +0) New / Reopened Patches ______________________ make build_opener raise exception when not passed a handler (2007-07-10) CLOSED http://python.org/sf/1750931 opened by Robert Renaud struni: fix for test_cmd_line (2007-07-10) CLOSED http://python.org/sf/1751493 opened by Christian Heimes struni: Replace assert_(==) with failUnlessEqual (2007-07-11) CLOSED http://python.org/sf/1751515 opened by Christian Heimes curses - new window methods: addchstr and addchnstr (2007-07-11) http://python.org/sf/1751519 opened by Wojciech Mula Dict comprehensions (2007-07-11) CLOSED http://python.org/sf/1751800 opened by Thomas Wouters Patch for Windows build (2007-07-11) CLOSED http://python.org/sf/1751801 opened by Thomas Heller struni: gettext fixes (2007-07-11) CLOSED http://python.org/sf/1751958 opened by Christian Heimes Typo in Lib/lib-tk/ScrolledText.py (2007-07-11) CLOSED http://python.org/sf/1751965 opened by Ali Gholami Rudi opcode.h incorrectly describes arg of SETUP_* (2007-07-11) CLOSED http://python.org/sf/1752132 opened by Christopher Tur Lesniewski-Laas Use the bytes type in asynchat (2007-07-11) CLOSED http://python.org/sf/1752173 opened by Alexandre Vassalotti fixing 2.5.1 build with unicode and dynamic loading disabled (2007-07-11) http://python.org/sf/1752175 opened by Alexander Neundorf PyHeapTypeObject fix (2007-07-11) http://python.org/sf/1752184 opened by Thomas Heller struni: for for poll, pep263, bigmem and a bit pickletool (2007-07-11) CLOSED http://python.org/sf/1752195 opened by Christian Heimes struni: _fileio fixes for Windows (2007-07-11) CLOSED http://python.org/sf/1752225 opened by Amaury Forgeot d'Arc Use the Unicode API in dlmodule.c (2007-07-11) CLOSED http://python.org/sf/1752229 opened by Alexandre Vassalotti urllib2 1750931 alternative patch (2007-07-12) CLOSED http://python.org/sf/1752270 opened by John J Lee reference leak in _PyUnicode_AsDefaultEncodedString (2007-07-12) CLOSED http://python.org/sf/1752317 opened by Amaury Forgeot d'Arc getaddrinfo no longer used in httplib (2007-07-12) http://python.org/sf/1752332 opened by John J Lee fix failing unit tests in mmap in struni branch (2007-07-12) CLOSED http://python.org/sf/1752647 opened by Joe Gregorio chown() does not handle UID > INT_MAX (2007-07-12) http://python.org/sf/1752703 opened by Andrew Ferguson Add RegEnableReflectionKey and RegDisableReflectionKey (2007-07-13) http://python.org/sf/1753245 opened by Mark Hammond Lib/regrtest.py -x 'test_xxx' does not work (2007-07-13) CLOSED http://python.org/sf/1753310 opened by Thomas Heller test_urllib2.test_fie passes (2007-07-13) CLOSED http://python.org/sf/1753889 opened by Hasan Diwan Tighter co_stacksize computation in stackdepth_walk (2007-07-14) http://python.org/sf/1754094 opened by Christopher Tur Lesniewski-Laas Deprecation warning for `backticks` (2007-07-15) http://python.org/sf/1754271 opened by Tom Lee Deprecation warning for <> (NOTEQUAL) (2007-07-15) http://python.org/sf/1754273 opened by Tom Lee struni: Bytes support for TextIOWrapper.write() (2007-07-15) CLOSED http://python.org/sf/1754339 opened by Christian Heimes linecache package handling (2007-07-15) http://python.org/sf/1754483 opened by Kevin Goodsell struni: Various patches for windows (2007-07-16) CLOSED http://python.org/sf/1754484 opened by Amaury Forgeot d'Arc Non-portable address length calculation for AF_UNIX sockets (2007-07-16) http://python.org/sf/1754489 opened by Vlado Handziski urllib2 tests pass (2007-07-16) http://python.org/sf/1755133 opened by Hasan Diwan struni: corrections for test_cProfile (2007-07-17) CLOSED http://python.org/sf/1755176 opened by Amaury Forgeot d'Arc struni: corrections in ftplib (2007-07-17) CLOSED http://python.org/sf/1755206 opened by Amaury Forgeot d'Arc struni: correction for sockets on win32 (2007-07-17) CLOSED http://python.org/sf/1755214 opened by Amaury Forgeot d'Arc struni: correction for _winreg module (2007-07-17) CLOSED http://python.org/sf/1755229 opened by Amaury Forgeot d'Arc Patch for [ 735515 ] urllib2 should cache 301 redir (2007-07-18) http://python.org/sf/1755841 opened by O.R.Senthil Kumaran Show Location of Unicode Escape Errors (2007-07-18) http://python.org/sf/1755885 opened by Kurt B. Kaiser Patches Closed ______________ make build_opener raise exception when not passed a handler (2007-07-10) http://python.org/sf/1750931 closed by gbrandl struni: fix for test_cmd_line (2007-07-10) http://python.org/sf/1751493 closed by gvanrossum struni: Replace assert_(==) with failUnlessEqual (2007-07-10) http://python.org/sf/1751515 closed by gvanrossum Dict comprehensions (2007-07-11) http://python.org/sf/1751800 closed by twouters Patch for Windows build (2007-07-11) http://python.org/sf/1751801 closed by theller Patch for PEP 3109 (2007-05-06) http://python.org/sf/1713889 closed by gvanrossum Implementation of @abstractmethod for PEP 3119 (2007-04-24) http://python.org/sf/1706989 closed by gvanrossum struni: gettext fixes (2007-07-11) http://python.org/sf/1751958 closed by gvanrossum Typo in Lib/lib-tk/ScrolledText.py (2007-07-11) http://python.org/sf/1751965 closed by gbrandl opcode.h incorrectly describes arg of SETUP_* (2007-07-11) http://python.org/sf/1752132 closed by gbrandl Use the bytes type in asynchat (2007-07-11) http://python.org/sf/1752173 closed by gvanrossum struni: for for poll, pep263, bigmem and a bit pickletool (2007-07-11) http://python.org/sf/1752195 closed by gvanrossum struni: _fileio fixes for Windows (2007-07-11) http://python.org/sf/1752225 closed by theller Use the Unicode API in dlmodule.c (2007-07-11) http://python.org/sf/1752229 closed by gvanrossum urllib2 1750931 alternative patch (2007-07-11) http://python.org/sf/1752270 closed by gbrandl reference leak in _PyUnicode_AsDefaultEncodedString (2007-07-11) http://python.org/sf/1752317 closed by gvanrossum binary and new-style octal literals (2007-03-14) http://python.org/sf/1681002 closed by twouters Patch inspect.py for IronPython / Jython Compatibility (2007-06-19) http://python.org/sf/1739696 closed by gbrandl Fix selectmodule.c compilation on GNU/Hurd (2007-06-11) http://python.org/sf/1735030 closed by gbrandl Patch to vs 2005 build (2007-05-26) http://python.org/sf/1726195 closed by gbrandl Datetime enhancements (2007-02-21) http://python.org/sf/1665292 closed by gbrandl '%G' string formatting doesn't catch same errors as '%g' (2007-03-05) http://python.org/sf/1673759 closed by gbrandl Improve doc for time.strptime (2007-06-05) http://python.org/sf/1731659 closed by gbrandl Expect skips by platform (2007-06-05) http://python.org/sf/1731169 closed by gbrandl Zipfile tweaks and test coverage improvement (2007-03-07) http://python.org/sf/1675424 closed by gbrandl fix failing unit tests in mmap in struni branch (2007-07-12) http://python.org/sf/1752647 closed by gvanrossum Lib/regrtest.py -x 'test_xxx' does not work (2007-07-13) http://python.org/sf/1753310 closed by gbrandl test_urllib2.test_fie passes (2007-07-13) http://python.org/sf/1753889 closed by gvanrossum struni: Bytes support for TextIOWrapper.write() (2007-07-15) http://python.org/sf/1754339 closed by gvanrossum struni: Various patches for windows (2007-07-15) http://python.org/sf/1754484 closed by gvanrossum struni: corrections for test_cProfile (2007-07-16) http://python.org/sf/1755176 closed by gvanrossum struni: corrections in ftplib (2007-07-16) http://python.org/sf/1755206 closed by gvanrossum struni: correction for sockets on win32 (2007-07-16) http://python.org/sf/1755214 closed by gvanrossum struni: correction for _winreg module (2007-07-16) http://python.org/sf/1755229 closed by gvanrossum New / Reopened Bugs ___________________ Popen pipe file descriptor leak on OSError in init (2007-07-10) http://python.org/sf/1751245 opened by Justin Francis struni: str() doesn't call __str__() of subclasses of str (2007-07-11) http://python.org/sf/1751598 opened by Christian Heimes struni: Three ctypes tests are SEGFAULTing (2007-07-11) CLOSED http://python.org/sf/1751885 opened by Christian Heimes struni: help() is broken (2007-07-11) http://python.org/sf/1751932 opened by Christian Heimes tkFileDialog closes Python when used (2007-07-11) http://python.org/sf/1752252 opened by ferrari24 RotatingFileHandler.doRollover behave wrong vs. log4j's (2007-07-12) http://python.org/sf/1752539 opened by Jin Qing email.message_from_string: initial line gets discarded (2007-07-12) CLOSED http://python.org/sf/1752723 opened by David Webster Exception in HTMLParser for special JavaScript code (2007-07-12) http://python.org/sf/1752919 opened by Eugine Kosenko Open always create new tab or new browser (2007-07-13) http://python.org/sf/1753371 opened by Ilan Peleg struni: assertion in Windows debug build (2007-07-13) http://python.org/sf/1753395 opened by Thomas Heller subprocess.check_call() new in 2.5 (2007-07-13) CLOSED http://python.org/sf/1753406 opened by Yitz Gale base64 "legacy" functions violate RFC 3548 (2007-07-13) http://python.org/sf/1753718 opened by Paul Winkler xmlrpclib.Binary doesn't say which base64 spec it implements (2007-07-13) http://python.org/sf/1753732 opened by Paul Winkler subprocess raising "No Child Process" OSError (2007-07-13) http://python.org/sf/1753891 opened by slowfood Docstring for codecs.lookup is incorrect (2007-07-15) http://python.org/sf/1754453 opened by Omari Norman "yield" causes strange behaviour (2007-07-16) CLOSED http://python.org/sf/1754456 opened by Miki Tebeka subprocess.Popen.wait fails sporadically with threads (2007-07-16) http://python.org/sf/1754642 opened by Geoffrey Bache document default values for sort parameters (2007-07-16) http://python.org/sf/1755097 opened by Ilya Sandler subprocess raising "No Child Process" OSError (2007-07-16) CLOSED http://python.org/sf/1755150 opened by slowfood Deadlocks with fork() and multithreading (2007-07-16) http://python.org/sf/1755179 opened by Vanco Buca Problem with socket.gethostbyaddr() and KeyboardInterrupt (2007-07-17) http://python.org/sf/1755388 opened by STINNER Victor Bugs Closed ___________ Bad documentation of SMTPException (2007-04-05) http://python.org/sf/1694950 closed by quiver Python-2.5.1.tar.bz2 build failed at Centos-4.5 server (2007-06-17) http://python.org/sf/1738559 closed by loewis os.getlogin should use the DISPLAY and not the tty (2007-07-08) http://python.org/sf/1750013 closed by loewis struni: Three ctypes tests are SEGFAULTing (2007-07-11) http://python.org/sf/1751885 closed by tiran string and unicode formatting are missing a test for "G" (2007-03-05) http://python.org/sf/1673757 closed by gbrandl PCbuild8/pcbuild.sln is missing "_socket" sub-project (2007-04-15) http://python.org/sf/1700865 closed by gbrandl test_sqlite fails on OSX G5 arch if test_ctypes is run (2006-10-21) http://python.org/sf/1581906 closed by theller email.message_from_string: initial line gets discarded (2007-07-12) http://python.org/sf/1752723 closed by bwarsaw IDE needs to remember status of interactive window (2003-06-22) http://python.org/sf/758565 closed by ronaldoussoren subprocess.check_call() new in 2.5 (2007-07-13) http://python.org/sf/1753406 closed by gbrandl Segfault in c_char_p of ctypes (2007-04-16) http://python.org/sf/1701409 closed by theller non-standard: array[0] (2007-01-31) http://python.org/sf/1649098 closed by theller ctypes: problem with large integers (2007-04-19) http://python.org/sf/1703952 closed by theller ctypes documenation obscure and incomplete (2006-05-09) http://python.org/sf/1484580 closed by theller Python 2.5b2 fails to build on Solaris 10 (GCC Compiler) (2006-07-26) http://python.org/sf/1529269 closed by theller "yield" causes strange behaviour (2007-07-16) http://python.org/sf/1754456 closed by tebeka subprocess raising "No Child Process" OSError (2007-07-16) http://python.org/sf/1755150 deleted by slowfood RFE Closed __________ if __name__=='__main__' missing in tutorial (2007-01-17) http://python.org/sf/1637365 closed by gbrandl From bj_666 at gmx.net Tue Jul 17 04:18:10 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Jul 2007 08:18:10 GMT Subject: Best method for inter process communications References: <1184606522.541918.18870@22g2000hsm.googlegroups.com> Message-ID: <5g3ca2F3dv5s2U1@mid.uni-berlin.de> On Tue, 17 Jul 2007 08:08:45 +0200, Hendrik van Rooyen wrote: > I heard a rumour once that a "hello world" string takes something like > 10k bytes in XMLRPC - have never bothered to find out if its BS... Just try it out: In [8]: import xmlrpclib In [9]: a = xmlrpclib.dumps(('hello world',)) In [10]: len(a) Out[10]: 80 In [11]: print a hello world Even with some additional boilerplate like XML declaration etc. there is still a little bit room until 10?kB are reached. :-) Ciao, Marc 'BlackJack' Rintsch From bignose+hates-spam at benfinney.id.au Sat Jul 14 23:43:38 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 15 Jul 2007 13:43:38 +1000 Subject: Can a low-level programmer learn OOP? References: Message-ID: <87vecmgwlx.fsf@benfinney.id.au> Dennis Lee Bieber writes: > Though I should have added that, in Python, the toolset tends to > be... just an editor... Much more than that. The common toolset I see used is: * A customisable, flexible, programmer's text editor * The online documentation in a web browser * A Python interactive shell * An automated build tool like 'make' * A programmable shell for ad-hoc tasks * A multi-session terminal program to run all these simultaneously What I *don't* see is some single all-in-one tool specific to programming a particular language. Having learned one good instance of each of the above, it seems silly to need to learn all of them again simply because one has started using Python as the programming language. -- \ "Room service? Send up a larger room." -- Groucho Marx | `\ | _o__) | Ben Finney From vedrandekovic at v-programs.com Sat Jul 28 05:10:16 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Sat, 28 Jul 2007 02:10:16 -0700 Subject: a simple string question In-Reply-To: <1185599148.583067.42910@d30g2000prg.googlegroups.com> References: <1185549793.114644.62170@k79g2000hse.googlegroups.com> <1185558406.916313.32980@r34g2000hsd.googlegroups.com> <1185589263.743811.204040@x40g2000prg.googlegroups.com> <1185599148.583067.42910@d30g2000prg.googlegroups.com> Message-ID: <1185613816.996100.323090@r34g2000hsd.googlegroups.com> On 28 srp, 07:05, Zentrader wrote: > > > vedrandeko... at v-programs.com wrote: > > > > NEW TEXT : "Hello world;\nHello:\n\t\t\n\n\n\n\n\nHello2" > > If you are doing all of this to format the output into columns, > Python's print() or write() will do this, and is easier as well. Some > more info on what you want to do will clear things up. Hi, That is confusing me too, so now I will try explain it more.This is text before "translation": Let me explain you with python code. I want to this "function" act code indentation >>> Short_Text="n=90; if n==90:print 'ok'" Then now I must write that function for detect ";" and ":", and if that function detect ";" then it appends "\n" before ";" but if detect ":" then it appends "\n\t\t\t\t\t\t\t\t" >>> Short_text_after_translation="n=90;\nif n==90:\n\t\t\t\t\t\t\t\tprint 'ok" ...And now when we run this code with exec this must look like: n=90; if n==90: print 'ok' I think this will be enough for help. Regards, Vedran From steve at holdenweb.com Sun Jul 22 18:13:45 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 22 Jul 2007 18:13:45 -0400 Subject: split on NO-BREAK SPACE In-Reply-To: <20070722193732.4947.752757075.divmod.quotient.14354@ohm> References: <20070722193732.4947.752757075.divmod.quotient.14354@ohm> Message-ID: Jean-Paul Calderone wrote: > On Sun, 22 Jul 2007 21:13:02 +0200, Peter Kleiweg wrote: >> Carsten Haese schreef op de 22e dag van de hooimaand van het jaar 2007: >> >>> On Sun, 2007-07-22 at 17:44 +0200, Peter Kleiweg wrote: >>>>> It's a feature. See help(str.split): "If sep is not specified or is >>>>> None, any whitespace string is a separator." >>>> Define "any whitespace". >>> Any string for which isspace returns True. >> Define white space to isspace() >> >>>> Why is it different in and ? >>>>>> '\xa0'.isspace() >>> False >>>>>> u'\xa0'.isspace() >>> True >> Here is another "space": >> >> >>> u'\uFEFF'.isspace() >> False >> >> isspace() is inconsistent > > It's only inconsistent if you think it should behave based on the > name of a unicode code point. It doesn't use the name, though. It > uses the category. NO-BREAK SPACE is in the Zs category (Separator, Space). > ZERO WIDTH NO-BREAK SPACE is in the Cf category (Other, Format). > > Maybe that makes unicode inconsistent (I won't try to argue either way), > but it's pretty clear that isspace is being consistent based on the data > it has to work with. > Well, if you're going to start answering questions with FACTS, how can questioners reply on their prejudices to guide them any more? 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 Mon Jul 30 21:13:58 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 30 Jul 2007 18:13:58 -0700 Subject: What is the "functional" way of doing this? In-Reply-To: References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> Message-ID: James Stroud wrote: > py> f = lambda n, r=None: f(n/26, (r if r else [])) + [n%26] if n/26 > else [n%26] > py> f(300000) > [17, 1, 20, 12] > py> f(30000) > [1, 18, 9, 22] > py> f(3000) > [4, 11, 10] > py> f(1000) > [1, 12, 12] > > Oops, those are backwards. Should be: f = lambda n, r=None: [n%26] + f(n/26, (r if r else [])) if n/26 else [n%26] -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From no at no.no Sun Jul 22 09:46:46 2007 From: no at no.no (Daniel) Date: Sun, 22 Jul 2007 16:46:46 +0300 Subject: Sort lines in a text file References: <1185073397.821811.143260@k79g2000hse.googlegroups.com> Message-ID: On Sun, 22 Jul 2007 06:03:17 +0300, leegold wrote: > say I have a text file: > > zz3 uaa4a ss 7 uu > zz 3 zzzz66 ppazz9 > aaaaaaaaa00000zz0 > > I want to sort the text file. I want the key to be the number after > the two "zz". Or I guess a string of two zz then a number....So > that's 3, 9, 0 > > I'm trying to say that I want to sort lines in a file based on a > regular expression. How could I do that in Python? I'm limited to > Python 2.1, I can't add any 2nd party newer tools. > > Thanks > Lee G. > Shouldn't it be 3, 6, 9, 0 From mensanator at aol.com Mon Jul 30 19:14:59 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 30 Jul 2007 16:14:59 -0700 Subject: 128 or 96 bit integer types? In-Reply-To: References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com> <1185562901.206212.52570@j4g2000prf.googlegroups.com> <1185607142.096574.209200@e16g2000pri.googlegroups.com> <37pma35qhpca41cvgjfrdkdoru27rgml9s@4ax.com> Message-ID: <1185837299.024919.174280@z24g2000prh.googlegroups.com> On Jul 29, 11:35 pm, Tim Roberts wrote: > John DeRosa wrote: > >On Sat, 28 Jul 2007 00:19:02 -0700, "mensana... at aol.com" > > wrote: > > >>For example, how many ways can you put 492 marbles into > >>264 ordered bins such that each bin has at least 1 marble? > > >>The answer > > >>66189415264331559482776409694993032407028709677550 > >>59629130019289014193777349831417543311612293951363 > >>4124491233746912456893016976209252459301489030 > > >You missed that blue one in the corner... Actually, the blue one in the corner wasn't missed, it was deliberately omitted. When you add the restriction that each bin must contain at least one marble, the number of partitions of depth items into width bins is comb(depth-1,width-1). So comb(491,263) IS, in fact, the correct answer even though the marble count seems to be wanting. > > He lost that one to a talented 12-year-old with a keen eye and a > well-balanced steelie... > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. From nicolasg at gmail.com Wed Jul 25 02:34:46 2007 From: nicolasg at gmail.com (NicolasG) Date: Wed, 25 Jul 2007 06:34:46 -0000 Subject: How to create a single executable of a Python program Message-ID: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> Dear fellows, I'm trying to create a executable file using py2exe . Unfortunately along with the python executable file it also creates some other files that are needed in order to the executable be able to run in a system that doesn't have Python installed. Can some one guide me on how can I merge all this files created by py2exe in a single exe file ? If I have a python program that uses an image file I don't want this image file to be exposed in the folder but only to be accessible through the program flow.. Regards, Nicolas. From nick at craig-wood.com Thu Jul 5 04:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 05 Jul 2007 03:30:03 -0500 Subject: what is wrong with that r"\" References: <5f1ehiF3a62csU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Wed, 04 Jul 2007 11:21:14 +0000, Neil Cerutti wrote: > > > If the escaped quotes didn't function in raw strings, I'd be > > unable to construct (with a single notation) a regex that > > included both kinds of quotes at once. > > > > re.compile(r"'\"") > > Where's the problem!? :: > > re.compile(r''''"''') > > Ah, I see -- readability is the problem. :-) Actually the problem is that those backslashes don't actually disappear thus producing non-intuititive behaviour. The example you provided produces a different result to Neil's result. >>> r"'\"" '\'\\"' >>> r''''"''' '\'"' >>> Neil is correct in saying that his example works for regexp matching though, as the regexp matcher understands \" as being the same as ". So r"" strings work well as Regexp-strings but not so well as Raw-strings IMHO. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From aleax at mac.com Mon Jul 16 01:28:12 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 15 Jul 2007 22:28:12 -0700 Subject: how to implementation latent semantic indexing in python.. References: Message-ID: <1i1bczv.b60cm8y6ygowN%aleax@mac.com> 78ncp wrote: > hi... > how to implementation algorithm latent semantic indexing in python > programming...?? You may get more responses (as in, >0!-) if you give some URL about what this algorithm is supposed to do. Alex From glen.e.mettler at lmco.com Thu Jul 12 17:17:31 2007 From: glen.e.mettler at lmco.com (meg99) Date: Thu, 12 Jul 2007 14:17:31 -0700 Subject: New guy help with setup Message-ID: <1184275051.504507.116080@57g2000hsv.googlegroups.com> I just downloaded 2.5 and read the readme file. It says "Before you can build Python, you must first confiigure it....Start by running the script "./configure". I can't find "./configure" I am running Windows XP SP2 btw Python.exe gives me a black window Pythonw.exe does nothing (I assume this is a windows interface) thanks meg99 From goon12 at gmail.com Wed Jul 18 10:46:59 2007 From: goon12 at gmail.com (Joe Riopel) Date: Wed, 18 Jul 2007 10:46:59 -0400 Subject: The Modernization of Emacs: exists already In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272678.877166.209640@j4g2000prf.googlegroups.com> <1184764620.778937.264760@m37g2000prh.googlegroups.com> Message-ID: <6a2ccd190707180746w62b98fbeq9a8b4e26b672b4a0@mail.gmail.com> Sorry, I don't understand why this is still on the python mailing list. :wq From steve at holdenweb.com Mon Jul 9 14:38:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 09 Jul 2007 14:38:24 -0400 Subject: socket.makefile() buggy? In-Reply-To: <1183970531.241008.295940@z28g2000prd.googlegroups.com> References: <1183892789.434028.15370@x35g2000prf.googlegroups.com> <1183970531.241008.295940@z28g2000prd.googlegroups.com> Message-ID: ahlongxp wrote: > On Jul 8, 9:54 pm, Steve Holden wrote: >> That's a pretty pejorative subject line for someone who's been >> programming Python [guessing by the date of your first post] for about a >> month. >> [...] > And last but not least, I' here to be helped and help as long as I > can. > But as you noticed I'm not very good at expressing myself in English. > I didn't mean to offense anyone but I might seem to be rude or > offensive. > I hope you can understand. > Sure. I felt it necessary to explain my remarks as my own remarks seemed potentially rude or offensive. Naturally not everyone has English as a first language, but your first post was good enough that it wasn't immediately obvious in your case. 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 nicolasg at gmail.com Thu Jul 26 02:37:51 2007 From: nicolasg at gmail.com (NicolasG) Date: Thu, 26 Jul 2007 06:37:51 -0000 Subject: How to create a single executable of a Python program In-Reply-To: References: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> Message-ID: <1185431871.579595.234830@l70g2000hse.googlegroups.com> > You need to tell us why you "think" you need this and perhaps we can make a > suggestion. Question: Have you installed ANY applications recently that > consisted of only a single file on your hard drive? Answer: No. Most > applications install many (sometimes hundreds) of files. So what is the > problem. If you want a single file to distribute, look at Inno Installer. Use > it to make a single, setup.exe out of all the files that come out of py2exe > along with documentation, shortcuts, etc. that a good modern application needs. > > -Larry I "want" to create a single file for two of my very simple/small programs. For very simple/small programs I don't need to distribute documentation, shortcuts etc.. I just want a single file to run ! Another reason is that for another program I wrote has to do with displaying an Image file and I want that this image file can be visible only through my program and not exposed in the same directory where my program is located. Thank you all for the suggestions, I will try some methods you mentioned. Regards, Nicolas. From horpner at yahoo.com Thu Jul 5 13:28:24 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 05 Jul 2007 17:28:24 GMT Subject: Where is the syntax for the dict() constructor ?! References: <468D1D9D.6060002@gmail.com> Message-ID: On 2007-07-05, Captain Poutine wrote: > I'm simply trying to read a CSV into a dictionary. > > (if it matters, it's ZIP codes and time zones, i.e., > 35983,CT > 39161,CT > 47240,EST > > > > Apparently the way to do this is: > > import csv > > dictZipZones = {} > > reader = csv.reader(open("some.csv", "rb")) > for row in reader: > # Add the row to the dictionary In addition to Chris's answer, the csv module can read and write dictionaries directly. Look up csv.DictReader and csv.DictWriter. -- Neil Cerutti In my prime I could have handled Michael Jordan. Of course, he would be only 12 years old. --Jerry Sloan From phil at riverbankcomputing.co.uk Thu Jul 26 14:27:54 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 26 Jul 2007 19:27:54 +0100 Subject: compiling sip on vista In-Reply-To: <1185435734.855452.30640@r34g2000hsd.googlegroups.com> References: <1185435734.855452.30640@r34g2000hsd.googlegroups.com> Message-ID: <200707261927.54851.phil@riverbankcomputing.co.uk> On Thursday 26 July 2007 8:42 am, boriq wrote: > Hi, > > I'm trying to compile sip 4.6 on windows vista. > I have Python 2.5 installed in c:\Python25. > I have Qt 4.3.0 installed in c:\Qt\4.3.0 together with MinGW in c: > \MinGW. > I have environment variable PATH set to c:\Qt\4.3.0\bin;c:\MinGW\bin > And here is what I did: > C:\sip-4.6>configure.py -p win32-g++ > This is SIP 4.6 for Python 2.5 on win32. > The SIP code generator will be installed in C:\Python25. > The SIP module will be installed in C:\Python25\Lib\site-packages. > The SIP header file will be installed in C:\Python25\include. > The default directory to install .sip files in is C:\Python25\sip. > The platform/compiler configuration is win32-g++. > Creating sipconfig.py? > Creating top level Makefile? > Creating sip code generator Makefile? > Creating sip module Makefile? > > C:\sip-4.6>make > makefile:29: warning: overriding commands for target `.c.o' > makefile:26: warning: ignoring old commands for target `.c.o' > mingw32-make[1]: Entering directory `C:/sip-4.6/sipgen' > gcc -c -O2 -w -DUNICODE -DQT_LARGEFILE_SUPPORT -I. -o main.o main.c > gcc: installation problem, cannot exec `cc1?: No such file or > directory > mingw32-make[1]: *** [main.o] Error 1 > mingw32-make[1]: Leaving directory `C:/sip-4.6/sipgen' > mingw32-make: *** [all] Error 2 > > C:\sip-4.6> > > Could anybody tell me what's wrong here and what should I make to > correct that? > > Thanks in advance. There would seem to be something wrong with your MinGW setup. Nothing to do with sip or Vista. Phil From bg_ie at yahoo.com Mon Jul 30 10:36:00 2007 From: bg_ie at yahoo.com (bg_ie at yahoo.com) Date: Mon, 30 Jul 2007 07:36:00 -0700 Subject: File handle not being released by close Message-ID: <1185806160.161748.58910@d55g2000hsg.googlegroups.com> Hi, I'm in the process of writing some code and noticed a strange problem while doing so. I'm working with PythonWin 210 built for Python 2.5. I noticed the problem for the last py file processed by this script, where the concerned tmp file is only actually written to when PythonWin is closed. In other words, after I run this script, one of the generated tmp files has a size of 0kB. I then close PythonWin and it is then written to. I'm guessing the garbage collector is causing the file to be written, but shouldn't close do this? /Barry import os, time, string dir = 'c:\\temp1' def listAllFile(fileNames,dir,files): def f1(a,dir=dir): return os.path.join(dir,a) files2 = map(f1, files) fileNames.extend(files2) fileNames = [] os.path.walk(dir,listAllFile,fileNames) for fileName in fileNames: fileBeginning = os.path.splitext(fileName)[0] fileEnd = os.path.splitext(fileName)[1] if fileEnd == ".py": print fileName f=open(fileBeginning+".tmp", 'w') f.write("Hello") f.close From ken at seehart.com Sat Jul 21 16:46:20 2007 From: ken at seehart.com (Ken Seehart) Date: Sat, 21 Jul 2007 13:46:20 -0700 Subject: UnicodeDecodeError Message-ID: <46A2709C.3040602@seehart.com> I get this whenever I encounter a non-ascii character in a non-unicode string: UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 23: ordinal not in range(128) The string in question is "... ESPA\xd1OL ..." I completely understand why I get the error, and my solution will be to simply convert to unicode (since the code that uses the string is unicode ready). I am wondering if anyone knows where I can find a mapping from this particular extended ascii code (where \xd1 is ?), to the corresponding unicode characters. Ken From orsenthil at users.sourceforge.net Mon Jul 23 22:59:48 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Tue, 24 Jul 2007 08:29:48 +0530 Subject: set_proxy in urllib2 is driving my crazy In-Reply-To: <1185184217.388353.104400@z24g2000prh.googlegroups.com> References: <1185184217.388353.104400@z24g2000prh.googlegroups.com> Message-ID: <20070724025948.GA3573@gmail.com> * est [2007-07-23 09:50:17]: > A simple py script > > import urllib2 > req=urllib2.Request("http://www.google.com") > req.set_proxy("127.0.0.1:1","http") > print urllib2.urlopen(req).read() > Try to use the ProxyHandler of urllib2. import urllib2 proxy_url = 'http://' + PROXY_USER + ':' + PROXY_PASSWORD + \ '@' + PROXY_IP + ':' + PROXY_PORT proxy_support = urllib2.ProxyHandler({'http': proxy_url}) opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler) urllib2.install_opener(opener) print urllib2.urlopen(req).read() > urllib2.URLError: The error indicates a network issue. Please see the difference when you use the ProxyHandler to try it. -- O.R.Senthil Kumaran http://uthcode.sarovar.org From walterbyrd at iname.com Wed Jul 25 18:31:45 2007 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 25 Jul 2007 15:31:45 -0700 Subject: Why PHP is so much more popular for web-development In-Reply-To: References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <82d28c40707251158ibae2f9u70889f01ac45a9f6@mail.gmail.com> Message-ID: <1185402705.421724.3680@x35g2000prf.googlegroups.com> On Jul 25, 3:55 pm, Steve Holden wrote: > Jeff McNeil wrote: > > Unfortunately, I also find that PHP programmers are usually more > > plentiful than their Python counterparts. When thinking of staffing > > an organization, it's common to target a skill set that's cheaper to > > employ and easier to replace down the road if need be. > > Right, that's why hospitals are replacing their surgeons with butchers. > There are so many more of them available. It's only cutting meat, after all. > Hospitals probably would if they could. Healthcare is extremely regulated. Software development, web or otherwise, is still the wild- west. Besides, I don't think it's quite fair to characterize all PHP developers as "butchers" and Python developers as "surgeons." Python may be superior to PHP, but come on now. Besides, I see about 100X more ads for PHP programmers, than Python programmers. My guess is that there probably are a lot more PHP developers, especially web- developers. > > Also, larger hosting shops are hesitant to run things such as TG and > > Rails that require an additional server process. The name of the game > > is density. Sure, it may be easy to manage and run a TG project, but > > it's a pain to set one up on a shared hosting server. > > Virtualization will solve that problem. > I can get PHP hosting for $10/year. Will I be able to get a virtual host for that? From nicolasg at gmail.com Tue Jul 24 06:57:55 2007 From: nicolasg at gmail.com (NicolasG) Date: Tue, 24 Jul 2007 10:57:55 -0000 Subject: Where do they tech Python officialy ? In-Reply-To: <7x8x96fa3q.fsf@ruckus.brouhaha.com> References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> <1185265091.276958.239910@r34g2000hsd.googlegroups.com> <7x8x96fa3q.fsf@ruckus.brouhaha.com> Message-ID: <1185274675.038893.71200@d55g2000hsg.googlegroups.com> > Why would you want to become a programmer? Programmers smell bad, > they have no social life, they get treated like crap by everyone. > They can get paid pretty well but then they spend all the money on > useless electronic junk so they still live like bums. I wouldn't call this person programmer , I would call him a geek ;) > one reason to be a programmer, which is that the drive to program > burns in you like a fire. But in that case don't ask how to become a > programmer, because you are already one, so welcome to the ranks ;-). Yes true , I'm already a programmer.. doing technical support for my company products in a call center. I hate my job, I hate the moment I have to wake up to go work ! I hate that moment I have to go sleep when I think of the next working day morning. 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 .. From solisgb at gmail.com Wed Jul 25 13:55:02 2007 From: solisgb at gmail.com (luis) Date: Wed, 25 Jul 2007 10:55:02 -0700 Subject: Windows error 126 loading a dll on windows 2000 Message-ID: <1185386102.634182.264810@b79g2000hse.googlegroups.com> Hi! I'm using ctypes with python 2.4 on windows xp the code if exists(join(getcwd(),'statistics.dll')): ...ap=windll.LoadLibrary(join(getcwd(),'statistics.dll')) works fine but on windows 2000, the some code raise the windows error 126, it can't load the module statistics.dll thanks in advance From nospam-abuse at ilyaz.org Tue Jul 10 21:58:57 2007 From: nospam-abuse at ilyaz.org (Ilya Zakharevich) Date: Wed, 11 Jul 2007 01:58:57 +0000 (UTC) Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <5fh0imF3cjte7U1@mid.individual.net> Message-ID: [A complimentary Cc of this posting was sent to Martin Gregorie ], who wrote in article : > >> If Stephen Hawking is right, the shape of the universe > >> is such that there isn't any time "before" the big bang > >> at all. It's like asking what's north of the North Pole. > > I do not remember any statement like this - even from 70s... Could > > you provide a reference? There were conjectures about "initial > > singularity", but I do not recollect them related to SH. > Its in "A Short History of Time". Sorry I can't quote chapter or page, > but a friend borrowed my copy and lent me Dawkins "Climbing Mount > Improbable" before vanishing, never to be seen since. Not an equal > exchange: I preferred ASHOT to CMI. I would prefer a reference to a peer-reviewed paper. ;-) Thanks, Ilya From thomas at jollans.com Sun Jul 1 14:03:04 2007 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 1 Jul 2007 20:03:04 +0200 Subject: How to uninstall packages In-Reply-To: References: Message-ID: <200707012003.05390.thomas@jollans.com> On Sunday 01 July 2007, Rustom Mody wrote: > I first installed the debian package python-pysqlite1.1 using > synaptic. Since this seemed too old for other packages (sqlalchemy) I > downloaded the sources pysqlite-2.3.4.tar.gz and ran setup install. I wonder why you chose not to use python-pysqlite2... From josiah.carlson at sbcglobal.net Tue Jul 17 12:13:25 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Tue, 17 Jul 2007 09:13:25 -0700 Subject: Implementaion of random.shuffle In-Reply-To: <1184654645.406393.43250@g12g2000prg.googlegroups.com> References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> <87d4ys9z46.fsf@mulj.homelinux.net> <1184654645.406393.43250@g12g2000prg.googlegroups.com> Message-ID: <0Q5ni.28576$C96.18680@newssvr23.news.prodigy.net> shabda raaj wrote: > The code for shuffle is > > if random is None: > random = self.random > for i in reversed(xrange(1, len(x))): > # pick an element in x[:i+1] with which to exchange x[i] > j = int(random() * (i+1)) > x[i], x[j] = x[j], x[i] > > With > j = int(random() * (i+1)) > being the only call to random(). > As long as (i + 1) is not large enough so that j is generated with > equal probability in range [0, i] we would get all permutations with > equal probability. With MT with period of 2**19937 (i+1) would have to > be really large before this the case. Be careful of assuming too much about permutations and randomness. In particular, you are assuming too much about what mersenne twister guarantees, what that implies regarding random permutations, and what a random permutation really is. In particular, if we merely enumerate all possible permutations of n elements, there are n! total permutations. Now, because the generation of a permutation *is fundamentally indistinguishable from choosing a number in the range [0...n!)*, then we can rely on the knowledge and research regarding the generation of such numbers. In particular, thanks to birthday collisions, you only need to generate O(sqrt(n!)) random permutations to have a 50% chance of having come upon a duplicate permutation. For example: >>> a = range(10) >>> b = {} >>> import random >>> while 1: ... x = a[:] ... random.shuffle(x) ... x = tuple(x) ... if x not in b: ... b[x] = None ... else: ... break ... >>> len(b) 3605 >>> x (4, 3, 9, 8, 0, 2, 1, 7, 6, 5) >>> x in b True >>> I only generated 3605 permutations of 10 items before I got a collision. According to your claims, I should have gone through all 3628800 possible permutations before that happened. Note that I could repeat this exercise with any decent pseudo random number generator, or actual random information generated from any good random source. As long as the PRNG doesn't suck, it should offer some variant of the above. > Anyway, is there some test harness we can run to test the robustness > of shuffle? We can run that test harness for large values and see at > what point all permutations are not possible or come with unequal > probability. Shuffle works as intended. Your assumptions about it's functionality are incorrect. Testing will only prove that your assumptions are wrong. - Josiah From skawanagi at gmail.com Tue Jul 17 07:09:35 2007 From: skawanagi at gmail.com (mosi) Date: Tue, 17 Jul 2007 11:09:35 -0000 Subject: a=0100; print a ; 64 how to reverse this? Message-ID: <1184670575.205759.115360@i13g2000prf.googlegroups.com> Problem: how to get binary from integer and vice versa? The simplest way I know is: a = 0100 a 64 but: a = 100 (I want binary number) does not work that way. a.__hex__ exists a.__oct__ exists but where is a.__bin__ ??? What`s the simplest way to do this? Thank you very much. From orsenthil at users.sourceforge.net Sun Jul 22 08:03:43 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Sun, 22 Jul 2007 17:33:43 +0530 Subject: importing a module from a specific directory In-Reply-To: References: Message-ID: <20070722120343.GA4759@gmail.com> > I would like to organize them into directory structure in > which there is a 'main' directory, and under it directories for > specific sub-tasks, or sub-experiments, I'm running (let's call them > 'A', 'B', 'C'). > Is there a neat clean way of achieving the code organization? > This is a kind of a frequently asked question at c.l.p and every programmer I guess has to go through this problem. If you look around c.l.p you will find that one of the good ways to solve this problem with the python interpretor <2.5 is: >>> import sys >>> sys.path.append(os.path.abspath(os.pardir)) But, if you are using Python 2.5, you are saved. Straight from the documentation: Starting with Python 2.5, in addition to the implicit relative imports described above, you can write explicit relative imports with the from module import name form of import statement. These explicit relative imports use leading dots to indicate the current and parent packages involved in the relative import. From the surround module for example, you might use: from . import echo from .. import Formats from ..Filters import equalizer HTH. -- O.R.Senthil Kumaran http://uthcode.sarovar.org From steve at holdenweb.com Tue Jul 24 14:10:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Jul 2007 14:10:12 -0400 Subject: code indentation In-Reply-To: <1185297657.186852.136950@k79g2000hse.googlegroups.com> References: <1185297657.186852.136950@k79g2000hse.googlegroups.com> Message-ID: vedrandekovic at v-programs.com wrote: > On 24 srp, 05:20, "Gabriel Genellina" wrote: >> En Mon, 23 Jul 2007 16:53:01 -0300, ...:::JA:::... >> escribi?: >> >> >> >>>> If you are using the tokenize module as suggested some time ago, try to >>>> analyze the token sequence you get using { } (or perhaps begin/end pairs >>>> in your own language, that are easier to distinguish from a dictionary >>>> display) and the sequence you get from the "real" python code. Then >>>> write >>>> a script to transform one into another: >>>> from tokenize import generate_tokens >>>> from token import tok_name >>> >from cStringIO import StringIO >>>> def analyze(source): >>> > g = generate_tokens(StringIO(source).readline) >>> > for toknum, tokval, _, _, _ in g: >>> > print tok_name[toknum], repr(tokval) >>>> I think you basically will have to ignore INDENT, DEDENT, and replace >>>> NAME+"begin" with INDENT, NAME+"end" with DEDENT. >>> So......how can I do this????????????? >>> I will appreciate any help!!!!! >> Try with a simple example. Let's say you want to convert this: >> >> for x in range(10): >> begin >> print x >> end >> >> into this: >> >> for x in range(10): >> print x >> >> Using the analyze() function above, the former block (pseudo-python) gives >> this sequence of tokens: >> >> NAME 'for' >> NAME 'x' >> NAME 'in' >> NAME 'range' >> OP '(' >> NUMBER '10' >> OP ')' >> OP ':' >> NEWLINE '\n' >> NAME 'begin' >> NEWLINE '\n' >> NAME 'print' >> NAME 'x' >> NEWLINE '\n' >> NAME 'end' >> ENDMARKER '' >> >> The latter block ("real" python) gives this sequence: >> >> NAME 'for' >> NAME 'x' >> NAME 'in' >> NAME 'range' >> OP '(' >> NUMBER '10' >> OP ')' >> OP ':' >> NEWLINE '\n' >> INDENT ' ' >> NAME 'print' >> NAME 'x' >> DEDENT '' >> ENDMARKER '' >> >> If you feed this token sequence into untokenize, in response you get a >> source code equivalent to the "real" python example above. So, to convert >> your "pseudo" python into the "real" python, it's enough to convert the >> first token sequence into the second - and from that, you can reconstruct >> the "real" python code. Converting from one sequence into the other is a >> programming exercise and has nothing to do with the details of the >> tokenize module, nor is very Python-specific - looking at both sequences >> you should figure out how to convert one into the other. (Hint: a few >> additional newlines are not important) >> >> It is even simpler than the example given in the tokenize documentation: >> - which transforms >> 3.1416 into Decimal("3.1416") by example. >> >> Once you get this simple case working, you may try what happens with this: >> >> for x in range(10): >> begin >> print x >> end >> >> and this: >> >> for x in range(10): begin >> print x >> end >> >> and later this: >> >> for x in range(10): >> begin >> print x >> end >> >> You are now using explicit begin/end pairs to group statements, so >> indentation is no more significant. You may want to preprocess the >> pseudo-python source, stripping any leading blanks, before using tokenize >> - else you'll get indentation errors (which are bogus in your >> pseudo-python dialect). >> >> Since this will be your own Python dialect, don't expect that someone else >> will do the work for you - you'll have to do it yourself. But it's not too >> dificult if you do the things in small steps. In case you get stuck at any >> stage and have specific questions feel free to ask. >> >> -- >> Gabriel Genellina > > Hello, > > Sorry, now I become very nuisance and stupid but please I really need > this.Do you remember my topic "python changing keywords name" ,and do > you remember example that you give me for translate keywords? Can you > give me some example script of this? Please!!! > > PS: THANKS FOR YOUR TIME!!!!!!!!!! I think you may have to accept that the task you have undertaken is, for the moment, beyond your capabilities. It's unfortunate that you are having difficulty with two languages simultaneously: your command of English, though impressive, appears to be insufficient for you to explain the problem in enough detail for someone else to solve it for you (even if someone should feel so generous). Your command of Python is not enough to solve it for yourself. Perhaps you should re-think your approach and consider that it may take you longer than you anticipated. 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 Jul 25 21:02:32 2007 From: zyzhu2000 at gmail.com (beginner) Date: Thu, 26 Jul 2007 01:02:32 -0000 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <5gpbfhF3gj6fdU1@mid.uni-berlin.de> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <5gpbfhF3gj6fdU1@mid.uni-berlin.de> Message-ID: <1185411752.637601.226960@e16g2000pri.googlegroups.com> > Not the most beautiful solution, but it works. > > Diez- Hide quoted text - > > - Show quoted text - Yeah it works! Thanks. From nis at superlativ.dk Thu Jul 5 15:43:42 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Thu, 05 Jul 2007 21:43:42 +0200 Subject: Where is the syntax for the dict() constructor ?! In-Reply-To: References: <468D1D9D.6060002@gmail.com> <468D3445.2060408@gmail.com> Message-ID: <468d49ff$0$90264$14726298@news.sunsite.dk> Neil Cerutti skrev: > Mostly you can use the default 'excel' dialect and be quite > happy, since Excel is the main reason anybody still cares about > this unecessarily hard to parse (it requires more than one > character of lookahead for no reason except bad design) data > format. I knew there had to be a reason why everyone is using xml these days ... Nis From whamil1 at entergy.com Thu Jul 5 08:48:39 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Thu, 5 Jul 2007 07:48:39 -0500 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xd4z837e2.fsf@ruckus.brouhaha.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CAD0@LITEXETSP001.etrsouth.corp.entergy.com> > From: Paul Rubin > > greg writes: > > > E.g. your program might pass its test and run properly for years > > > before some weird piece of input data causes some regexp to not quite > > > work. > > > > Then you get a bug report, you fix it, and you add a test > > for it so that particular bug can't happen again. > > Why on earth would anyone prefer taking a failure in the field over > having a static type check make that particular failure impossible? Because static typechecking won't make that particular failure "impossible," but instead just change it from a type error into a data error that may or may not be harder to identify. If your program gets a piece of data that breaks it, you'll get a failure in the field. Static typechecking won't prevent that. -- -Bill Hamilton From hniksic at xemacs.org Fri Jul 13 03:38:06 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 13 Jul 2007 09:38:06 +0200 Subject: How to create new files? References: <1184274877.612434.26870@k79g2000hse.googlegroups.com> Message-ID: <871wfc69ep.fsf@mulj.homelinux.net> Robert Dailey writes: > class filestream: > def __init__( self, filename ): > self.m_file = open( filename, "rwb" ) [...] > So far, I've found that unlike with the C++ version of fopen(), the > Python 'open()' call does not create the file for you when opened > using the mode 'w'. According to your code, you're not using 'w', you're using 'rwb'. In that respect Python's open behaves the same as C's fopen. > Also, you might notice that my "self.m_file.read()" function is wrong, > according to the python docs at least. read() takes the number of > bytes to read, however I was not able to find a C++ equivalent of > "sizeof()" in Python. If I wanted to read in a 1 byte, 2 byte, or 4 > byte value from data into python I have no idea how I would do this. Simply read as much data as you need. If you need to unpack external data into Python object and vice versa, look at the struct module (http://docs.python.org/lib/module-struct.html). From http Wed Jul 11 17:17:30 2007 From: http (Paul Rubin) Date: 11 Jul 2007 14:17:30 -0700 Subject: 2**2**2**2**2 wrong? Bug? References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> <1184173446.779276.250530@k79g2000hse.googlegroups.com> <1184182757.797808.206480@d55g2000hsg.googlegroups.com> Message-ID: <7xir8q63o5.fsf@ruckus.brouhaha.com> "Evan Klitzke" writes: > Python happens to choose right > associativity for exponentiation because it is more useful for that > operator, but that doesn't make the language itself right associative. I would say Python uses right associativity for exponentiation because that's standard mathematical convention, and any languages that do it differently (if they use operator precedence at all) get it wrong. From steve at holdenweb.com Wed Jul 25 12:18:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Jul 2007 12:18:22 -0400 Subject: 16-bit colour representation In-Reply-To: <5gp03nF3hl7siU1@mid.uni-berlin.de> References: <1185364424.797757.84620@22g2000hsm.googlegroups.com> <5gp03nF3hl7siU1@mid.uni-berlin.de> Message-ID: <46A777CE.4030607@holdenweb.com> Diez B. Roggisch wrote: > beertje wrote: > >> This has me a bit stumped... >> >> I'm trying to extract pictures from a file. So far I'm successfully >> retrieved the header and what I think is the colour for each pixel. >> Here's the description: >> >> """ >> 3) The picture data format: >> The color information is 15 bit data stored in 16 bit. This means the >> most >> significant bit is unused. The data is stored line for line in little >> endian Intel format starting with top left edge to bottom right edge. >> This >> is normally called chunky format. >> >> Bit 0.. 4 blue value >> Bit 5.. 9 green value >> Bit 10..14 red value >> """ >> >> So I've got a list of 16-bit numbers, but how to extract RGB info from >> those I'm a bit lost. I thought at first I should convert the decimal >> (say 23294) into a binary (say 0101101011111110) into something like >> this: >> blue: 01011 >> green: 01011 >> red: 11111 >> >> But encountered two problems: First, I don't know what the best way is >> to do this conversion, but more importantly I don't see how every >> colour could possibly be represented like this. 65535 is presumably >> white, but converting this into chunks of 5 gives me a 31, 31, 31, a >> dark shade of grey. >> >> I guess I'm on the wrong track completely? >> >> I'm a bit unsure about how to treat what the guide calls 'UWORD'... > > ANDing and SHIFTing are your friends here: > > v = 0x0bcd > b = v & 0xf > v >>= 4 > g = v & 0xf > v >>= 4 > r = v & 0xf > print r, g, b > > Alternatively, using 5-bit colors you would use b = v & 0x1f g = (v >> 5) & 0x1f r = (v >> 10) & 0x1f 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 jgodoy at gmail.com Sun Jul 22 22:42:08 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 22 Jul 2007 23:42:08 -0300 Subject: custom plugin architecture: how to see parent namespace? References: <1185113192.049692.258310@k79g2000hse.googlegroups.com> <1185148311.431968.148520@m3g2000hsh.googlegroups.com> <1185156202.232114.319300@n60g2000hse.googlegroups.com> Message-ID: escalation746 wrote: > I have updated documentation for this on my blog, diagrammes modernes. > Surf: > http://diagrammes-modernes.blogspot.com/ Your motivation looks a lot like what is solved by setuptools, eggs and entry points. http://peak.telecommunity.com/DevCenter/PkgResources http://docs.pythonweb.org/display/pylonscookbook/Using+Entry+Points+to+Write+Plugins From nitte.sudhir at gmail.com Thu Jul 5 02:54:41 2007 From: nitte.sudhir at gmail.com (kath) Date: Thu, 05 Jul 2007 06:54:41 -0000 Subject: ['a', 'b'][True] results 'b' But how? Message-ID: <1183618481.636297.96080@e9g2000prf.googlegroups.com> Hi, Can any one please tell me how is the following code is working? ['a','b'] is a list of string, and [True] is list of boolean value. How is it making effect....? >>> ['a','b] [True] 'b' >>> ['a','b'] [False] 'a' >>> ['a','b']['some_string' == r'some_string'] 'b' >>> ['a','b']['some_string' == r'somestring'] 'a' Thanks in advance, regards, kath. From kay.schluehr at gmx.net Fri Jul 20 02:56:41 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 19 Jul 2007 23:56:41 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <7x8x9lwka9.fsf@ruckus.brouhaha.com> Message-ID: <1184914601.872554.19720@n2g2000hse.googlegroups.com> On Jul 20, 6:45 am, John Nagle wrote: > Juergen Erhard wrote: > > On proving programs correct... from my CS study days I distinctly > > remember thinking "sure, you can prove it correct, but you cannot do > > actual useful stuff with it". We might have come a long way since > > then (late 80s :P), but I don't hold out much hope (especially since > > the halting problem does exist, and forever will). > > The halting problem only applies to systems with infinite memory. Sure. But knowing that memory is limited doesn't buy you much because you achieve an existential proof at best: you can show that the program must run out of memory but you have to run the program to know where this happens for arbitrary input values. Moreover you get always different values for different memory limits. So in the general case you can't improve over just letting the program run and notice what happens. From tjreedy at udel.edu Mon Jul 30 13:05:14 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 30 Jul 2007 13:05:14 -0400 Subject: Replacing overloaded functions with closures. References: <1185807536.021216.278500@22g2000hsm.googlegroups.com> <1185810128.237758.17550@k79g2000hse.googlegroups.com> Message-ID: "king kikapu" wrote in message news:1185810128.237758.17550 at k79g2000hse.googlegroups.com... | > def func(obj): | > if isinstance(obj, bool): | > return not obj | > elif isinstance(obj, int): | > return obj * 2 | > elif isinstance(obj, basestring): | > return obj + obj | > else: | > raise NotImplementedError('type %r not supported' % type(obj)) | | I have already come up with that solution but |...And get rid of the isinstance commands. A sometimes alternative is a dict (untested): func_switch = { bool: lambda o: not o, int: lambda i: i*2, str: lambda s: s+s, unicode: lambda s: s+s } def func(o): try: return func_switch[type(o)] except IndexError: raise NotImplementedError('type %r not supported' % type(obj)) but this does not work for instances of subclasses the way isinstance does. tjr From jwkenne at attglobal.net Mon Jul 2 12:27:37 2007 From: jwkenne at attglobal.net (John W. Kennedy) Date: Mon, 02 Jul 2007 12:27:37 -0400 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> Message-ID: Martin Gregorie wrote: > Roedy Green wrote: >> >> To add to the confusion you have GPS, Loran and Julian day also used >> as scientific times. > > > GPS time is UTC time No it isn't. GPS has never introduced a leap second, and is still on uncorrected UTC-as-of-1980. However, the GPS signal also includes an occasional UTC correction figure, so it can be used to obtain UTC. -- John W. Kennedy "The first effect of not believing in God is to believe in anything...." -- Emile Cammaerts, "The Laughing Prophet" From restycena at gmail.com Thu Jul 12 15:44:22 2007 From: restycena at gmail.com (kublai) Date: Thu, 12 Jul 2007 19:44:22 -0000 Subject: web page text extractor In-Reply-To: <469670CB.4020603@web.de> References: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> <469670CB.4020603@web.de> Message-ID: <1184269462.385477.254710@r34g2000hsd.googlegroups.com> On Jul 13, 2:19 am, Stefan Behnel wrote: > kublai wrote: > > For a project, I need to develop a corpus of online news stories. I'm > > looking for an application that, given the url of a web page, "copies" > > the rendered text of the web page (not the source HTNL text), opens a > > text editor (Notepad), and displays the copied text for the user to > > examine and save into a text file. Graphics and sidebars to be > > ignored. The examples I have come across are much too complex for me > > to customize for this simple job. Can anyone lead me to the right > > direction? > > Super-simplistic: > > >>> import lxml.etree as et > >>> parser = et.HTMLParser() > >>> tree = et.parse("http://the/page.html", parser) > >>> print tree.xpath("string(/html/body)") > > http://codespeak.net/lxml/ > > You may want to use the incredibly versatile "lxml.html.clean" module first to > remove any annoying content. It's not released yet but available in a branch: > > http://codespeak.net/svn/lxml/branch/html/ > > Stefan Hi, Stefan, This looks very interesting. I will look into this first thing tonight. Gotta hit some golf bugs, I mean, balls first. It's a beautiful afternoon here in Edmonton. Cheers, gk From stanc at al.com.au Tue Jul 31 23:50:03 2007 From: stanc at al.com.au (Astan Chee) Date: Wed, 01 Aug 2007 13:50:03 +1000 Subject: removing redundant elements in a dictionary Message-ID: <46B002EB.1080201@al.com.au> Hi, I have a dictionary which looks something like this: elem = {"co":[1,2,3],"cp":[3,2,1],"pp":[5,6,7],"cl":[1,2,3],"qw":[6,7,8],"qa":[8,7,6]} what Im trying to do is find all keys in the list that have the same value and delete those (except one); thereby removing all redundant keys so that the above dict will look like this: elem = {"co":[1,2,3],"pp":[5,6,7],"qa":[8,7,6]} my code so far looks like this: for out1 in elem.keys(): for out2 in elem.keys(): if out1 != out2: elem[out1].sort() elem[out2].sort() if elem[out1] == elem[out2]: del elem[out1] This returns in a KeyError exception when sorting. What am I missing here? Thanks Astan -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sun Jul 1 03:06:38 2007 From: http (Paul Rubin) Date: 01 Jul 2007 00:06:38 -0700 Subject: Python's "only one way to do it" philosophy isn't good? References: <1182750077.570603.160240@q69g2000hsb.googlegroups.com> <7xir9cbm0g.fsf@ruckus.brouhaha.com> <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1182872972.417776.78650@o11g2000prd.googlegroups.com> <1182873568.454491.302860@e9g2000prf.googlegroups.com> <7xps3iy73h.fsf@ruckus.brouhaha.com> <7x1wfudtw9.fsf@ruckus.brouhaha.com> <7x8xa1pbg8.fsf@ruckus.brouhaha.com> <7xhcopnvcg.fsf@ruckus.brouhaha.com> Message-ID: <7x4pkozjpd.fsf@ruckus.brouhaha.com> Douglas Alan writes: > > Haskell and ML are both evaluate typed lambda calculus unlike Lisp > > which is based on untyped lambda calculus. Certainly the most > > familiar features of Lisp (dynamic typing, S-expression syntax, > > programs as data (Lisp's macro system results from this)) are absent > > from Haskell and ML. > > And that is supposed to make them better and more flexible??? Well no, by itself the absence of those Lisp characteristics mainly means it's a pretty far stretch to say that Haskell and ML are Lisp dialects. > The ideal language of the future will have *optional* manifest > typing along with type-inference, and will have some sort of pramgma > to turn on warnings when variables are forced to become dynamic due > to there not being enough type information to infer the type. But > it will still allow programming with dynamic typing when that is > necessary. If I understand correctly, in Haskell these are called existential types: http://haskell.org/hawiki/ExistentialTypes > The last time I looked at Haskell, it was still in the stage of being > a language that only an academic could love. I used to hear the same thing said about Lisp. > > Haskell's type system lets it do stuff that Lisp can't approach. > > What kind of stuff? Compile-time polymorphism is cool for efficiency > and type safety, but doesn't actually provide you with any extra > functionality that I'm aware of. For example, it can guarantee referential transparency of functions that don't live in certain monads. E.g. if a function takes an integer arg and returns an integer (f :: Integer -> Integer), the type system guarantees that computing f has no side effects (it doesn't mutate arrays, doesn't open network sockets, doesn't print messages, etc). That is very helpful for concurrency, see the paper "Composable Memory Transactions" linked from here: http://research.microsoft.com/Users/simonpj/papers/stm/index.htm other stuff there is interesting too. > Where do you get this idea that the Lisp world does not get such > things as parallelism? StarLisp was designed for the Connection > Machine... Many parallel programs have been written in Lisp and *Lisp, and similarly in C, C++, Java, and Python, through careful use of manually placed synchronization primitives, just as many programs using dynamic memory allocation have been written in C with manual use of malloc and free. This presentation shows some stuff happening in Haskell that sounds almost as cool as bringing garbage collection to the malloc/free era: http://research.microsoft.com/~simonpj/papers/ndp/NdpSlides.pdf As for where languages are going, I think I already mentioned Tim Sweeney's presentation on "The Next Mainstream Programming Language": http://www.st.cs.uni-sb.de/edu/seminare/2005/advanced-fp/docs/sweeny.pdf It's not Haskell, but its type system is even more advanced than Haskell's. From tenax.raccoon at gmail.com Tue Jul 24 14:01:19 2007 From: tenax.raccoon at gmail.com (Jason) Date: Tue, 24 Jul 2007 11:01:19 -0700 Subject: wxPython - How to add sorting to a ListCtrl? In-Reply-To: <1185294074.410142.214140@22g2000hsm.googlegroups.com> References: <1185294074.410142.214140@22g2000hsm.googlegroups.com> Message-ID: <1185300079.930984.92640@22g2000hsm.googlegroups.com> On Jul 24, 10:21 am, Robert Dailey wrote: > Hi, > > I have 3 columns in my list control, each with a different "type" of > data (for example, one column has names, the other has dates, etc). > Can anyone reference a tutorial for solving this issue? I've done my > share of googling to no avail. I need the user to be able to click any > of the column headers and sort the rows of data by that column in > ascending or descending order. > > Thanks for your time. You probably want to post these questions to the wxPython forums. Still, take a look at the wxPython demo [1]. Under the "Core Windows/ Controls" category, the ListCtrl demo does exactly what you describe. They have code and comments built into the demo itself. [1] http://www.wxpython.org/download.php --Jason From wbrehaut at mcsnet.ca Sun Jul 15 15:05:38 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Sun, 15 Jul 2007 13:05:38 -0600 Subject: Can a low-level programmer learn OOP? References: <4697d9f0$0$7614$426a74cc@news.free.fr> <1184485640.495801.194200@z28g2000prd.googlegroups.com> Message-ID: On Sun, 15 Jul 2007 07:47:20 -0000, bonnie at macbird.com wrote: >On Jul 13, 3:20 pm, Wayne Brehaut wrote: >> On Sat, 14 Jul 2007 06:01:56 +0200, Bruno Desthuilliers >> >> wrote: >> >Chris Carlen a ?crit : >> >> Hi: >> >> >> From what I've read of OOP, I don't get it. I have also found some >> >> articles profoundly critical of OOP. I tend to relate to these articles. >> >> === 8< === === 8< === >> Under a claim of Academic Impunity (or was that "Immunity"), here's >> another historical tid-bit. In a previous empolyment we once had a >> faculty applicant from CalTech who knew we were using Simula as our >> introductory and core language in our CS program, so he visited Xerox >> PARC before coming for his inteview. His estimate ofAlan Kayand >> Smalltalk at that time (early 80s) was that "They wanted to implement >> Simula but didn't understand it--so they invented Smalltalk and now >> don't understand _it_!" >> >> wwwayne >> >> === 8< === > >A couple of notes on this post. > >Alan Kay has always publicly credited Simula as the direct inspiration >for Smalltalk, and if you know the man and his work, this implication >of taking credit for the first OOP language is not true, it is a >credit assigned to him by others, and one which he usually rights when >confronted with it. I know this, and was perhaps a little too flippant in my all-inclusive statement "self-serving propaganda from Xerox PARC,Alan Kay, and Smalltalk adherents everywhere!", for which I apologize. But it was made with humorous intent, as I had hoped the opening "Oh you young'uns, not versed in The Ancient Lore, but filled with self-serving propaganda..." would imply. A more accurate and unhumorous statement of my opinion is that it is Smalltalk adherents who know virtually nothing of the history of OOP--and even some who do--who did and still do make such claims, both personally and in the published literature of OOP. And my statement about a prospective faculty member's opinion was just that: a historical anecdote, and the expression of an early 80s opinion by a professional CS professor and researcher in formal semantics (which may have been part of his distrust of the Smalltalk team's "understanding" of Smalltalk) . The opinion he expressed was his and not my own, and I was just recording (what I thought might be) an amusing anecdote in a context in which I thought it appropriate: discussion of what OOP is, and after Bruno made the claim: "OO is about machines - at least as conceveid by Alan Key, who invented the term and most of the concept." I don't think my recording it here should be construed as my opinion of either Smalltalk or its creators (at that time or now). As often happens in many arenas, the creator of an idea can lose control to the flock, and many publications can get accepted if referrees themselves don't know the facts or take care to check them before recommending publication--which probably explains why so many publications (especially in conference proceedings) on OOP in the 80s and 90s completely omitted any mention of Simula: so much so that I once intended writing a paper on "Ignorance of Simula Considered Harmful." On the other hand, anytyhing you may have inferred about my distaste for those who doesn't bother to learn anything of the history of a subject, then make false or misleading claims, and don't bother to correct themselves when questioned, is true. >You may be confused with the fact that "object oriented >programming"was a term which I believe was first used by Alan and his >group at PARC, so perhaps the coining of the term is what is being >referenced by others. No, I have been at more than one CS (or related area) conference where a Smalltalk aficionado has stated unequivocally that Kay invented OOP and that Smalltalk was the first OOPL. The last I recall for sure was WebNet 2000, where a (quite young) presenter on Squeak made that statement, and was not at all certain what Simula was when I asked whether it might actually have been the first more than 10 years before Smalltalk 80. So his claim, and that of many others, explicitly or implicitly, is that not only the term, but most (or all) of the concept, and (often) the first implementation of OOP was by Kay and his Xerox PARC team in Smalltalk 80. >Perhaps I'm mistaken, but the tone of your post conveys an animosity >that did not exist between the original Smalltalk and Simula >inventors; Nygard and Kay were good friends, and admired each others' >work very much. Yes, you are very much mistaken (as I note above), and appear not to have understood the intended humorous tone of my posting. wwwayne > >Bonnie MacBird > From stars at MIT.EDU Tue Jul 31 01:06:07 2007 From: stars at MIT.EDU (Star) Date: Tue, 31 Jul 2007 01:06:07 -0400 (EDT) Subject: Where do they tech Python officialy ? In-Reply-To: <46ae3dc8$0$634$426a34cc@news.free.fr> References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> <46ae3dc8$0$634$426a34cc@news.free.fr> Message-ID: MIT's freshman survey, EECS 1 is taught in Python and Scheme, soon to be just Python. -Star On Wed, 25 Jul 2007, Bruno Desthuilliers wrote: > Omari Norman a ?crit : >> On Mon, Jul 23, 2007 at 10:48:10PM -0700, Paul Rubin wrote: >> >> >>> If you're having trouble with Python because you're new at >>> programming, I can sympathize--I don't think it's the most >>> beginner-friendly of languages despite the efforts in that direction >>> by the designers. >> >> >> Just curious--what language would you recommend as most >> beginner-friendly? > > C ?-) > > (sorry, just kidding.) > >> My previous programming experience was with BASIC--and I think it is >> true that BASIC will, in many ways, rot your brain. > > So will Java. > > I learned programming with Hypertalk (MacIntosh's Hypercard scripting > language, which more or less gave birth to AppleTalk), then RealBasic > (Mac's Better VB-like), then VB, then Java, then C, then bits of Pascal, > then Python, and this is where I started to see the light. But I had > hard time unlearning all those java-ish anal-retentive stupidities and > arbitrary overcomplexifications before I really enjoyed Python. Playing > with Lisp (Common Lisp and Scheme) and Smalltalk helped getting rid of > mental pollution wrt/ declarative static typing. To be honest, playing > with Haskell and O'Caml also helped me understanding that static typing > is not necessarily bad by itself. > >> I had used QBasic >> and, later, a little VBA and some PHP. It took some time to unlearn some >> bad things (object orientation in VBA seems to be mostly a hack, for >> example, while PHP seems to be a big hack generally) > > Well... this is not exactly a scoop !-) > >> but it seems to me >> that Python helped me learn my first modern programming language. >> >> >>> I think Python is not used in university programs very much. Look for >>> one that uses SICP (Scheme) or CTM (Mozart/Oz) or a functional >>> language like Haskell, in preference to the ones that use Java (the >>> Cobol of the 1990's). With some reasonable experience in Scheme or >>> Mozart or Haskell, plus a Python manual, you'll be well on your way. >> >> >> I had heard of these languages, but learning them is a bit discouraging >> because (Java excepted) they don't seem to get much practical use. > > Before considering practical use (FWIW, Python was pretty far from > mainstream 7 year ago), you should ask yourself how learning one of > these languages will affect the way you thing about programming. While > mostly in the imperative/OO camp, Python stole quite a lot from > functional languages, and this is obviously a GoodThing(tm). > > My 2 cents > -- > http://mail.python.org/mailman/listinfo/python-list > From the.mindstorm.mailinglist at gmail.com Sun Jul 15 17:49:35 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Sun, 15 Jul 2007 14:49:35 -0700 Subject: Circular import problem In-Reply-To: References: <1184294176.550267.119980@n60g2000hse.googlegroups.com> <1184343897.111992.107880@g4g2000hsf.googlegroups.com> <1184500194.909470.178430@w3g2000hsg.googlegroups.com> Message-ID: <1184536175.985742.112770@r34g2000hsd.googlegroups.com> On Jul 15, 10:08 pm, "Gabriel Genellina" wrote: > En Sun, 15 Jul 2007 08:49:54 -0300, Alex Popescu > escribi?: > > > > >> > But, I still don't understand how python can access a function in a > >> > file I have NOT included. In this case, to get things to work, I DO > >> > NOT "import MMA.grooves" but later in the module I access a function > >> > with "xx=MMA.grooves.somefunc()" and it finds the function, and works > >> > just fine. It shouldn't work. > > >> That depends a bit on what is "MMA" and what is "grooves". > >> MMA.grooves means "look for an attribute named grooves inside MMA". If > >> MMA > >> is a module, and MMA.grooves is a class/function defined inside the > >> module, you don't need to import it before using it. > > > I am a bit confused: I think the above should be: > > > if MMA.grooves in a class/function defined inside the module MMA, you > > don't need to import the > > class/function before using it, but only import the module MMA. > > > Am I wrong? > > You are right, but we were talking about a slightly different scenario. To > make things clear: > > 1) > import MMA > xx=MMA.grooves.somefunc() > > 2) > import MMA.grooves > xx=MMA.grooves.somefunc() > > If MMA is a module, containing a class named gooves, those two ways are > valid. > If MMA is a package, and grooves is a module contained in the package, > only the second one is valid (assuming the package has an empty > __init__.py, or does not import grooves itself) > > The OP was asking why the second form worked fine for him for a while, but > stopped working after reordering some imports. And the answer (according > to "Greg") is: some other module imported MMA.grooves, and that put > grooves into MMA namespace, available for everyone else. > > -- > Gabriel Genellina Now, everything is 100% clear. bests, ./alex -- .w( the_mindstorm )p. From stefan.behnel-n05pAM at web.de Fri Jul 13 05:01:49 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 13 Jul 2007 11:01:49 +0200 Subject: Question about PyDict_SetItemString In-Reply-To: <1184311267.876950.150040@e16g2000pri.googlegroups.com> References: <1184311267.876950.150040@e16g2000pri.googlegroups.com> Message-ID: <46973F7D.80105@web.de> lgx schrieb: > Does PyDict_SetItemString(pDict,"key",PyString_FromString("value")) > cause memory leak? > >>From Google results, I find some source code write like that. But some > code write like below: > > obj = PyString_FromString("value"); > PyDict_SetItemString(pDict,"key",obj); > Py_DECREF(obj); Sorry, my previous response came from the completely wrong bag. The second is right. PyString_FromString() increases the refcount of the returned string, so you have to decref it after use. PyDict_SetItemString() does its own refcount increase internally when it stores the value, so don't bother about it at all when you think about what refcounts you have to increase or decrease. Stefan From bbxx789_05ss at yahoo.com Sun Jul 29 12:28:25 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 29 Jul 2007 09:28:25 -0700 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1185703671.241103.124780@g12g2000prg.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> <1184458002.961657.267830@x35g2000prf.googlegroups.com> <1184466882.446791.127670@x35g2000prf.googlegroups.com> <1185658013.859359.47700@57g2000hsv.googlegroups.com> <1185703671.241103.124780@g12g2000prg.googlegroups.com> Message-ID: <1185726505.609135.146410@d55g2000hsg.googlegroups.com> On Jul 29, 4:07 am, Graham Dumpleton wrote: > > Any ideas what went wrong? > > Have you got an appropriate LoadModule directive in Apache > configuration to load the mod_python module? That you get this error > is indicative of mod_python module not being loaded. > I checked and I don't have a LoadModule directive for mod_python in / Library/Apache2/conf/httpd.conf. But I can't find a file called mod_python.so anywhere on my computer, so I don't know what path to use. > You can check the > Apache error logs to see if mod_python got loaded. > I checked both these error logs: /Library/Apache2/logs/error_log /Library/Apache2/logs/access_log and there is no entry for yesterday when I tried to start Apache after my mod_python install. I assume that was because Apache never started up? From zyzhu2000 at gmail.com Fri Jul 27 17:18:56 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 27 Jul 2007 21:18:56 -0000 Subject: Another C API Question In-Reply-To: References: <1185498383.333248.225360@19g2000hsx.googlegroups.com> <1185545488.751250.200270@z24g2000prh.googlegroups.com> Message-ID: <1185571136.628131.168260@z24g2000prh.googlegroups.com> On Jul 27, 11:37 am, Farshid Lashkari wrote: > beginner wrote: > > This works with PyFloat only. It does not work with integers. > > Did you try it out? I have used it on ints, bools, and objects that > implement the __float__ method. It does not work on strings though. I did and it did not seem to work. I ended up doing the following. Verbose, isn't it? If I do d=PyFloat_AsDouble(oDiscount); in the third "if", I get an error. Maybe I missed something obvious. if(oDiscount==Py_None) { } else if(PyFloat_Check(oDiscount)) { d=PyFloat_AsDouble(oDiscount); } else if(PyNumber_Check(oDiscount)) { PyObject *pf=PyNumber_Float(oDiscount); if(pfDiscount) { d=PyFloat_AsDouble(pfDiscount); Py_DECREF(pfDiscount); } } else ... From steve at REMOVE.THIS.cybersource.com.au Wed Jul 25 21:12:01 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 26 Jul 2007 11:12:01 +1000 Subject: classmethod & staticmethod References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> <46a5b2ad$0$18903$426a74cc@news.free.fr> Message-ID: On Wed, 25 Jul 2007 00:55:17 +0000, Alex Popescu wrote: > Neil Cerutti wrote in news:eRwpi.36813$G23.28496 > @newsreading01.news.tds.net: > >> On 2007-07-25, Alex Popescu wrote: >>> As a matter of style, how do you figure out that class_list is >>> a class attribute and not an instance attribute? (I don't >>> remember seeing anything in the PEP describing the coding >>> style). >> >> Check out dir(MyClass) and dir(MyClass()) for some insight, if it >> turns out that it matters. > > I must confess that I am a bit confused by this advise, as both are > returning exactly the same thing. > >> Preferably, the user of a class >> doesn't have to really think about it much. >> > I know that this would be prefered, but in case you are getting 3rd party > code and you modify a class attribute without knowing it is a class > attribute then you may get into trouble (indeed the real problem is with > the designer of the 3rd party code, but still I think it is a valid > concern). # warning: doesn't consider slots if "attribute" in instance.__dict__: print "instance attribute" elif "attribute" in instance.__class__.__dict__: print "class attribute" else: print "either no attribute at all, or in a parent class" -- Steven. From noamtm at gmail.com Wed Jul 4 08:25:01 2007 From: noamtm at gmail.com (noamtm) Date: Wed, 04 Jul 2007 05:25:01 -0700 Subject: ignoring a part of returned tuples In-Reply-To: <468b5a9d$0$2228$426a74cc@news.free.fr> References: <1183536536.324939.236910@c77g2000hse.googlegroups.com> <468b5a9d$0$2228$426a74cc@news.free.fr> Message-ID: <1183551901.590528.225940@n2g2000hse.googlegroups.com> On Jul 4, 11:29 am, Bruno Desthuilliers wrote: > A common idiom is to use '_' for unused values, ie: > > for (dirpath, _, filenames) in os.walk(...): That's what I need - this avoids PyLint telling me that I have an unused variable, and also makes it clear that this value is not used. Thanks! From gagsl-py2 at yahoo.com.ar Tue Jul 24 21:28:43 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Jul 2007 22:28:43 -0300 Subject: exec and func_code References: <1185298743.3370.25.camel@dot.uniqsys.com> Message-ID: En Tue, 24 Jul 2007 14:55:43 -0300, Prepscius, Colin (IT) escribi?: > Actually, thx to Gabrielle Genellina, who wrote earlier: Ehmm... my name is actually Gabriel, and last time I checked, I was a male :) -- Gabriel Genellina From godzillaismad at gmail.com Thu Jul 12 18:34:27 2007 From: godzillaismad at gmail.com (Godzilla) Date: Thu, 12 Jul 2007 15:34:27 -0700 Subject: Fastest way to convert a byte of integer into a list Message-ID: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> Hello, I'm trying to find a way to convert an integer (8-bits long for starters) and converting them to a list, e.g.: num = 255 numList = [1,1,1,1,1,1,1,1] with the first element of the list being the least significant, so that i can keep appending to that list without having to worry about the size of the integer. I need to do this because some of the function call can return a 2 lots of 32-bit numbers. I have to find a way to transport this in a list... or is there a better way? From cfpete at gmail.com Mon Jul 16 23:19:34 2007 From: cfpete at gmail.com (cfpete at gmail.com) Date: Tue, 17 Jul 2007 03:19:34 -0000 Subject: how to compile python to have gtk and Tkinter modules in Linux environment. Message-ID: <1184642374.154463.277180@g37g2000prf.googlegroups.com> Hello, How do I go about to have python compiled from source so that I can import gtk and Tkinter modules. Those don't seem to be included when I use the default ./configure or python setup.py. Thanks in advance, -Peter From jstroud at mbi.ucla.edu Fri Jul 13 15:34:47 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 13 Jul 2007 12:34:47 -0700 Subject: Pass by reference or by value? In-Reply-To: <1184354563.861992.119070@22g2000hsm.googlegroups.com> References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> <1184354563.861992.119070@22g2000hsm.googlegroups.com> Message-ID: Robert Dailey wrote: > I actually want to know how to "pass by > reference", in that any changes made to a parameter inside of a > function also changes the variable passed in. Pass a mutable type. py> class C(object): ... def __repr__(self): ... return str(self.value) ... def __init__(self, v): ... self.value = v ... py> c = C(4) py> c 4 py> def doit(v): ... v.value = v.value * 2 ... py> doit(c) py> c 8 James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From ironfroggy at gmail.com Sun Jul 22 14:34:54 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Sun, 22 Jul 2007 14:34:54 -0400 Subject: Where is the collections module? In-Reply-To: References: Message-ID: <76fd5acf0707221134n11b32baeo2626cc1b33761341@mail.gmail.com> Look in Modules/_collectionsmodule.c Pretty much any built-in module will be named thusly. On 7/22/07, Gordon Airporte wrote: > I was going to try tweaking defaultdict, but I can't for the life of me > find where the collections module or its structures are defined. Python 2.5. > -- > http://mail.python.org/mailman/listinfo/python-list > -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From metalheart at hot.ee Thu Jul 12 19:06:23 2007 From: metalheart at hot.ee (Raul Laansoo) Date: Fri, 13 Jul 2007 02:06:23 +0300 Subject: Screen Scraping Question In-Reply-To: <1184157921.488811.295570@n60g2000hse.googlegroups.com> References: <1184157921.488811.295570@n60g2000hse.googlegroups.com> Message-ID: <1184281583.22541.7.camel@metalheart> ?hel kenal p?eval, K, 2007-07-11 kell 12:45, kirjutas jeffbg123: > Hey, > > I am trying to make a bot for a flash game using python. However I am > having some trouble with a screen scraping strategy. Is there an > accepted way to compare a full screenshot with the image that I want > to locate? It is a math based game, so I just have to check what > number, 1-9, appears in the center of the flash game. Is there an > easier method to do this? > > Thanks > > -Jeff > Maybe you can compare screenshots by the size, if they vary. Raul From jstroud at mbi.ucla.edu Wed Jul 25 12:49:22 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 25 Jul 2007 16:49:22 GMT Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <1185378418.100041.38560@w3g2000hsg.googlegroups.com> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> Message-ID: beginner wrote: > On Jul 25, 10:19 am, Stargaming wrote: >> On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote: >>> Hi, >>> I am wondering how do I 'flatten' a list or a tuple? For example, I'd >>> like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4]. >> A recursive function, always yielding the first element of the list, >> could do the job. See the ASPN Python Cookbook for a few implementations.http://aspn.activestate.com/ASPN/search? >> query=flatten§ion=PYTHONCKBK&type=Subsection >> >>> Another question is how do I pass a tuple or list of all the aurgements >>> of a function to the function. For example, I have all the arguments of >>> a function in a tuple a=(1,2,3). Then I want to pass each item in the >>> tuple to a function f so that I make a function call f(1,2,3). In perl >>> it is a given, but in python, I haven't figured out a way to do it. >>> (Maybe apply? but it is deprecated?) >>>>> def foo(a, b, c): print a, b, c >> ... >>>>> t = (1, 2, 3) >>>>> foo(*t) >> 1 2 3 >> >> Have a look at the official tutorial, 4.7.4http://www.python.org/doc/ >> current/tut/node6.html#SECTION006740000000000000000 >> >>> Thanks, >>> cg >> HTH, >> Stargaming > > Hi Stargaming, > > I know the * operator. However, a 'partial unpack' does not seem to > work. > > def g(): > return (1,2) > > def f(a,b,c): > return a+b+c > > f(*g(),10) will return an error. > > Do you know how to get that to work? > > Thanks, > cg > > Were this not hypothetical, I would make use of the commutative property of addition: f(10, *g()) Proof: 1+2+10 = 10+1+2 Also, this has not been suggested: py> def g(): ... return (1,2) ... py> def f(a,b,c): ... return a+b+c ... py> f(c=10, *g()) 13 James From steve at REMOVE.THIS.cybersource.com.au Wed Jul 11 21:47:27 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 12 Jul 2007 11:47:27 +1000 Subject: bool behavior in Python 3000? References: <5ficp9F3cram2U2@mid.individual.net> <469472f4$0$1293$9b622d9e@news.freenet.de> Message-ID: On Wed, 11 Jul 2007 08:04:33 +0200, Stargaming wrote: > No, I think Bjoern just wanted to point out that all those binary > boolean operators already work *perfectly*. You just have to emphasize > that you're doing boolean algebra there, using `bool()`. > "Explicit is better than implicit." So we should always write things explicitly like: if bool(bool(some_condition) is True) is True: first_line = str(some_string).split(str("\n"))[int(0)] n = int(int(len(list(some_list))) + int(1)) elif bool(bool(some_condition) is False) is True: f = float(math.sin(float(6.0)/float(math.pi))) instead of the less explicit code. I'll try to remember that, thank you for the advice. -- Steven From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jul 16 04:25:10 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 16 Jul 2007 10:25:10 +0200 Subject: running a Delphi part from Python ? In-Reply-To: <889c1$469b275c$d443bb3a$2876@news.speedlinq.nl> References: <889c1$469b275c$d443bb3a$2876@news.speedlinq.nl> Message-ID: <469b2b65$0$21672$426a74cc@news.free.fr> Stef Mientki a ?crit : > > I'm starting to get used to wxPython (coming from Delphi), > and it seems it can do almost everything I need. > > Now one thing I'm missing is a good RichEditor. Scintilla is for you, then. IIRC, there's a wxWidget widget embedding it, and quite a few editors using it. From leena_kirank at yahoo.com Thu Jul 19 03:17:29 2007 From: leena_kirank at yahoo.com (Kan) Date: Thu, 19 Jul 2007 00:17:29 -0700 Subject: Direct Client-Web Designer/Web Architect-Bay Area,CA Message-ID: <1184829449.166442.136360@g12g2000prg.googlegroups.com> Hello, We have requirement for Web Designer/Web Architect in bay area CA. The person needs to have experience in building Commerce Site where Actual Shopping has been done. If your skills and experience matches with the same, send me your resume asap with contact # and rate to 'kanchan at tbiinc.org'. Title = Contract Information Architect/User Experience Designer 6 month contract Location: Redwood city Requirements: The person needs to have experience in building Commerce Site where Actual Shopping has been done Strong knowledge of site design; mastery in principles of Web design (HCI, HTML, CSS) Strong knowledge of user interface design processes and methodology Working knowledge of User Centered Design Principles and Practices Knowledge of architecture-related software (Illustrator, Visio, Photoshop, SQL Server, MS Office, Acrobat, Dreamweaver) Strong Preference given to those with:: Experience with digital media commerce sites Kan BTech Inc Recruiter 510-438-6834 kanchan at tbiinc.org www.tbiinc.org From steve at REMOVE.THIS.cybersource.com.au Sat Jul 28 02:17:40 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Jul 2007 16:17:40 +1000 Subject: Relative-importing * References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> <871weth2gg.fsf@benfinney.id.au> Message-ID: On Sat, 28 Jul 2007 09:05:51 +1000, Ben Finney wrote: > rbygscrsepda at gmail.com writes: > >> from . import * >> from .sibiling import * >> from .. import * >> from ..parent_sibling import * >> >> ...and so on. The same error occurs: >> SyntaxError: 'import *' not allowed with 'from .' > > Interesting. I know that 'from foo import *' is frowned on Well, it is discouraged, unless it is the right thing to do, in which case it is encouraged. It's only frowned upon when it is the wrong thing to do. And later, Ben continued: > While waiting, you should take it as an opportunity to remove the > blight of "from foo import *". All imports should explicitly import > names, not implicitly clobber the current namespace with whatever pops > out. That word you use, implicit -- I do not think it means what you think it means. I read "from module import *" as explicitly saying "clobber the current namespace with whatever names module exports". That's what from does: it imports names into the current namespace. It isn't some sort of easy to miss side-effect. If a name already existed, it gets clobbered, just like any other import: >>> math = 45 >>> import math # clobber any existing name 'math' >>> math I do take your point that importing * has the potential to unexpectedly clobber names you didn't intend, and that's a good reason to avoid it unless you have a good reason to use it. But there are good reasons. The "from module import *" statement is very useful if you wish to export all the public objects from a "private" module, e.g. emulate what the os module does with platform specific functions. It is an excellent way of reducing the amount of duplicated data that needs to be maintained in multiple places. E.g. instead of: # export some public functions, which are defined differently at # run-time, but must all exist if lights_are_green: from green_module import (dead_parrot, spanish_inquisition, knights_who_say_ni, wafer_thin_mints) else: from red_module import (dead_parrot, spanish_inquisition, knights_who_say_ni, wafer_thin_mints) you can Do The Right Thing with: if lights_are_green: from green_module import * else: from red_module import * and so long as green_module and red_module also Do The Right Thing it will Just Work. Indeed, sub-modules can add extra functions to their public API, and you don't need to do anything to support them: it also Just Works. Python has a mechanism for making it work: modules can define what their public API is, thus avoiding the possibility of exporting things you didn't intend to. __all__ = ["dead_parrot", "spanish_inquisition", "knights_who_say_ni", "wafer_thin_mints", "ethel_the_aardvark"] (Naturally, if the modules' __all__ doesn't match the API you are expecting from the documentation, strange and terrible things might occur; but importing _anything_ from a broken module may do strange and terrible things.) I certainly agree that "from module import *" is easily abused, but to go from there to the conclusion that it is a blight that must be stamped out is far too strong. But back to the relative imports... I've spent some time reading the documentation, and googling, and I can't find any clue why importing * from a package is prohibited. I do know that it is prohibited inside a function or method (and rightly so!). -- Steven. From stargaming at gmail.com Wed Jul 25 12:23:04 2007 From: stargaming at gmail.com (Stargaming) Date: 25 Jul 2007 16:23:04 GMT Subject: Flatten a list/tuple and Call a function with tuples References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> Message-ID: <46a778e8$0$8323$9b622d9e@news.freenet.de> On Wed, 25 Jul 2007 15:46:58 +0000, beginner wrote: > On Jul 25, 10:19 am, Stargaming wrote: >> On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote: [snip] >> >> > Another question is how do I pass a tuple or list of all the >> > aurgements of a function to the function. For example, I have all the >> > arguments of a function in a tuple a=(1,2,3). Then I want to pass >> > each item in the tuple to a function f so that I make a function call >> > f(1,2,3). In perl it is a given, but in python, I haven't figured out >> > a way to do it. (Maybe apply? but it is deprecated?) >> >>> def foo(a, b, c): print a, b, c >> ... >> >>> t = (1, 2, 3) >> >>> foo(*t) >> >> 1 2 3 >> >> Have a look at the official tutorial, 4.7.4http://www.python.org/doc/ >> current/tut/node6.html#SECTION006740000000000000000 >> >> > Thanks, >> > cg >> >> HTH, >> Stargaming > > Hi Stargaming, > > I know the * operator. However, a 'partial unpack' does not seem to > work. > > def g(): > return (1,2) > > def f(a,b,c): > return a+b+c > > f(*g(),10) will return an error. http://docs.python.org/ref/calls.html > Do you know how to get that to work? Well, there are several ways to solve this. You could either invoke f(*g () + (10,)). Might be a bit nasty and unreadable, though. Or you could just change your function f to accept them in reversed order (f(10, *g) should work) or convert g() to return a dictionary like {'b': 1, 'c': 2} and use f(10, **g). But if your function f's hugest use case is being called with g(), changing f to accept something and g's result (tuple) -- unpacking it inside f -- might be better. From http Fri Jul 13 03:57:10 2007 From: http (Paul Rubin) Date: 13 Jul 2007 00:57:10 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <87zm20iw3e.fsf@benfinney.id.au> Message-ID: <7x1wfcviqx.fsf@ruckus.brouhaha.com> Ben Finney writes: > This is interesting. Do you have any references we can read about this > assertion -- specifically, that "GOTO" was not well loved (I assume > "by the programming community at large") even by around 1966? Dijkstra's famous 1968 "GOTO considered harmful" letter (http://www.acm.org/classics/oct95/) quotes a 1966 article by N. Wirth and C.A.R. Hoare: The remark about the undesirability of the go to statement is far from new. I remember having read the explicit recommendation to restrict the use of the go to statement to alarm exits, but I have not been able to trace it; presumably, it has been made by C. A. R. Hoare. In [1, Sec. 3.2.1.] Wirth and Hoare together make a remark in the same direction in motivating the case construction: "Like the conditional, it mirrors the dynamic structure of a program more clearly than go to statements and switches, and it eliminates the need for introducing a large number of labels in the program." Reference: 1. Wirth, Niklaus, and Hoare C. A. R. A contribution to the development of ALGOL. Comm. ACM 9 (June 1966), 413-432. From bignose+hates-spam at benfinney.id.au Sat Jul 7 20:02:01 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 08 Jul 2007 10:02:01 +1000 Subject: __unicode__ method for exception object References: Message-ID: <874pkfoj9i.fsf@benfinney.id.au> Manlio Perillo writes: > I have just noticed that exception objects does not handle well > Unicode arguments. This error is unrelated to the fact that you created an exception object. > >>> e = RuntimeError(u'?????') > >>> str(e) > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode characters in position Your terminal has been detected as using the 'ascii' encoding, so while that's true no attempt to output non-ASCII characters will work. You'll need to change whatever settings are on your terminal emulator so that it is using an encoding (such as 'utf-8') which can display the characters you want. -- \ "The World is not dangerous because of those who do harm but | `\ because of those who look at it without doing anything." -- | _o__) Albert Einstein | Ben Finney From Sascha.Kuhlmann at gmail.com Thu Jul 5 11:57:13 2007 From: Sascha.Kuhlmann at gmail.com (KuhlmannSascha) Date: Thu, 05 Jul 2007 15:57:13 -0000 Subject: How can i change an Object type ? In-Reply-To: <1183569245.352019.147380@r34g2000hsd.googlegroups.com> References: <1183516235.774875.45710@q69g2000hsb.googlegroups.com> <1183569245.352019.147380@r34g2000hsd.googlegroups.com> Message-ID: <1183651033.819953.243560@r34g2000hsd.googlegroups.com> On Jul 4, 12:14 pm, kyoso... at gmail.com wrote: > On Jul 4, 12:40 am, Tim Roberts wrote: > > > > > KuhlmannSascha wrote: > > > >i tried now for several hours to read through a win32com API to access > > >Itunes and read out myplaylists. > > > >First of all the Code: > > >... > > >The current Logic is to access first Itunes and then a Playlist > > >Collection. > > >This Playlist collection returns different kind of objects for > > >Playlists. > > >I am focussing on the Playlists of the object UserPlaylist. > > >(CodeLine: if curPlaylist.Kind == 2:) > > >After that i should be sure to have a UserPlaylist, but Python stops > > >with an exception that the requested Attribute "Smart" is not > > >available > > >Error MEssage: > > >AttributeError: ' > >instance at 0x30216960>' object has no attribute 'Smart' > > > Smart is part of IITUserPlaylist, not IITPlaylist. You need to call > > curPlaylist.QueryInterface to get the IITUserPlaylist, but that means > > you'll need to know the GUID for IITUserPlaylist. Perhaps Google will > > help. > > -- > > Tim Roberts, t... at probo.com > > Providenza & Boekelheide, Inc. > > These look like they could give you some pointers too: > > http://www.brunningonline.net/simon/blog/archives/001627.htmlhttp://lazycat.org/backburner.htmlhttp://mail.python.org/pipermail/python-win32/2007-February/005506.html > > Mike Thanks all of you ! The Casting was the issue !!! Regards Sascha From jipksaman at gmail.com Mon Jul 9 06:42:02 2007 From: jipksaman at gmail.com (abdo911) Date: Mon, 09 Jul 2007 03:42:02 -0700 Subject: ?Hi Hi Hi.....ARE YOU Searching for Happiness Message-ID: <1183977722.060978.150010@q75g2000hsh.googlegroups.com> Allow me to share with you here some information about happiness. Happiness is a common goal that everyone strives to attain. Philosophers, intellectuals, doctors and artists alike have all strived in search of the causes of happiness and ways to escape anxiety. The reality is, however, that the proposed solutions achieve only partial or superficial happiness. They are more or less like drugs which only provide temporary relief; when their effect wares off, anxieties return two fold. The following words invite you to ultimate happiness and will lead you to true success. But before you begin reading, I hope that you to take a moment to try to open your heart and mind - as the intelligent one is he who searches for the truth no matter where it lies. An undeniable reality is that permanent happiness cannot be achieved except by believing in God - The Creator - and following His guidance. Since it is He who created mankind, He is the one who knows what pleases and benefits them, just as he knows what saddens and harms them. A number of psychologists have affirmed that only a religious person lives with true content and serenity. So if believing in God leads to ultimate happiness, then how can this be achieved? There are numerous religions and a variety of creeds. However, their critical differences in core issues make it impossible for all of them to be correct. So which is the correct religion? What is the correct creed that God requires us to believe in and in the end pleases Him? And which one of these creeds guarantees us happiness in this life and in the hereafter? Before answering these questions, a criterion must first be established to be used as a basis for correctly determining the true religion. I firmly believe that all sensible people will agree that a religion is not deemed correct simply due to the fact that one was raised in that religion, had parents that adhered to it, or lived in a society that practiced it. Rather a religion's accuracy and authenticity are based upon substantial evidence and firm intellectual proofs. Intellect, the distinguishing factor between mankind and animals, must be applied when studying the issue of religion, which is undeniably the most important and gravest of all matters. A short journey into the world of religions and sifting through various creeds could prove to be a good method in arriving at the desired conclusion. In order to save you the time and effort, I say with full conviction and confidence that no matter how much you investigate this issue, you will only arrive at one reality: that the true and correct religion is Islam and that true happiness and content lies within it. Before you hastily rebut this statement and stop reading, please realize that completing the rest would not harm you at all, and it may in fact benefit you. Also, remember that you have an intellect by which you can distinguish things and determine truth from falsehood. Why Islam? This is an important question, indicating that the questioner is mature and enlightened. In response I say: Islam is a religion that includes a number of merits and characteristics that are absent from other religions. These characteristics, alone, serve as convincing evidence that Islam is the true religion of God. You can determine the authenticity of this statement by contemplating them. Islam's many merits and characteristics make it impossible to elaborate on all of them. However, some of the most important can be summarized as follows: 1. Amongst the greatest merits of Islam is that it fulfills the spiritual aspects of the human being and enables those who embrace it to have an ongoing connection with God. This makes it possible for them to be at ease spiritually. It shields them from chaos, being lost or feeling (spiritually) empty, and protects from mental instability. 2. Another of Islam's merits is that it coincides totally with common sense. All of the Islamic legislation and its rulings are acceptable intellectually and are never contradictory. One man who embraced Islam was asked why he did so and replied, "Islam never ordered me to do anything that I later wished wasn't obligated, and it never forbade me from anything that I later wished wasn't forbidden." Much of what is readily accepted in other religions causes great confusion. This confusion makes it difficult to believe many of the fundamental tenets/doctrines that these religions are based upon. On the other hand, we find that Islam respects the intellect, prohibits ignorance, and condemns blind following. 3. Islam is an all-inclusive way of life attending to both spiritual and physical needs. Practicing Islam does not mean that one has to be secluded or that he is prohibited from the finer things in life. Rather, according to Islam, a person can be religious and still enjoy a normal life - attaining prestigious ranks/positions and achieving the highest academic degrees. 4. Among the merits of Islam is that it is a comprehensive religion. Every aspect of a person's life is managed by Islam. There is not a problem except that a solution for it lies in Islam, which makes it possible to embrace and practice in every time and place. How can this not be the case in such a well organized religion that has guidelines and positive instruction for every aspect of life including: conflict resolution, buying and selling, social and marital relations, greetings, public etiquettes, and even how a person eats, sleeps and dresses. These practices have not been addressed generally, but rather in precise detail, causing the mind to wonder in amazement. Know that Islam even provides direction on how to wear and remove footwear. It encourages people to use their right hand when eating, drinking, shaking hands, and when giving and receiving items. As for disliked affairs such as using the bathroom, the left hand is to be used. Islam also has wonderful instructions regarding going to sleep and waking up. When two Muslims meet, Islam directs them on how they should greet each other; a rider should initiate greeting the pedestrian, the youth should initiate greeting the elderly, and a small group should initiate greeting a larger group. These are but a few of Islam's many comprehensive guidelines for all aspects of life. 5. Another of Islam's merits is that it establishes good for mankind in all its regulations and safeguards them from evil. It is man himself who benefits from these regulations. Islam's prohibition of alcohol and drugs for example is only because of the great harm they cause to a person's physical and mental health. You can witness the state of a drunken man, no longer human except in appearance. A lot of murders, disputes, traffic accidents and rapes would not have taken place were it not for consuming these mind-altering products. Islam's prohibition of premarital sex relieves societies of destructive diseases (such as AIDS and other STDs), immoral behavior, and the existence of a generation of illegitimate children. This generation is often deprived of a mother's love and a father's upbringing which can lead them to become burdensome on society. Islam prohibits women from displaying themselves publicly. This is because Islam considers women to be valued, preserved pearls; not some cheap merchandise to be displayed for all to see. It does so to protect them from the wolves of mankind - those who are only concerned with satisfying their lusts, even if it is at the cost of a woman's honor, nobility, status, and purity. On the other hand, Islam permits all harmless and beneficial drinks. It also permits married couples to enjoy one another within a happy home. In summary, Islam has not eliminated freedoms and desires. Rather, it regulates them for the benefit of mankind and the society at large. 6. A radiant aspect of Islam is that it pays a great deal of attention to values, character, and praiseworthy manners, while prohibiting mankind from oppression, transgression and bad character. Islam is a religion of love, unity and mercy. It defines an individual's relationship with his parents, relatives, neighbors, friends and all people. Islam embeds the best of manners in those who embrace it and prevents them from living selfishly. It encourages its followers to help others and take others' feelings into consideration - especially the poor, orphans, elderly and widows. They all have rights in Islam that must not be taken lightly by Muslims. Muslims shouldn't feel like they are bestowing favors upon others when giving them their due rights, rather these rights are obligations upon Muslims. It is considered to be a great sin in Islam for one to go to sleep with a full stomach knowing that his neighbor is hungry. Islam even prohibits two people from whispering to each other in the presence of a third, taking his feelings into consideration. Islam goes even further than that, obligating kind treatment to animals and prohibiting harming them. More specifically, Islam prohibits slaughtering an animal while another watches, or sharpening a knife while it is watching, so that it is not tormented along with being slaughtered. Truthfulness, trustworthiness, bravery, generosity, humility, abiding by promises, visiting the sick, attending funerals, being dutiful to parents, visiting relatives and neighbors, and striving to help others are all etiquettes that are encouraged by Islam. On the other hand, Islam strictly prohibits oppression, lying, conceitedness, envy, and insulting or betraying others. It is impermissible in Islam to speak ill of a person in his absence, even if what is being said is true. Islam encourages people to moderate in spending, being neither excessive nor misers. During times when a lot of societies complain about cold heartedness, materialism, selfishness and so on, we find that Islam has proven remedies for all of these problems. This summarized introduction should make it clear that Islam is a logical religion that can be easily understood by all people. The doors to Islam are wide open and do not shut for anyone looking to enter. Understanding all of Islam's teachings in a short article is impossible. However, briefly discussing some of its fundamental tenets should assist in further clarifying the religion for those who are interested. All of Islam's regulations and teachings are important, but some have precedence over others. There are six essential articles of faith that one must believe in, and five pillars that one's faith must be built upon. As for the six articles that must be believed in: 1. Believing in Allah (God) alone, associating no partners unto Him in worship. This is done by believing that Allah alone is the Creator of this universe and everything that is within it, and that it is He alone who disposes its affairs as He sees fit. Consequently, worship can only be offered to Him alone. Worship is implementing the teachings of Islam and its legislation while believing that all other religions are false. 2. Believing in the angels. Angels were created by Allah but we can not see them. They worship Allah and never disobey Him. Allah orders them to carry out many of the universe's affairs. The angel Gabriel, for example, (peace be upon him) delivers Allah's revelation to the messengers. Another is Mikayeel (peace be upon him), who is entrusted with the affairs of rain. Still there are other angels responsible for writing the deeds of mankind - deeds which they will be held accountable for on the Day of Resurrection. It is essential to believe that all of the angels act solely upon the order of Allah and do only what He wills. 3. Believing in the Books of Revelation. This means to believe that Allah revealed books to His servants comprising of His words. These books contain bliss for mankind by clarifying what Allah is pleased with as well as what He dislikes. The Angel charged with delivering revelation to the Prophets is Gabriel (peace be upon him) - the greatest of angels. A prophet then conveys the revelation to the rest of mankind. Allah has revealed many books, amongst them: The Torah, revealed to Moses (peace be upon him), The Psalms, revealed to David (peace be upon him), The Gospel, sent down to Jesus (peace be upon him) and the Quran, which was revealed to Muhammad (peace be upon him). One must believe that the Quran has abrogated all books prior to it, meaning that - after the Prophet (Muhammad) was sent - it is the only book that can be acted upon, especially since the Quran combines all the merits of past books and further supplements them. Know that the Quran is from the greatest evidences that this religion is the truth revealed by Allah (God) the Most High. The Quran was revealed over 1400 years ago. Since then till this day, no contradictions or mistakes have been found in the Quran, not even in a single word. Many of the scientific discoveries of modern times were mentioned in the Quran. Since that time until today, nothing has been added to or subtracted from the Quran, while previous revelations have been tampered with and altered. It is for this reason that you can pick up a copy of the Quran in the far East and find it to be exactly the same as one you pick up in the far West. If you were to come across a copy of the Quran that is hundreds of years old, you would also find that it is exactly the same as the one being printed currently - you wouldn't be able to find even one letter that is different. This is because of Allah's protection of this Book, the Book of the religion that sealed all other religions. Speaking about the Quran would take a lot of time. However, it is enough for you to know that there is nothing like it whatsoever; not by way of (literary) style, its effect on people, nor its information about the unseen. 4. Believing in the Prophets. This is done by believing that Allah has chosen the best of mankind to be recipients of His revelation and ordered them to convey His religion to the people. There are numerous Prophets, among them are: Noah, Abraham, David, Solomon, Lot, Joseph, Moses and others (peace be upon all of them). Also from them is Jesus. It is imperative to believe that he is among the best of Prophets and to love and respect him. Whoever despises him or denies his prophethood is not Muslim. Likewise it is compulsory to believe that Allah created him from a mother only, with no father, just as Allah created Adam with neither a mother nor a father. Having mentioned this, we now know that Jesus is a noble messenger and not God, nor is he a son of God. He foretold the coming of a prophet to come after him; Muhammad ibn (the son of) Abdullah, the last of the prophets. Muhammad ibn Abdullah (peace be upon him) was sent 1400 years ago. It is compulsory for everyone who comes after him until the Day of Judgment to believe in him and his message, and obey his orders and prohibitions. All those who studied the biography of this messenger have agreed that he is a great personality who has been bestowed with the best of manners and most noble etiquettes. He had characteristics which were not present in anyone before him and will not be present in anyone after him. Anything that you read about him, no matter how small it is, confirms what I am saying. Allah has also granted him proofs and evidences that establish the authenticity of his prophethood, thus having doubt in this fact is intellectually impossible. Having been given such proofs and evidences of his prophethood, whoever denies his truthfulness, would make it impossible for that individual to establish the truthfulness of any other prophet. 5. The Last Day. This is fulfilled firmly believing that after this life of ours is over, there is another more complete life. In it, there are immense rewards and magnificent luxuries, as well as punishment. Luxury is in Heaven and punishment in Hell. So whoever is righteous and believes in the religion of Islam enters Heaven, a place that contains untold pleasure and unimagined bliss. All the luxuries on earth cannot be compared to it at all. Whoever enters Heaven will continue to live in such luxuries for eternity as death does not exist therein. As for those who act upon evil and do not believe in Islam, they would end up in Hell, which contains fires and punishment that can not be imagined, all of the fires of earth and forms of punishment cannot be compared to the punishment of the hellfire at all. The existence of punishment and reward after this life is an issue that is intellectually acknowledged, because it is impossible for this world to exist and then just diminish into nothingness. This is trifling about, and our Lord, the Creator, does not engage in such activities. 6. Believing in Divine Decree. This is to believe that everything that happens in this world is due to Allah's knowledge and will. Nothing except what He wills takes place, and what He does not will, does not take place. Allah has written everything in a great book (The Preserved Tablet). Believing in divine decree also includes believing that Allah created everything. As for the five pillars that must be practiced: 1. Uttering a phrase that is the key to entering into Islam. It is a contract between a servant and his Lord, signifying that he is upon this religion: "Ashhadu an la ilaha ila Allah, wa ashadu ana Muhammad 'abduhu wa rasuluhu." "I bear witness that there is no deity worthy of worship except Allah, and that Muhammad is His servant and Messenger." This testimony signifies the acceptance, admission, and adherence to the fact that worship must be offered to Allah alone. It also includes the acceptance of Islam as the only correct religion, Allah as the only true deity deserving worship, and that all other deities and religions are false. The second part of the testimony entails an affirmation that Muhammad is the Messenger of Allah and that he is to be obeyed and believed in all that he says. 2. The Prayer. It is a combination of statements, actions and invocations carried out in a specific manner. It is performed five times daily and doesn't take much time at all. In fact, a prayer may not take more than five minutes. Prayer is the link between a servant and his Lord. It enables a Muslim to be confident, mentally and spiritually at rest, calm and untroubled. 3. The Zakaat. A wealthy Muslim must give a small portion of his money to the poor, 2.5% of his wealth to be exact. Even though it is a small amount, it enables the Muslim community to be conciliated and merciful amongst each other. It propagates brotherhood, love and concern amongst Muslims. And again, Zakaat is only to be given out by the wealthy, not the poor. 4. Fasting. What is meant by fasting is that a person withholds from eating, drinking and sexual relations during the month of Ramadan [which is the 9th month of the lunar calendar] between dawn and sunset. The sick, travelers, and those with valid excuses are pardoned from fasting. They are permitted to eat and drink but must make up the missed days once they become able. Fasting has many health, personal, and social benefits. Amongst them are: giving the digestive system a break, allowing Muslims to grow spiritually and practice good mannerisms. It enables Muslims to be conscious of their needy brothers and sisters, those who are unable to find enough food to satisfy their needs throughout the year. Consequently, the Muslims humble themselves and strive to help them. 5. Hajj. It is a form of worship that must be performed only once in a lifetime, in Makkah. Those who are physically incapable or not financially able to perform it are pardoned from doing so. Hajj contains many magnificent benefits; the gathering of Muslims from all around the globe in one place getting to know each other and displaying love for one another, not to mention what a Muslim achieves by way of spiritual purification and character refinement due to experiencing such a spiritual environment in the shade of Hajj. Hopefully what has preceded is sufficient in clarifying - in a summarized fashion - some of the merits of Islam. I invite all who have not yet entered into the fold of Islam to listen to a sincere invitation from one who only wants good for you: save yourself before death takes you by surprise, and thus you die upon other than Islam - what a great loss that is! Do you know what dying upon other than Islam means? It means that you would enter the Hellfire, abiding therein for eternity. This is what Allah has warned all those who die without embracing Islam. So why would you take a chance with an issue as grave as this? I'm going to ask you a question that I want you to answer honestly: What would you lose if you embraced Islam? If you embrace Islam, you can continue living your normal ordinary life, but in a more spiritual, organized, and pleasant fashion...and after death, tremendous delight and eternal pleasure await you. If you have reached a level of conviction, believing that Islam is the true religion, but fear that embracing Islam would prevent you from enjoying pleasures that you cannot live without, then compare these temporary pleasures with eternal pleasure. Which of the two should be given preference? Furthermore, you can embrace Islam and then gradually try to reduce such pleasures. And if you were to honestly invoke Allah, He would surely aid you in leaving them. In any case, embracing Islam and having shortcomings is better than not embracing Islam at all. If the barrier between you and Islam is due to having a weak personality, the inability to make such a big decision, or because you fear that people may talk about you or mock you, know that these are just unrealistic thoughts. You would not be the first person to embrace Islam; a lot of others have made the decision to do so. They did not lose anything, their lives were not ruined, nor do they have any regrets. Furthermore, does it make sense that you sacrifice your own well being and happiness in this life and in the hereafter just because you fear mockery or admonishment? This affair is worthy of your time. Contemplate upon it deeply. My last words: Do not lose yourself! I ask Allah to bless you with true guidance. One who wishes only the best for you, ABDO911 I advise you visiting : http://www.islam-guide.com/ http://www.thetruereligion.org/ http://www.beconvinced.com/ http://www.plaintruth.org/ http://english.islamway.com/ http://www.todayislam.com/ http://www.prophetmuhammed.org/ http://www.islamtoday.net/english/ http://www.islamunveiled.org/ http://www.islamic-knowledge.com/ From steve at REMOVE.THIS.cybersource.com.au Tue Jul 24 19:21:22 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 25 Jul 2007 09:21:22 +1000 Subject: classmethod & staticmethod References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> <46a5b2ad$0$18903$426a74cc@news.free.fr> Message-ID: On Tue, 24 Jul 2007 21:35:58 +0000, Alex Popescu wrote: > Neil Cerutti wrote in > news:slrnfaccgl.1gk.horpner at FIAD06.norwich.edu: > >> On 2007-07-24, Alex Popescu wrote: >>> Bruno Desthuilliers >>> wrote in news:46a5b2ad$0$18903$426a74cc at news.free.fr: >>> >> >> [snip...] >> >>> >>> class MyClass(object): >>> class_list = ['a', 'b'] >>> >>> def instance_method(self): >>> print "instance_method with class list %s" % class_list >> >> There's no implicit self or class for Python identifiers. >> >> The name class_list must be quailified: self.class_list or >> MyClass.class_list. >> > > After more investigation I have figured this out by myself, but thanks for > the details. > Now I am wondering if in the above case there is a prefered way: > MyClass.class_list or self.__class__.class_list? (IMO the 2nd is more safe > in terms of refactorings). Consider what happens when you sub-class: class MyClass(object): class_list = [1, 2, 3] def method(self, x): return sum(MyClass.class_list) + x class MySubclass(MyClass): class_list = ['a', 'b', 'c'] # over-ride the class attribute expecting_a_string = MySubclass().method('x') Use a direct reference to MyClass.class_list when you want a direct reference to MyClass regardless of which instance or class you are calling from. Use self.class_list when you want to use inheritance. Use self.__class__.class_list when you have an instance method and you need the class it belongs to. Use a classmethod and the first argument (by convention called klass or cls) when you don't care about the instance and just want the class. -- Steven. From theller at ctypes.org Wed Jul 4 14:55:46 2007 From: theller at ctypes.org (Thomas Heller) Date: Wed, 04 Jul 2007 20:55:46 +0200 Subject: Interest in a one-day business conference for Python, Zope and Plone companies ? In-Reply-To: <4688FFCE.6040009@egenix.com> References: <4688FFCE.6040009@egenix.com> Message-ID: eGenix Team: M.-A. Lemburg schrieb: > Hello, > > eGenix is looking into organizing a one day conference > specifically for companies doing business with Python, Zope and > Plone. The conference will likely be held in or close to > D?sseldorf, Germany, which is lively medium-sized city, with good > airport connections world-wide and specifically to all major > European cities, so it's easy getting there and ideal for a one > day event. I would be interested in such an event. But: Am I the only one? Thomas From rcdailey at gmail.com Fri Jul 6 17:37:53 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 06 Jul 2007 21:37:53 -0000 Subject: ImportError: "No Module named xxx" In-Reply-To: <5f7p2eF3bm6tuU1@mid.individual.net> References: <1183750316.740239.257010@m36g2000hse.googlegroups.com> <1183750738.308894.261750@c77g2000hse.googlegroups.com> <5f7p2eF3bm6tuU1@mid.individual.net> Message-ID: <1183757873.958122.238780@g4g2000hsf.googlegroups.com> On Jul 6, 4:04 pm, Bjoern Schliessmann wrote: > Robert Dailey wrote: > > The description of -m is confusing in the documentation, what does > > it really do? > > IMHO, it's quite clear. What's unclear with this description: > > -m module-name Searches sys.path for the named module and runs > the corresponding .py file as a script. > > Regards, > > Bj?rn > > -- > BOFH excuse #191: > > Just type 'mv * /dev/null'. Perhaps the confusing part is their definition of "Script". I figured any .py file was a "python script", in that it has code to execute- making it a script. From nospam at example.com Fri Jul 13 20:09:47 2007 From: nospam at example.com (Tony23) Date: Fri, 13 Jul 2007 17:09:47 -0700 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: <139g52918liskef@corp.supernews.com> Chris Carlen wrote: > John Nagle wrote: >> Chris Carlen wrote:[edit] >>> Hence, being a hardware designer rather than a computer scientist, I >>> am conditioned to think like a machine. I think this is the main >>> reason why OOP has always repelled me. >> >> Why? > > When pointers were first explined to me, I went "Ok." And rather > quickly ideas lit up in my head about what I could do with them. > > When I read what OOP is, that doesn't happen. All I think is "what's > the point of this?" "What can this do for me that I can do already with > the procedural way of thinking?" And if it can't do anything new, then > why rearrange my thinking to a new terminology? It's results that > matter, not the paradigm. I have been programming since 1978. I started off with BASIC, learned Assembly and Pascal, and much later eventually moved on to Javascript, Perl, and PHP. All of my work was done procedurally. Recently, I have been working on a very large project involving a lot of OO-Javascript. For what we are doing on the project, OO makes sense. I really didn't get OOP until working on this project - probably because I never did anything that really needed it. I have found myself leaning more toward the OO paradigm since doing this, after 25+ years of procedural programming, and now I find myself doing more work with OO concepts, and getting things done even faster, and with less work, than I used to. But I still have a problem with STRICT OOP - which is why I like Python. Use OO where it's useful, use procedural when that works best. I suspect that the reason it isn't clicking for you is twofold: 1) You don't do anything currently that has an obvious need for OOP, and 2) You haven't done anything with OOP. A couple ideas: 1) Maybe you can try building a relatively trivial program that would more naturally use an OO methodology - perhaps a simple videogame like Pac-man? The 'monsters' would be objects, with properties such as color, X-position, Y-position, etc. - make yourself work in OO terms 2) This may seem silly, but download & play with "Scratch" (http://scratch.mit.edu) - it's basically an introduction to programming for kids, but it's completely OO, and super easy to use. It might be useful to help you to see the 'grand view' better. 3) Give in to the dark side :) Good luck - after so much time invested in one way of thinking, it's not easy to change. From skpatel20 at gmail.com Thu Jul 12 05:47:48 2007 From: skpatel20 at gmail.com (Sanjay) Date: Thu, 12 Jul 2007 02:47:48 -0700 Subject: pytz giving incorrect offset and timezone Message-ID: <1184233668.072963.264020@d55g2000hsg.googlegroups.com> Hi All, Using pytz, I am facing a problem with Asia/Calcutta, described below. Asia/Calcutta is actually IST, which is GMT + 5:30. But while using pytz, it was recognized as HMT (GMT + 5:53). While I digged into the oslan database, I see the following: # Zone NAME GMTOFF RULES FORMAT [UNTIL] Zone Asia/Calcutta 5:53:28 - LMT 1880 # Kolkata 5:53:20 - HMT 1941 Oct # Howrah Mean Time? 6:30 - BURT 1942 May 15 # Burma Time 5:30 - IST 1942 Sep 5:30 1:00 IST 1945 Oct 15 5:30 - IST Searching in this group, I saw a similar problem posted at http://groups.google.co.in/group/comp.lang.python/browse_thread/thread/55496e85797ac890 without any solutions. I mailed to Stuart and also posted it at the launchpad of pytz, but did not get any response. Unable to know how to proceed further. Any suggestion will be of vital help. thanks Sanjay From inq1ltd at inqvista.com Tue Jul 31 18:45:57 2007 From: inq1ltd at inqvista.com (jim-on-linux) Date: Tue, 31 Jul 2007 18:45:57 -0400 Subject: Error with Tkinter and tkMessageBox In-Reply-To: <46af8c5d$0$10619$4fafbaef@reader2.news.tin.it> 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: <200707311845.57630.inq1ltd@inqvista.com> On Tuesday 31 July 2007 15:24, Fabio Z Tessitore wrote: > Il Tue, 31 Jul 2007 19:12:48 +0000, kyosohma ha scritto: > > I'm not sure, but I don't think you need the > > "win" variable at all. I can get it to work > > as follows: > > > > > > > > from Tkinter import * > > from tkMessageBox import showinfo > > > > def reply(): > > showinfo(title='ciao', > > message='hello') > > > > Button(text='press me', > > command=reply).pack(fill=X) mainloop() > > > > > > > > Mike > > You're right. But the problem I have is always > there. Tkinter doesn't work properly and I > don't understand why. Thanks! Try This: def reply(): showinfo('ciao','hello') jim-on-linux http://www.inqvista.com From evan at yelp.com Fri Jul 13 14:30:57 2007 From: evan at yelp.com (Evan Klitzke) Date: Fri, 13 Jul 2007 11:30:57 -0700 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: On 7/13/07, John Nagle wrote: > You can sometimes get better performance in C++ than in C, because C++ > has "inline". Inline expansion happens before optimization, so you > can have abstractions that cost nothing. This is a bit off topic, but inline is a keyword in C since C99. -- Evan Klitzke From steve at holdenweb.com Mon Jul 30 16:38:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Jul 2007 16:38:51 -0400 Subject: How to write GUI and event separately in wxPython?? In-Reply-To: <1185826617.556482.23530@g4g2000hsf.googlegroups.com> References: <1185777254.925902.204500@z28g2000prd.googlegroups.com> <5h5kmiF3hmufcU3@mid.uni-berlin.de> <5h5upbF3hmufcU5@mid.uni-berlin.de> <1185826617.556482.23530@g4g2000hsf.googlegroups.com> Message-ID: <46AE4C5B.5060706@holdenweb.com> star.public at gmail.com wrote: > On Jul 30, 11:42 am, "Chris Mellon" wrote: > >>>> On Mon, 30 Jul 2007 06:32:55 -0400, Steve Holden wrote: >>>>> >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)] >>>>> True > >> nitpick: list(xrange(42)) == list(xrange(42)) is slightly more concise >> than the list comp.. > > Not that it has anything to do with this topic anymore, but I find the > list comp a bit clearer for expressing the thought 'each element in > one is the same as the coresponding element in the other, or: the > sequences are identical' -- the list() version would proabably have > had me going 'huh?' even longer ^_^. > -- > [star for star in weaver] Here's another one, a little more obscure still, but only valid in 2.5 because of all(): >>> all(x==y for (x, y) in zip(xrange(0, 101), xrange(101))) True >>> 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 mmarch at gmail.com Sat Jul 7 17:21:53 2007 From: mmarch at gmail.com (Cowmix) Date: Sat, 07 Jul 2007 14:21:53 -0700 Subject: Phoenix, AZ PIGgie (User Group)? Message-ID: <1183843313.579460.292070@a26g2000pre.googlegroups.com> Does anyone know if there is a Phoenix (Arizona) based Python User Group? If not, is there any interest out there to start one? Personally, I'm motivated to help out with it.. If you are interest too (or know of an existing group I might of over- looked) email mmarch at gmail dot com. thanks! From nospam.themindstorm at gmail.com Wed Jul 25 19:23:46 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Wed, 25 Jul 2007 23:23:46 +0000 (UTC) Subject: Singleton in Python Cookbook References: <5gq00tF3fm71gU1@mid.uni-berlin.de> Message-ID: Alex Popescu wrote in news:Xns9979172DC38F1themindstorm at 80.91.229.5: > "Diez B. Roggisch" wrote in > news:5gq00tF3fm71gU1 at mid.uni-berlin.de: > >> Alex Popescu schrieb: >>> Hi all! >>> >>> I was reading through Python Cookbook the Singleton recipe. At this >>> moment I am a bit puzzled as the example in the book is not working >>> resulting in: >>> >>> TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of >>> type >>> >>> (I haven't presented the original code as I am not sure about >>> copyrights). >> >> AFAIK the cookbook is completely found online at ASPN. So no sweat >> publishing it here. >> >> >> And regarding the problem: is it possible that you forgot to subclass >> SingleSpam from object? >> >> Diez > > The exact code: > class Singleton(object): > """ A Pythonic Singleton """ > def _ _new_ _(cls, *args, **kwargs): > if '_inst' not in vars(cls): > cls._inst = type._ _new_ _(cls, *args, **kwargs) > return cls._inst > > if _ _name_ _ == '_ _main_ _': > class SingleSpam(Singleton): > def _ _init_ _(self, s): self.s = s > def _ _str_ _(self): return self.s > s1 = SingleSpam('spam') > print id(s1), s1.spam( ) > s2 = SingleSpam('eggs') > print id(s2), s2.spam( ) > > ./alex > -- > .w( the_mindstorm )p. > I got it working in 2 ways: class Singleton(object): """ A Pythonic Singleton """ def __new__(cls, *args, **kwargs): if '_singletoninstance' not in vars(cls): #variant 1: cls._singletoninstance = object.__new__(cls, *args, **kwargs) #variant 2: cls._singletoninstance = super(type, cls).__new__(cls, *args, **kwargs) return cls._singletoninstance Both of these seem to work. ./alex -- .w( the_mindstorm )p. From benc.nospam at gmail.com Tue Jul 3 11:42:40 2007 From: benc.nospam at gmail.com (Ben Cartwright) Date: Tue, 03 Jul 2007 08:42:40 -0700 Subject: mysteries of urllib/urllib2 In-Reply-To: <1183475672.295922.47600@e9g2000prf.googlegroups.com> References: <1183470239.153444.244700@j4g2000prf.googlegroups.com> <1183472702.932557.108600@n2g2000hse.googlegroups.com> <1183475672.295922.47600@e9g2000prf.googlegroups.com> Message-ID: <1183477360.751290.273740@n2g2000hse.googlegroups.com> On Jul 3, 11:14 am, Adrian Smith wrote: > > > The following (pinched > > > from Dive Into Python) seems to work perfectly in Idle, but > > > falls at the final hurdle when run as a cgi script > > Put this at the top of your cgi script: > > > import cgitb; cgitb.enable() Did you even try this? Asking for Python help without posting the traceback is like phoning your mechanic and saying, "My car is making a generic rattling noise, can you tell me what the problem is without looking under the hood?" > Apparently there's a way to change the user-agent string > by subclassing urllib's URLopener class, but that's beyond my comfort > zone at present. Untested: import urllib url = 'http://groups.google.com/group/Google-AJAX-Search-API/ browse_thread/thread/a0eb87ad13b11762' opener = urllib.FancyURLopener() opener.addheaders = [('User-Agent', 'Fauxzilla 4.0')] data = opener.open(url).read() Hope that helps, --Ben From crcarleRemoveThis at BOGUSsandia.gov Mon Jul 16 14:45:04 2007 From: crcarleRemoveThis at BOGUSsandia.gov (Chris Carlen) Date: Mon, 16 Jul 2007 11:45:04 -0700 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: Hendrik van Rooyen wrote: > "Chris Carlen" wrote: >>Form 2: Use Python and PySerial and TkInter or wxWidgets. >>Pro: Cross-platform goal will likely be achieved fully. Have a >>programmer nearby with extensive experience who can help. >>Con: Must learn new language and library. Must possibly learn a >>completely new way of thinking (OOP) not just a new language syntax. >>This might be difficult. > This is the way to go. - Trust me on this. > When you describe your history, it is almost an exact parallel to mine. > In my case, I have been doing real low level stuff (mostly 8031 assembler) > since 1982 or so. And then I found python in a GSM module (Telit), and > I was intrigued. > I really appreciate your comments on OO - it parallels a lot of what I feel > as there is a lot of apparent BS that does not seem to "do anything" at first > sight. > However- for the GUI stuff, there is an easily understood relationship between > the objects and what you see on the screen - so its a great way of getting > into OO - as far as people like you and me will go with it, which is not very > far, as we tend to think in machine instructions... > And for what its worth - you can programme assembler-like python, and it also > works. > > The best thing to do is just to spend a few days playing with say Tkinter. > I use a reference from the web written by John W Shipman at New Mexico > Tech - it is succinct and clear, and deserves more widespread publicity. > > Google for it - I have lost the link, although I still have the pdf file. [edit] Thanks for the tip. The next poster provides the link, which I've got bookmarked now. The more I play with Python, the more I like it. Perhaps I will understand OOP quicker than I thought. What I've learned so far about names binding to objects instead of values stored in memory cells, etc. has been interesting and fascinating. -- Good day! ________________________________________ Christopher R. Carlen Principal Laser&Electronics Technologist Sandia National Laboratories CA USA crcarleRemoveThis at BOGUSsandia.gov NOTE, delete texts: "RemoveThis" and "BOGUS" from email address to reply. From gagsl-py2 at yahoo.com.ar Sun Jul 29 10:57:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 29 Jul 2007 11:57:11 -0300 Subject: problem with change to exceptions References: Message-ID: En Fri, 27 Jul 2007 19:49:17 -0300, Neal Becker escribi?: > import exceptions > > class nothing (exceptions.Exception): > def __init__ (self, args=None): > self.args = args > > if __name__ == "__main__": > raise nothing > > Traceback (most recent call last): > File "", line 1, in > File "/usr/tmp/python-3143hDH", line 5, in __init__ > self.args = args > TypeError: 'NoneType' object is not iterable > > I'll have to say, I don't understand this error. If this is all your code, try using just: class nothing(Exception): pass if __name__ == "__main__": raise nothing Exceptions are built-in since aeons ago, so you don't have to import the exceptions module. The standard Exception class has an "args" attribute, and it's expected to be a tuple (not None). See -- Gabriel Genellina From tunuyan-house at hotmail.com Mon Jul 16 18:33:02 2007 From: tunuyan-house at hotmail.com (Natalia) Date: Mon, 16 Jul 2007 15:33:02 -0700 Subject: www.cerocom.com Message-ID: <1184625182.795126.291700@n2g2000hse.googlegroups.com> ...................................... www.cerocom.com ...................................... You will be able to ask yourself: Is Internet a good investment for my company? So that an investment would have to do I of this type? Really is going to serve to me to have a Web site? So that to be in Internet? See some of the main advantages have a Web site: ? Increase the productivity and to generate more businesses with the implementation of collaboration rofe and integration maximizing the value of Internet and networks IP. ? Offer solutions of Internet, integration and collaboration in accordance with our clients, anyone is their size or trains, to rofesional r to integrate their applications, to fortify their present position in the market or to impel their growth, assuring trustworthiness, discharge rofesional qualification, and customized service. I invite it to cross the Web site and interiorice of the services available. www.cerocom.com Contact: Commercial direction: Viamonte 783 Piso 3? Capital Federal (C1053ABO) Bs. As. Argentina Tel/Fax: (54.11) 4322.1201 Celular: (54-9-11) (15) 5006.4384 Mail: cerocom at cerocom.com Web Site: www.cerocom.com From holdenweb at gmail.com Mon Jul 2 13:32:57 2007 From: holdenweb at gmail.com (holdenweb at gmail.com) Date: Mon, 02 Jul 2007 10:32:57 -0700 Subject: subprocess -- broken pipe error In-Reply-To: <1183396350.429008.185200@n2g2000hse.googlegroups.com> References: <1183396350.429008.185200@n2g2000hse.googlegroups.com> Message-ID: <1183397577.959518.264230@g4g2000hsf.googlegroups.com> On Jul 2, 1:12 pm, 7stud wrote: > Hi, > > Can someone explain what a broken pipe is? The following produces a > broken pipe error: > > ---------- > import subprocess as sub > > p = sub.Popen(["ls", "-al", "../"], stdin=sub.PIPE, stdout=sub.PIPE) > > print p.stdout.read() > #outputs the files correctly > > p.stdin.write("ls\n") > #IOError: [Errno 32] Broken pipe > ----------- You are seeing this error because sub.Popen closes both stdin and stdout once the subprocess terminates (which it must have done for p.stdout.read() to return a result). Consequently you are trying to write to a pipeline whose reader has already closed it, hence the error message. regards Steve From deeasbury at msn.com Tue Jul 17 17:13:37 2007 From: deeasbury at msn.com (Dee Asbury) Date: Tue, 17 Jul 2007 16:13:37 -0500 Subject: really small values Message-ID: In multiplying a value of xe^-325 with ye^-4, Python is returning zero. How do I get it to give me back my tiny value? Thanks! Dee "The most exciting phrase to hear in science, the one that heralds new discoveries, is not 'Eureka!' but 'That's funny...'" - Isaac Asimov From musiccomposition at gmail.com Wed Jul 18 16:15:08 2007 From: musiccomposition at gmail.com (Benjamin) Date: Wed, 18 Jul 2007 13:15:08 -0700 Subject: wxPython, searching, and threads Message-ID: <1184789708.351825.224110@x35g2000prf.googlegroups.com> Hello! I am writing a search engine with wxPython as the GUI. As the search thread returns items, it adds them to a Queue which is picked up by the main GUI thread calling itself recursively with wx.CallAfter. These are then added to a ListCtrl. This works fine for small searches, but with larger and longer searchs the GUI is clogged and won't respond. I suspect (I may be wrong) that there are so many results being sent to the ListCtrl that the event loop doesn't have time to respond to events. I've tried buffering the results before sending them to the GIU, but that doesn't help at all. Please advise. From torriem at chem.byu.edu Sat Jul 28 21:32:06 2007 From: torriem at chem.byu.edu (Michael Torrie) Date: Sat, 28 Jul 2007 19:32:06 -0600 Subject: Memory utilization (linux v. openbsd) In-Reply-To: References: Message-ID: <46ABEE16.2010400@chem.byu.edu> nazgul at jsbsystems.com wrote: > My problem is that the two process under OpenBSD are going to fail with > a MemoryError becaause the size just keeps getting larger and larger. > ulimit -d is 1G for each process. The problem is that you can't get accurate memory use readings from top. The reality is that your python program is probably using the same amount of memory on both platforms (in and of itself), but due to the way the memory management OS system works, the usage is being reported differently on BSD. Basically you're seeing the memory footprint of the python executable, it's data (your program) and also all of the shared libraries that python is linked to. Of course the shared libraries are shared, so it's not like python's using all this memory just itself. > > Any idea why the memory utilization is so much higher under OpenBSD? > > What I also find interesting is that the OpenBSD box seems to grind to a > halt (that's probably due to swapping since there's 500M of swap space > in use). Those processes should both be over 90% since they are CPU > bound, and they are that way at the start of the run. Gradually, the > system % creeps up as does idle, but there's no reason for them to be > idle. It's a CPU bound process. (While I'm typing this top is showing > cpu rats of 63% and 41% for the two jobs). I can't answer your questions or solve your problem. But I just wanted to point out that the problem is likely somewhere besides python itself. Maybe there are settings in the OS. Who knows. My guess is the difference in overall memory footprint is due to differences in the C library and its dependencies. You probably would want to bring this issue up on the OpenBSD lists as it's clear that your BSD machine is having problems generally (trashing to death). This doesn't appear to be a python problem. > > TIA, > nazgul From vsapre80 at gmail.com Wed Jul 11 04:21:48 2007 From: vsapre80 at gmail.com (Vishal) Date: Wed, 11 Jul 2007 08:21:48 -0000 Subject: binascii.unhexlify ... not clear about usage, and output In-Reply-To: References: <1180511251.625790.280260@h2g2000hsg.googlegroups.com> Message-ID: <1184142108.846958.189080@k79g2000hse.googlegroups.com> On May 30, 1:31 pm, Peter Otten <__pete... at web.de> wrote: > Vishal wrote: > > I have a file with a long list of hex characters, and I want to get a > > file with corresponding binary characters > > > here's what I did: > > >>>> import binascii > >>>> f1 = 'c:\\temp\\allhex.txt' > >>>> f2 = 'c:\\temp\\allbin.txt' > >>>> sf = open(f1, 'rU') > >>>> df = open(f2, 'w') > >>>> slines = sf.readlines() > >>>> for line in slines: > > ... x = line.rstrip('\n') > > ... y = binascii.unhexlify(x) > > ... df.write(y) > > ... > >>>> df.close() > >>>> sf.close() > > Your code is OK, but you have to open f2 in binary mode if your data is > truly binary (an image, say). > > > But what I get is all garbage, atleast textpad and notepad show that > > I tried doing it for only one string, and this is what I am seeing on > > the interpreter: > > >>>> x > > '0164' > >>>> y > > '\x01d' > > > I was expecting 'y' would come out as a string with binary > > characters!!! > > What are "binary characters"? > > > What am i missing here? Can someone please help. > > What /exactly/ did you expect? Note that "\x01d" and "\x01\x64" are just > different renderings of the same string chr(0x01) + chr(0x64). > > Peter Thanks Peter for the explanation. Actually what I want is: if Input is 0x0164, Output should be: 0000000101100100 where each nibble is separated and the output appears in terms of '0's and '1's. Can I do that with this function binascii.unhexlify()??? Thanks and best regards, Vishal From branko.petrovic at gmail.com Wed Jul 25 06:02:46 2007 From: branko.petrovic at gmail.com (branko.petrovic at gmail.com) Date: Wed, 25 Jul 2007 03:02:46 -0700 Subject: How to create a single executable of a Python program In-Reply-To: <1185347439.951960.126120@o61g2000hsh.googlegroups.com> References: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> <1185347439.951960.126120@o61g2000hsh.googlegroups.com> Message-ID: <1185357766.057216.262670@w3g2000hsg.googlegroups.com> On Jul 25, 9:10 am, hong2221 wrote: > On Jul 25, 2:34 am, NicolasG wrote: > > > Dear fellows, > > > I'm trying to create a executable file using py2exe . Unfortunately > > along with the python executable file it also creates some other files > > that are needed in order to the executable be able to run in a system > > that doesn't have Python installed. Can some one guide me on how can I > > merge all this files created by py2exe in a single exe file ? If I > > have a python program that uses an image file I don't want this image > > file to be exposed in the folder but only to be accessible through the > > program flow.. > > > Regards, > > Nicolas. > > I would like to konw as well. Thanks. Check PyInstaller (http://pyinstaller.python-hosting.com) From garyrafter at gmail.com Fri Jul 20 06:40:53 2007 From: garyrafter at gmail.com (Gary RAF) Date: Fri, 20 Jul 2007 03:40:53 -0700 Subject: =?utf-8?B?4peZ4pa6V2F0Y2ggRlJFRSBTYXRlbGxpdGUgVFYgb24geW91ciBQQ+KXhOKXmQ==?= Message-ID: <1184928053.126237.95220@j4g2000prf.googlegroups.com> Instantly Turn your Computer into a Super TV ? Watch all your favorite shows on your Computer & TV! ? Channels you can?t get any other place in the U.S.A! ? Watch from anywhere in the world! ? Save 1000's of $$$ over many years on cable and satellite bills ? INSTANT DOWNLOAD ? And much, much more! For More Details: http://tv-pc.xt.cx From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 10 06:52:52 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 10 Jul 2007 12:52:52 +0200 Subject: accessing an object instance by only having one of its attribute values In-Reply-To: <1183944576.702579.302150@g4g2000hsf.googlegroups.com> References: <1183918727.033724.213010@22g2000hsm.googlegroups.com> <1183921865.879071.172730@n2g2000hse.googlegroups.com> <1183940993.096789.148950@22g2000hsm.googlegroups.com> <1183944576.702579.302150@g4g2000hsf.googlegroups.com> Message-ID: <469364ed$0$26045$426a74cc@news.free.fr> mshiltonj a ?crit : > On Jul 8, 8:29 pm, Paul McGuire wrote: >> On Jul 8, 2:11 pm, mshiltonj wrote: > >> I have some comments on the Pythonicity of your suggestions. Same >> assumption, object attr is a unique key of some sort. How to create >> the dict of objects, and how to retrieve an object by key. >> >> -- Paul > > I was probably being overly helpful, in a bad way. I'm new to python, > I'm not very pythonic yet, and still learning the python idioms. > > Not sure why I slipped into the habit of testing for None, though. :-( > > Probably a perl thing, where I'm regularly testing for defined-ness. > "if ($foo)" is different than "if (defined $foo)" I'm not sure about the exact meaning of "defined-ness" in Perl, but in Python, trying to access a non-existing name - which is not the same thing as a name bound to None - will raise a NameError. And while we're at it, you definitively don't need the parens around the test. From maxkhesin at gmail.com Sun Jul 15 00:35:12 2007 From: maxkhesin at gmail.com (xamdam) Date: Sun, 15 Jul 2007 04:35:12 -0000 Subject: zipfile 2GB problems? Message-ID: <1184474112.081258.111490@n60g2000hse.googlegroups.com> Hi fellas, I am experiencing problems reading a 2GB zipfile consisting of multiple zipped files. I found a thread http://mail.python.org/pipermail/python-dev/2005-April/053027.html that mentions a problem on the writing side, does such a problem exist on a reading side? I am using 2.4.1, perhaps there is a fix in a later version? From noamtm at gmail.com Sun Jul 22 06:22:17 2007 From: noamtm at gmail.com (noamtm) Date: Sun, 22 Jul 2007 03:22:17 -0700 Subject: ignoring a part of returned tuples In-Reply-To: <5f1ngiF3a62csU2@mid.uni-berlin.de> References: <1183536536.324939.236910@c77g2000hse.googlegroups.com> <468b5a9d$0$2228$426a74cc@news.free.fr> <1183551901.590528.225940@n2g2000hse.googlegroups.com> <5f1ngiF3a62csU2@mid.uni-berlin.de> Message-ID: <1185099737.134255.95080@n2g2000hse.googlegroups.com> > Pylint also "allows" the name `dummy` without complaining. That makes it > even clearer and doesn't clash with the meaning of `_` when `gettext` is > used. Thanks, that's even better! Noam. From greg at cosc.canterbury.ac.nz Sat Jul 14 21:26:51 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sun, 15 Jul 2007 13:26:51 +1200 Subject: Circular import problem In-Reply-To: <1184435045.834596.97600@o61g2000hsh.googlegroups.com> References: <1184294176.550267.119980@n60g2000hse.googlegroups.com> <1184343897.111992.107880@g4g2000hsf.googlegroups.com> <1184435045.834596.97600@o61g2000hsh.googlegroups.com> Message-ID: <5ftbljF3d8me1U1@mid.individual.net> bvdp wrote: > before I moved other > imports around I was able to do the following: > > 1. NOT include MMA.gooves, > 2. call the function MMA.grooves.somefunc() > > and have it work. The import doesn't necessarily have to be in the same module where the attribute is used. The first time *any* module does 'import MMA.grooves', a grooves attribute gets put into MMA, which can be used by any module that has a reference to MMA. It's probably not a good idea to rely on this, though, and better to put an explicit 'import MMA.grooves' into every module that uses it. Importing something more than once does no harm. -- Greg From jjl at pobox.com Tue Jul 10 19:51:24 2007 From: jjl at pobox.com (John J. Lee) Date: Tue, 10 Jul 2007 23:51:24 GMT Subject: socket.makefile() buggy? References: <1183892789.434028.15370@x35g2000prf.googlegroups.com> <1183970531.241008.295940@z28g2000prd.googlegroups.com> Message-ID: <87ps2zes1v.fsf@pobox.com> Steve Holden writes: > ahlongxp wrote: >> On Jul 8, 9:54 pm, Steve Holden wrote: >>> That's a pretty pejorative subject line for someone who's been >>> programming Python [guessing by the date of your first post] for about a >>> month. >>> > [...] >> And last but not least, I' here to be helped and help as long as I >> can. >> But as you noticed I'm not very good at expressing myself in English. >> I didn't mean to offense anyone but I might seem to be rude or >> offensive. >> I hope you can understand. >> > Sure. I felt it necessary to explain my remarks as my own remarks > seemed potentially rude or offensive. Naturally not everyone has > English as a first language, but your first post was good enough that > it wasn't immediately obvious in your case. This is the danger in getting too good at another language :-) ahlongxp, maybe you should drop some deliberate mistakes in your too-good English ;-) And FWLIW, I'd be less surprised than Steve at your finding a real bug in Python's socket code... John From martin at v.loewis.de Sun Jul 1 16:01:54 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 01 Jul 2007 22:01:54 +0200 Subject: object references/memory access In-Reply-To: <1183318690.661279.256900@n2g2000hse.googlegroups.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> Message-ID: <46880833$0$1887$9b622d9e@news.freenet.de> > I guess now I'd like to know what are good practices in general to get > better results with sockets on the same local machine. I'm only > instantiating two sockets total right now - one client and one server, > and the transfer is taking 15 seconds for only 8.3MB. It would be good if you had showed the code that does that. It is hard for us to guess what programming error you have made. As you won't show code, I will. Please try the attached cli.py and server.py on your machine, and report the timing. On my machine, I get 0.00105595588684 0.076632976532 8300000 which means I can transmit 8.3MB in 76ms, which is a lot less than 15s. My guess is that you sum up the incoming data with total_data += received_data That is O(n**2). Regards, Martin -------------- next part -------------- A non-text attachment was scrubbed... Name: cli.py Type: text/x-python Size: 329 bytes Desc: not available URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: server.py Type: text/x-python Size: 192 bytes Desc: not available URL: From kw at codebykevin.com Wed Jul 11 10:49:41 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 11 Jul 2007 10:49:41 -0400 Subject: wxPython vs. Tkinter event loops Message-ID: <392e8$4694ee0a$4275d90a$27942@FUSE.NET> I'm porting a Tkinter application to wxPython and had a question about wxPython's event loop. The Tkinter app provides a GUI to a command-line tool. It gathers user input, and opens an asynchronous pipe to the external tool via os.popen(). Then, it dumps the output from the external process into a text display. Although threads are often recommended for use with GUI apps, I am able to keep the GUI responsive with Tkinter's event loop, i.e. with regular calls to self.update(); I am still able to update the GUI as needed. When I tried the same functions using threads, I noticed no measurable improvement in application responsiveness or performance. Thus, the application currently runs in a single thread and is updated via Tkinter's event loop only. Does wxPython's event loop function as smoothly as Tkinter's with an asynchronous process, i.e. is the wx.UpdateUIEvent() class analogous to Tkinter.update(), or are threads absoutely essential to keeping a wx GUI updated with a long-running background process? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From memracom at yahoo.com Sun Jul 22 16:17:46 2007 From: memracom at yahoo.com (memracom at yahoo.com) Date: Sun, 22 Jul 2007 13:17:46 -0700 Subject: best SOAP module In-Reply-To: References: Message-ID: <1185135466.351975.304830@n60g2000hse.googlegroups.com> On 18 Jul, 14:02, "Sells, Fred" wrote: > I need to talk to a vendor side via SOAP, Googling is overwhelming and many > hits seem to point to older attempts. > > Can someone tell me which SOAP module is recommended. I'm using Python 2.4. If you are doing this inside the enterprise then you should probably be using ZSI from the Python Web Services project. I've used this one successfully with my company's Web21C sdk to send SMS messages. http://pywebsvcs.sourceforge.net/ Here's the Web21C site if you are interested http://sdk.bt.com/ --Michael Dillon From Graham.Dumpleton at gmail.com Sun Jul 29 19:28:45 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 29 Jul 2007 23:28:45 -0000 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1185727058.306635.203130@b79g2000hse.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> <1184458002.961657.267830@x35g2000prf.googlegroups.com> <1184466882.446791.127670@x35g2000prf.googlegroups.com> <1185658013.859359.47700@57g2000hsv.googlegroups.com> <1185703671.241103.124780@g12g2000prg.googlegroups.com> <1185727058.306635.203130@b79g2000hse.googlegroups.com> Message-ID: <1185751725.882668.269850@i13g2000prf.googlegroups.com> On Jul 30, 2:37 am, 7stud wrote: > On Jul 29, 4:07 am, Graham Dumpleton > wrote: > > > Have you got an appropriate LoadModule directive in Apache > > configuration to load the mod_python module? That you get this error > > is indicative of mod_python module not being loaded. You can check the > > Apache error logs to see if mod_python got loaded. > > > See: > > > http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking > > > for more help on debugging. > > That article says the LoadModule directive should be: > > >LoadModule python_module libexec/mod_python.so > > I saw this note in /Library/Apache2/conf/http.conf > > # Configuration and logfile names: If the filenames you specify for > many > # of the server's control files begin with "/" (or "drive:/" for > Win32), the > # server will use that explicit path. If the filenames do *not* begin > # with "/", the value of ServerRoot is prepended -- so "logs/foo.log" > # with ServerRoot set to "/Library/Apache2" will be interpreted by the > # server as "/Library/Apache2/logs/foo.log". > > I have this server root in /Library/Apache2/conf/httpd.conf: > > ServerRoot "/Library/Apache2" > > So in the Load Module directive, the actual path to the mod_python.so > file is: > > /Library/Apache2/libexec/mod_python.so > > But I checked and I don't have a /Library/Apache2/libexec directory. Run 'apxs' for the version of Apache you are using to work out what the actual modules directory should be: $ /usr/local/apache-2.2.4/bin/apxs -q LIBEXECDIR /usr/local/apache-2.2.4/modules If there is no mod_python.so in there then you can't have done the mod_python install properly. Go back to the mod_python source code and rerun: sudo make install_dso When you do that it will even tell you exactly what the LoadModule line you should use is. Also ensure you actually installed the Python module components of mod_python. You can redo that by running: sudo make install_py_lib Graham From http Fri Jul 27 18:55:30 2007 From: http (Paul Rubin) Date: 27 Jul 2007 15:55:30 -0700 Subject: problem with change to exceptions References: Message-ID: <7xd4ydv4m5.fsf@ruckus.brouhaha.com> Neal Becker writes: > TypeError: 'NoneType' object is not iterable > I'll have to say, I don't understand this error. It's "lame duck typing". The .args attribute on an Exception instance is expected to be a tuple of the arguments passed through the raise statement. It is None if no args were passed. From samwyse at gmail.com Fri Jul 13 16:20:35 2007 From: samwyse at gmail.com (samwyse) Date: Fri, 13 Jul 2007 20:20:35 -0000 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: <1184358035.463086.189150@o61g2000hsh.googlegroups.com> On Jul 13, 1:05 pm, Chris Carlen wrote: > John Nagle wrote: > > Chris Carlen wrote:[edit] > >> Hence, being a hardware designer rather than a computer scientist, I > >> am conditioned to think like a machine. I think this is the main > >> reason why OOP has always repelled me. > > > Why? > > When pointers were first explined to me, I went "Ok." And rather > quickly ideas lit up in my head about what I could do with them. > > When I read what OOP is, that doesn't happen. All I think is "what's > the point of this?" "What can this do for me that I can do already with > the procedural way of thinking?" And if it can't do anything new, then > why rearrange my thinking to a new terminology? It's results that > matter, not the paradigm. What can this do for me that I can do already with the procedural way of thinking? Absolutely nothing; it's all Turing machines under the hood. Why rearrange my thinking to a new terminology? Because new terminologies matter a lot. There's nothing that you can do with pointers that can't be done with arrays; I know because I wrote a lot of FORTRAN 77 code back in the day, and withouy pointers I had to write my own memory allocation routines that worked off of a really big array. Likewise, there's nothing that you can do in C that can't be done with C++ (especially since C++ was originally a preprocessor for C); however C++ will keep track of a lot of low-level detail for you so you don't have to think about it. Let's say that you have an embedded single-board computer with a serial and a parallel port. You probably have two different routines that you use to talk to them, and you have to always keep track which you are using at any given time. It's a lot easier to have a single CommPort virtual class that you use in all of your code, and then have two sub-classes, one for serial ports and one for parallel. You'll be especially happy for this when someone decides that as well as logging trace information to a printer, it would be nice to also log it to a technician's handhelp diagnostic device. From horpner at yahoo.com Mon Jul 30 10:10:55 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 30 Jul 2007 14:10:55 GMT Subject: Detecting __future__ features References: <1185800016.950517.43240@g4g2000hsf.googlegroups.com> <5h68ggF3idk61U1@mid.uni-berlin.de> Message-ID: On 2007-07-30, Diez B. Roggisch wrote: > Making the switch between different parser-implementations on > the fly isn't technically impossible - but really, really, > really complicated. But then, if it's lameness sucks so much, > you might wanna take a stab at it? I was considering the following specific quote: What if you are designing a module meant to be imported, and used by other programs over which you have no control? You can't use "from __future__ import" in your module." If that were true, I think it would indeed be lame. Of course, it isn't true, right? -- Neil Cerutti From william.peterson at mchsi.com Fri Jul 27 11:41:06 2007 From: william.peterson at mchsi.com (Bill) Date: Fri, 27 Jul 2007 08:41:06 -0700 Subject: OOP in Python book? Message-ID: <1185550866.950455.61240@g12g2000prg.googlegroups.com> Does anyone out there have any information about this book. It's listed on Amazon to be published in November of this year. A simple Google search (1st page only) doesn't show anything useful, and I can't find a reference on the web sites of the authors. Neither of the authors appears to be heavily into OOP theory, just some CS areas that I don't understand. I'm particularly interested in why this book is worth the $100 tag that Amazon shows. TIA, Bill From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Jul 22 06:28:54 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 22 Jul 2007 12:28:54 +0200 Subject: Advice on sending images to clients over network References: <1185095666.627415.108450@w3g2000hsg.googlegroups.com> Message-ID: <5ggpr6F3fnqlgU1@mid.individual.net> Frank Millman wrote: > My question is, what is the best way to get the image to the > client? IMHO, HTTP would be most painless. Either incorporate a little HTTP server into your server application, or use a seperate daemon and let the server only output HTTP links. > My third thought was to set up a separate 'image server'. It would > be another server program written in Python, listening on its own > port number, waiting for a client request for a particular image. > It would know where to find it, read it in, and send it to the > client. Then all the client needs to know is the ip address and > port number. See above -- you could also write your own HTTP server. Best using Twisted or something of similar high level. Why make yourself work developing such a system when somebody already did it for you? > I guess the point of all this rambling is that my thought process > is leading me towards my third option, but this would be a bit of > work to set up, so I would appreciate any comments from anyone who > has been down this road before - do I make sense, or are there > better ways to handle this? For minimum additional work, I'd use some lightweight http daemon, like lighttpd ot thttpd. Then your server can pass links like and the clients can use well-tested standard library routines to retrieve the image. Regards, Bj?rn -- BOFH excuse #174: Backbone adjustment From westymatt at gmail.com Fri Jul 13 17:15:03 2007 From: westymatt at gmail.com (matt westerburg) Date: Fri, 13 Jul 2007 16:15:03 -0500 Subject: Can a low-level programmer learn OOP? In-Reply-To: <4b490f2f0707131408l10f3665ahd4d62952ac2b0f26@mail.gmail.com> References: <4b490f2f0707131408l10f3665ahd4d62952ac2b0f26@mail.gmail.com> Message-ID: <4b490f2f0707131415n52fc8b7t254355f0d5136d94@mail.gmail.com> On 7/13/07, matt westerburg wrote: > > I also come from a low level background (assembly and c) and I struggled > with object oriented programming. People talk about procedural languages or > designs and object oriented languages or designs. But after the interpreter > or compiler runs the byte or machine code is procedural always. Object > oriented code changes the structure of how the code is designed. Its merely > a convenient way to logically group similar functions and variables. This > is done in C via header and implementation files. Classes provide a simple > syntax normally for associating many variables and functions inside which > generally achieve a common goal. This class becomes an object that is > manipulatable. > > For example one might want to make a class to centralize their file > operations in a particular program. For instance a logger class for keeping > track of execution. > > class logger: > file = None > def __init__(self): > #code first executed on instantiation of the object > #you must make an instance of a class otherwise its a template > file = open('programx.log', 'w') > > def write_to_log(self, message): > #self is the instance of the class you made its used to internally > reference those variables contained within > # > self.file.write(message) > def close_log(self): > self.file.close() > > The class allows for internal referencing of variables so that the > variables are global to all methods or functions. Like the for example the > file handle to write to. > > OOP is merely an organizational structure that can only be grasped > appropriately by repeated use. > > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Thu Jul 26 14:56:46 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 26 Jul 2007 18:56:46 GMT Subject: is_iterable function. References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> <5uNpi.36822$G23.3430@newsreading01.news.tds.net> <5gs35iF3gbvuoU1@mid.uni-berlin.de> Message-ID: On 2007-07-26, Marc 'BlackJack' Rintsch wrote: > On Thu, 26 Jul 2007 15:02:39 +0000, Neil Cerutti wrote: > >> Based on the discussions in this thread (thanks all for your >> thoughts), I'm settling for: >> >> def is_iterable(obj): >> try: >> iter(obj).next() >> return True >> except TypeError: >> return False >> except KeyError: >> return False >> >> The call to iter will fail for objects that don't support the >> iterator protocol, and the call to next will fail for a >> (hopefully large) subset of the objects that don't support the >> sequence protocol. > > And the `next()` consumes an element if `obj` is not > "re-iterable". Crap. So how best to imlement deeply_mapped? The following still breaks for objects that don't provide __iter__, do provide __getitem__, but don't support the sequence protocol. def deeply_mapped(func, iterable): """ Recursively apply a function to every item in a nested container, recursively descending into items that are iterable. The result is an iterator over the mapped values. Similar to the builtin map function, func may be None, causing the items to returned unchanged. >>> import functools >>> flattened = functools.partial(deeply_mapped, None) >>> list(flattened([[1], [2, 3, []], 4])) [1, 2, 3, 4] >>> list(flattened(((1), (2, 3, ()), 4))) [1, 2, 3, 4] >>> list(flattened([[[[]]], 1, 2, 3, 4])) [1, 2, 3, 4] >>> list(flattened([1, [[[2, 3]], 4]])) [1, 2, 3, 4] >>> def magic(o): ... if o == 3: ... raise TypeError('Three is a magic number') ... return o >>> list(deeply_mapped(magic, [1, [[[2, 3]], 4]])) Traceback (most recent call last): ... TypeError: Three is a magic number """ frame = inspect.currentframe() info = inspect.getframeinfo(frame) filename = info[0] funcname = info[2] for item in iterable: try: for it in deeply_mapped(func, item): if func is None: yield it else: yield func(it) except TypeError: eframe = inspect.trace()[-1] efilename = eframe[1] efuncname = eframe[3] if efilename != filename or efuncname != funcname: raise if func is None: yield item else: yield func(item) -- Neil Cerutti From duncan.booth at invalid.invalid Mon Jul 16 10:03:33 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Jul 2007 14:03:33 GMT Subject: questions about functions inside a function References: Message-ID: "fdu.xiaojf at gmail.com" wrote: > In order to make sure all variables be larger than 0, I tried to created > constraint function like this: > > cons = [] > for i in range(N): > c = lambda x: x[i] - 1e-10 > cons.append(c) > > But when functions in cons are evaluated, the value in all functions are > all the same(N-1, which is the last value of i in the loop). > > What I want is, when functions in cons be evaluated, every function > refers to a different variable in X. So pass i in as a default value: for i in range(N): def c(x, i=i): return x[i] - 1e-10 cons.append(c) From jemnader at gmail.com Fri Jul 6 02:50:47 2007 From: jemnader at gmail.com (jolly) Date: Fri, 06 Jul 2007 06:50:47 -0000 Subject: import Message-ID: <1183704647.460604.102100@e9g2000prf.googlegroups.com> Hey guys, I'm rather new to python and i'm have trouble(as usual) I want to know if it is possible to change where 'import' looks.... this will save me clogging up my python directory Thanks From carsten at uniqsys.com Mon Jul 23 15:24:20 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 23 Jul 2007 15:24:20 -0400 Subject: Maintaining leading zeros with the lstrip string function? In-Reply-To: References: Message-ID: <1185218660.3378.22.camel@dot.uniqsys.com> On Mon, 2007-07-23 at 11:41 -0700, Randy Kreuziger wrote: > I need just the file name from a string containing the path to a file. > The name of the file starts with zeros. This is problematic because > the lstrip function strips them leaving this as the result: > 6128.jpg > > > How do I strip the path without losing the leading zeros in the file > name? > > ?--------------------------------------------- > import sys, os, win32com.client, string > > teststring = 'C:\shoreline\dvd\prep area\800x\\006128.jpg' > print string.lstrip(teststring, 'C:\shoreline\dvd\prep area\800x\\') You're using the wrong tool for the job. lstrip removes any contiguous string consisting of any of the characters in the string you give it. You would have achieved the same wrong result with teststring.lstrip(" 08:C\\adehilnoprsvx") As you have discovered, this hungry caterpillar will eat the leading zeroes of your filename. It doesn't see any difference between the zeroes before the last \ and the zeroes after the last \. It just eats them all. If the leading zeroes had been followed by an 8, it would have eaten that, too. The right tool for the job is os.path, more specifically os.path.basename(teststring). HTH, -- Carsten Haese http://informixdb.sourceforge.net From rkmr.em at gmail.com Sun Jul 29 18:22:47 2007 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Sun, 29 Jul 2007 15:22:47 -0700 Subject: making a variable available in a function from decorator Message-ID: Hi I create a variable in a decorator. i want to be able to access that variable in the function to be decorated. How to do this? thanks From ptmcg at austin.rr.com Fri Jul 13 14:30:16 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 13 Jul 2007 11:30:16 -0700 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> Message-ID: <1184351416.166930.290710@k79g2000hse.googlegroups.com> On Jul 13, 1:20 pm, Wayne Brehaut wrote: > On Mon, 09 Jul 2007 23:51:25 -0700, "mensana... at aol.com" > > > > > > wrote: > >On Jul 9, 11:42?pm, Paul McGuire wrote: > >> On Jul 9, 11:21 pm, "Jim Langston" wrote:> In Python 2.5 on intel, the statement > >> > 2**2**2**2**2 > >> > evaluates to>>> 2**2**2**2**2 > > >> > 200352993040684646497907235156025575044782547556975141926501697371089405955 63114 > >> > 530895061308809333481010382343429072631818229493821188126688695063647615470 29165 > >> > 041871916351587966347219442930927982084309104855990570159318959639524863372 36720 > > >> > > >> Exponentiation is right associative, so this is the same as: > > >> 2**(2**(2**(2**2))) > >> 2**2**2**4 > >> 2**2**16 > >> 2**65536 > > >> 2=10**0.3010, so 2**65536 is approx 10**19726 > > >> There are 19730 digits in your answer, > > >>>> import gmpy > >>>> n = 2**2**2**2**2 > >>>> gmpy.numdigits(n) > >19729 > > >Did you count the 'L'? > > numdigits(n)? > > What? 'L' is a digit in Python? I'm going back to Fortran! > > wwwayne > > > > >>so this seems to be at least in > >> the ball park. > > >> -- Paul- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text - 'L' counts for 50, but only when you use Roman font. -- Paul From Xin.Zheng at jpl.nasa.gov Fri Jul 13 10:40:32 2007 From: Xin.Zheng at jpl.nasa.gov (Jason Zheng) Date: Fri, 13 Jul 2007 07:40:32 -0700 Subject: os.wait() losing child? In-Reply-To: <873azsn6ca.fsf@mulj.homelinux.net> References: <4694903B.8000105@cosc.canterbury.ac.nz> <87bqehg5v1.fsf@mulj.homelinux.net> <873azsn6ca.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > Jason Zheng writes: > >> Hrvoje Niksic wrote: >>>> greg wrote: >>> Actually, it's not that bad. _cleanup only polls the instances that >>> are no longer referenced by user code, but still running. If you hang >>> on to Popen instances, they won't be added to _active, and __init__ >>> won't reap them (_active is only populated from Popen.__del__). >>> >> Perhaps that's the difference between Python 2.4 and 2.5. > [...] >> Nope it still doesn't work. I'm running python 2.4.4, tho. > > That explains it, then, and also why greg's code didn't work. You > still have the option to try to run 2.5's subprocess.py under 2.4. Is it more convenient to just inherit the Popen class? I'm concerned about portability of my code. It will be run on multiple machines with mixed Python 2.4 and 2.5 environments. From bj_666 at gmx.net Fri Jul 27 08:49:35 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jul 2007 12:49:35 GMT Subject: Filtering content of a text file References: <1185528507.750436.91140@j4g2000prf.googlegroups.com> Message-ID: <5gu7uuF3i0lfsU4@mid.uni-berlin.de> On Fri, 27 Jul 2007 02:28:27 -0700, Ira.Kovac wrote: > I am working with 30K+ record datasets in flat file format (.txt) that > look like this: > > //-+alibaba sinage > //-+amra damian//_9 > //-+anix anire//_ > //-+borom > //-+bokima sun drane > //-+ciren > //-+cop calestieon eded > //-+ciciban > //-+drago kimano sole The example seems to be sorted, is this true for the real data too? And are there records that don't start with a-z or 0-9? > a) By looping thru the file the program should isolate all records > that have letter a following the //-+ > b) The isolated dataset will contain only records that start with //- > +a > c) Save the isolated dataset as flat flat text file named a.txt > d) Repeat a), b) and c) for all letters of english alphabet (a thru z) > and numerical values (0 thru 9) This might be a little bit inefficient because the file gets read 36 times. If the data is already sorted you can use `itertools.groupby()` to get the groups and write them to several files. Otherwise if the files can be read into memory completely you can sort in memory and then use `itertools.groupby()`. Ciao, Marc 'BlackJack' Rintsch From nospam.themindstorm at gmail.com Thu Jul 26 06:32:47 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Thu, 26 Jul 2007 10:32:47 +0000 (UTC) Subject: Singleton in Python Cookbook References: <46a7c363$0$19625$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote in news:46a7c363$0$19625$426a34cc at news.free.fr: > Alex Popescu a ?crit : > > [snip...] > > > I don't have the book, so if you don't post the code, I just give up > trying to guess what the problem can be. I've sent the original code and 2 different variants a long time ago. ./alex -- .w( the_mindstorm )p. From dickey at saltmine.radix.net Sun Jul 22 17:39:10 2007 From: dickey at saltmine.radix.net (Thomas Dickey) Date: Sun, 22 Jul 2007 21:39:10 -0000 Subject: web page text extractor References: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> <1184248086.912636.254980@q75g2000hsh.googlegroups.com> Message-ID: <13a7jjuq99v3820@corp.supernews.com> Miki wrote: > (You can find lynx at http://lynx.browser.org/) not exactly - The current version of lynx is 2.8.6 It's available at http://lynx.isc.org/lynx2.8.6/ 2.8.7 Development & patches: http://lynx.isc.org/current/index.html -- Thomas E. Dickey http://invisible-island.net ftp://invisible-island.net From harry.g.george at boeing.com Thu Jul 19 01:10:22 2007 From: harry.g.george at boeing.com (Harry George) Date: Thu, 19 Jul 2007 05:10:22 GMT Subject: Issue with CSV References: <1184804753.810201.72150@x40g2000prg.googlegroups.com> Message-ID: Rohan writes: > Hello, > I'm working on a script which collects some data and puts into a csv > file which could be exported to excel. > so far so good, I'm able to do what I described. > When I run the script for the second time after a certain period of > time the results should appear next to the results of the last run, > I'm unable to make a new column when the script is run after the first > time. > Ideally I would like to have an output which looks like this. > 1/20 1/27 > we.py we.py > gh.py gj.py <- Indicating tht the file has changed > fg.py fg.py > > Please help me out. > Thanks > We'd need to see code to tell what you are doing wrong. The solution is pretty obvious: 1. Model the needed structure, which is a 2D matrix of script x date. Assuming the above output is the nromal case, this can be done with a list of rows, each of which has a list of entries by date. 2. Write reader code which reads a csv and loads it into this structure. 3. Write writer code which writes this structure out to csv. 4. Write orchestration code to a) read the old csv, b) check the loaded structure's data against the new data-on-disk to find changed files, c) update the structure appropriately, d) write out the resulting new csv. -- Harry George PLM Engineering Architecture From nuno at salgado.ws Thu Jul 12 20:05:42 2007 From: nuno at salgado.ws (nuno at salgado.ws) Date: Thu, 12 Jul 2007 17:05:42 -0700 Subject: diferent answers with isalpha() Message-ID: <1184285142.547758.57760@22g2000hsm.googlegroups.com> Hi, I have python with sys.version_info = (2, 4, 4, 'final', 0) In Idle when I do print '?'.isalpha() I get True. When I make and execute a script file with the same code I get False. Why do I have diferent answers ? Thank you From hhartwig at gmail.com Thu Jul 5 12:17:03 2007 From: hhartwig at gmail.com (Hardy) Date: Thu, 05 Jul 2007 09:17:03 -0700 Subject: list.append not working? In-Reply-To: <1183651638.584640.300240@a26g2000pre.googlegroups.com> References: <1183651138.209079.37620@q75g2000hsh.googlegroups.com> <1183651638.584640.300240@a26g2000pre.googlegroups.com> Message-ID: <1183652223.493657.274290@g4g2000hsf.googlegroups.com> On 5 Jul., 18:07, infidel wrote: > On Jul 5, 8:58 am, Hardy wrote: > > > > > I experience a problem with append(). This is a part of my code: > > > for entity in temp: > > md['module']= entity.addr.get('module') > > md['id']=entity.addr.get('id') > > md['type']=entity.addr.get('type') > > #print md > > mbusentities.append(md) > > #print mbusentities > > > I want something like: [{'module': 'home', 'id': 123, 'type': 'core'}, > > {'module': 'work', 'id': 456, 'type': 'core'}] > > md is always correct, BUT:mbusentities is wrong. Length of > > mbusentities is same of temp, so it appended everything. BUT: > > mbusentities only shows the values of the last append: [{'module': > > 'work', 'id': 456, 'type': 'core'}, {'module': 'work', 'id': 456, > > 'type': 'core'}] > > > What's wrong? > > You're reusing the same "md" dictionary over and over, appending the > same object to the list each time. So what you have is a list of > references to the same dictionary. You need to set md = {} first > thing each iteration. Thanks, that was my mistake, should take a break, getting code-blind :D From sjmachin at lexicon.net Fri Jul 6 19:52:43 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 06 Jul 2007 16:52:43 -0700 Subject: ImportError: "No Module named xxx" In-Reply-To: <1183757873.958122.238780@g4g2000hsf.googlegroups.com> References: <1183750316.740239.257010@m36g2000hse.googlegroups.com> <1183750738.308894.261750@c77g2000hse.googlegroups.com> <5f7p2eF3bm6tuU1@mid.individual.net> <1183757873.958122.238780@g4g2000hsf.googlegroups.com> Message-ID: <1183765963.612499.153710@e9g2000prf.googlegroups.com> On Jul 7, 7:37 am, Robert Dailey wrote: > On Jul 6, 4:04 pm, Bjoern Schliessmann > > > mail-0306.20.chr0n... at spamgourmet.com> wrote: > > Robert Dailey wrote: > > > The description of -m is confusing in the documentation, what does > > > it really do? > > > IMHO, it's quite clear. What's unclear with this description: > > > -m module-name Searches sys.path for the named module and runs > > the corresponding .py file as a script. > > > Perhaps the confusing part is their definition of "Script". "They" have not provided a definition of "script", confusing or otherwise. "runs ... as a script" means like what happens when you do this: python compile.py > I figured > any .py file was a "python script", in that it has code to execute- > making it a script. Not necessarily; a .py file can be intended solely for import, and would do nothing useful/visible if executed as a script. However, back to your problem ...... The documentation for -m says "module-name". The error message says "No module named compile.py". The name of the module is "compile", not "compile.py". If you are desperate to use the -m option, do this: python -m compile From nospam.themindstorm at gmail.com Sun Jul 29 11:34:49 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Sun, 29 Jul 2007 15:34:49 +0000 (UTC) Subject: replacement for execfile References: Message-ID: "Steven D'Aprano" wrote in news:pan.2007.07.29.03.39.34.703168 at REMOVE.THIS.cybersource.com.au: > On Sat, 28 Jul 2007 15:17:56 +0000, Alex Popescu wrote: > >> Hi all! >> >> From another thread (and the pointed PEP) I have found that execfile >> will not be present in Py3k. So, I am wondering what will be its >> replacement? Considering that most probably Py3k will keep eval and >> exec, this will still be possible (indeed requiring manual loading of >> the file string), so I would really appreciate some enlightning >> comments on this. > > (1) Don't use eval, exec or execfile. > > (2) If you're an expert, don't use eval, exec or execfile. > > (3) If you're an expert, and are fully aware of the security risks, > don't use eval, exec or execfile. > > (4) If you're an expert, and are fully aware of the security risks, > and have a task that can only be solved by using eval, exec or > execfile, find another solution. > > (5) If there really is no other solution, you haven't looked hard > enough. > > (6) If you've looked REALLY hard, and can't find another solution, AND > you're an expert and are fully aware of the security risks, THEN you > can think about using eval, exec or execfile. > Most probably I don't fit any of the aboves... but I still think that the approach I am considering is quite correct :-). > >> Background: >> Basically this question is related to my learning process/working >> project. In this, I have the need to allow the final user to provide >> a configuration like script, but built using my API (and whatever >> other normal Python code they want). > > I hope this is running on their own computer, not yours. > > If they're running it on a multi-user system, I hope they don't care > about security, because they probably don't have any now. > Yes, the framework will be run by dev teams on their own computers, so if somebody from that team would really want to rm something they will not really need python scripts for it :-). >> as I was able to automatically expose the API (so the end user >> doesn't need to bother about imports) and also easily execute it in >> the context I wanted. > > Let's see that I understand you... you're expecting the users to write > working Python code, but you think "import module" is too hard for > them? That was just a cherry on the cake. The most important part is that through this mechanism the user will be able to configure the framework through normal Python code (very simple API: 3 functions), and not through .ini, .xml or other variants. > > Anyway, with all the disclaimers above, execfile is trivial: > > > def execfile_(filename, globals_=None, locals_=None): > if globals_ is None: > globals_ = globals() > if locals_ is None: > locals_ = globals_ > text = file(filename, 'r').read() > exec text in globals_, locals_ > Thanks for confirming my idea. But the question stands: even if I can write myself an execfile equivalent, the same can apply to map, zip and other functions that are provided by Python core. To bring it to the extreme everything can be done at asm level, but we are chosing to use high level languages. And for the moment I fail to see the reasons to remove this function. ./alex -- .w( the_mindstorm )p. PS: I am (almost) never trying to create flamewars, but usually I really love to understand things before I can start feeling at ease:-). From evan at yelp.com Sun Jul 8 21:32:25 2007 From: evan at yelp.com (Evan Klitzke) Date: Sun, 8 Jul 2007 18:32:25 -0700 Subject: What is the most efficient way to test for False in a list? In-Reply-To: <1183938194.761283.97950@57g2000hsv.googlegroups.com> References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> Message-ID: On 7/8/07, lex wrote: > Of course there is the always the iteration method: > > list = [1, True, True, False, False, True] > status = True > for each in list: > status = status and each > > but what is your best way to test for for False in a list? In general, you can just do: if something in list: do_something() -- Evan Klitzke From exarkun at divmod.com Mon Jul 30 10:52:37 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 30 Jul 2007 10:52:37 -0400 Subject: File handle not being released by close In-Reply-To: <1185806160.161748.58910@d55g2000hsg.googlegroups.com> Message-ID: <20070730145237.4947.54975182.divmod.quotient.16659@ohm> On Mon, 30 Jul 2007 07:36:00 -0700, bg_ie at yahoo.com wrote: >Hi, > > [snip] > f=open(fileBeginning+".tmp", 'w') > f.write("Hello") > f.close > You forgot to call close. Try this final line, instead: f.close() Jean-Paul From aleax at mac.com Sat Jul 21 10:37:12 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 21 Jul 2007 07:37:12 -0700 Subject: Pythonic way for missing dict keys References: Message-ID: <1i1kmx4.1k0py031447jtmN%aleax@mac.com> Carsten Haese wrote: > On Sat, 21 Jul 2007 09:22:32 +0530, Rustom Mody wrote > > Can someone who knows about python internals throw some light on why > > >>> x in dic > > is cheaper than > > >>> dic.has_key(x) > > > > ?? > > I won't claim to know Python internals, but compiling and disassembling the > expressions in question reveals the reason: > > >>> from compiler import compile > >>> from dis import dis > >>> dis(compile("dic.has_key(x)","","eval")) > 1 0 LOAD_NAME 0 (dic) > 3 LOAD_ATTR 1 (has_key) > 6 LOAD_NAME 2 (x) > 9 CALL_FUNCTION 1 > 12 RETURN_VALUE > >>> dis(compile("x in dic","","eval")) > 1 0 LOAD_NAME 0 (x) > 3 LOAD_NAME 1 (dic) > 6 COMPARE_OP 6 (in) > 9 RETURN_VALUE > > "dic.has_key(x)" goes through an attribute lookup to find the function that > looks for the key. "x in dic" finds the function more directly. Yup, it's mostly that, as microbenchmarking can confirm: brain:~ alex$ python -mtimeit -s'd={}; f=d.has_key' 'f(23)' 10000000 loops, best of 3: 0.146 usec per loop brain:~ alex$ python -mtimeit -s'd={}; f=d.has_key' '23 in d' 10000000 loops, best of 3: 0.142 usec per loop brain:~ alex$ python -mtimeit -s'd={}; f=d.has_key' 'f(23)' 10000000 loops, best of 3: 0.146 usec per loop brain:~ alex$ python -mtimeit -s'd={}; f=d.has_key' '23 in d' 10000000 loops, best of 3: 0.142 usec per loop brain:~ alex$ python -mtimeit -s'd={}; f=d.has_key' 'd.has_key(23)' 1000000 loops, best of 3: 0.278 usec per loop brain:~ alex$ python -mtimeit -s'd={}; f=d.has_key' 'd.has_key(23)' 1000000 loops, best of 3: 0.275 usec per loop the in operator still appears to have a tiny repeatable advantage (about 4 nanoseconds on my laptop) wrt even the hoisted method, but the non-hoisted method, due to repeated lookup, is almost twice as slow (over 100 nanoseconds penalty, on my laptop). Alex From tinaweb at bestemselv.com Fri Jul 27 06:35:08 2007 From: tinaweb at bestemselv.com (Tina I) Date: Fri, 27 Jul 2007 12:35:08 +0200 Subject: Submit form, open result in a browser In-Reply-To: <1185530031.986538.270490@m37g2000prh.googlegroups.com> References: <1185530031.986538.270490@m37g2000prh.googlegroups.com> Message-ID: theju wrote: >> Is there a way to submit a form and then open the resulting page in the >> default browser? (Writing the form submission code is not a problem by >> the way) > > There is a library called "Client Form" that does this for you. > wwwsearch.sourceforge.net/ClientForm/ > > After the form is submitted through ClientForm open the resulting > response using the webbrowser module. > > Cheers > Thejaswi Puthraya > ClientForm is absolutely perfect! Less than 10 lines of extra code and the job is done :) Thanks! Tina From solonlee at comcast.net Wed Jul 11 09:38:31 2007 From: solonlee at comcast.net (solonlee at comcast.net) Date: Wed, 11 Jul 2007 13:38:31 +0000 Subject: python and Test Director Message-ID: <071120071338.5582.4694DD570003C13E000015CE22155934140A0A04020104019C@comcast.net> Hello, I have sent this similar email via another email address before I have registered with this email address, so the previous one may be rejected. I am sending agian via this newly established email address of mine. I am working on a project to translate Procomm to .py scripts, but the buttom line is to drive this .py test scripts via Test Dorector, can anyone guide me how to do it or refer me to some materials to read?I also heard which I am not sure if it's true or not that Test Director can work only with python 2.2 or below, if that's the case, what to do with python 2.4 that I am using now? Can I use WinRunner in between (python and Test Director), I don't know how this will work either. Thanks a lot!! Solon Lee -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Jul 13 21:20:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jul 2007 22:20:06 -0300 Subject: Understanding python functions - Instant Python tutorial References: <878x9kkeif.fsf@benfinney.id.au> Message-ID: En Fri, 13 Jul 2007 13:41:39 -0300, Chris Carlen escribi?: > Ben Finney wrote: >> Some languages have "variables", which act like boxes that have names >> etched on the side. Once created, the box can contain an object, and >> it can be inspected while in the box; to change the variable, you >> throw out the object and put a different object in the same box. > > Yes, so y = x takes a copy of the stuff in the x box and puts it in the > y box. Which is what really happens in the hardware. At least on some hardware, yes. Python namespaces are more like associative memories: you bind a tag (name) to a value, they have constant access time... But the real gain comes when you don't have to explicitely think step by step on *how* to do things, and can concentrate on a more abstract layer and say *what* you want to be done. > I get it. But I don't like it. Yet. Not sure how this will grow on me. > > A great deal of help, thanks. Excellent explanation. Wow. This is > strange. A part of me wants to run and hide under the nearest 8-bit > microcontroller. But I will continue learning Python. I think you will like it in the near future. But for someone coming from the microcontroller world, used to think closely in terms of the implementation, this may be a big paradigm shift. -- Gabriel Genellina From jarausch at skynet.be Tue Jul 31 16:30:34 2007 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 31 Jul 2007 22:30:34 +0200 Subject: split a string of space separated substrings - elegant solution? Message-ID: <46af9beb$0$14242$ba620e4c@news.skynet.be> Hi, 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') For that, one probably has to protect white space between quotes, then split by white space and finally converted the 'protected white space' to normal white space again. Is there an elegant solution - perhaps without using a lexer and something else. With regular expressions alone it seems clumsy. Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From carsten at uniqsys.com Sun Jul 22 12:13:36 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 22 Jul 2007 12:13:36 -0400 Subject: split on NO-BREAK SPACE In-Reply-To: References: Message-ID: <1185120816.3159.17.camel@localhost.localdomain> On Sun, 2007-07-22 at 17:44 +0200, Peter Kleiweg wrote: > > It's a feature. See help(str.split): "If sep is not specified or is > > None, any whitespace string is a separator." > > Define "any whitespace". Any string for which isspace returns True. > Why is it different in and ? >>> '\xa0'.isspace() False >>> u'\xa0'.isspace() True For byte strings, Python doesn't know whether 0xA0 is a whitespace because it depends on the encoding whether the number 160 corresponds to a whitespace character. For unicode strings, code point 160 is unquestionably a whitespace, because it is a no-break SPACE. > Why does split() split when it says NO-BREAK? Precisely. It says NO-BREAK. It doesn't say NO-SPLIT. -- Carsten Haese http://informixdb.sourceforge.net From bj_666 at gmx.net Tue Jul 3 14:10:02 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Jul 2007 18:10:02 GMT Subject: python 3.0 or 3000 ....is it worth waiting??? Newbie Question References: <468a8dc1$0$27406$ba4acef3@news.orange.fr> Message-ID: <5evhnqF39v66mU4@mid.uni-berlin.de> On Tue, 03 Jul 2007 19:54:57 +0200, M?ta-MCI wrote: >> Python 3000 doesn't include many significant changes to the language > > One exemple : non-Ascii characters in identifiers (= no significatif > change?) Not in the sense that old code doesn't work anymore. ASCII sources still work in Python 3000. And this change may be already in a Python 2.x before P3K. Ciao, Marc 'BlackJack' Rintsch From mensanator at aol.com Fri Jul 13 17:27:13 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Fri, 13 Jul 2007 14:27:13 -0700 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> Message-ID: <1184362033.094940.199250@n60g2000hse.googlegroups.com> On Jul 13, 1:20 pm, Wayne Brehaut wrote: > On Mon, 09 Jul 2007 23:51:25 -0700, "mensana... at aol.com" > > > > > > wrote: > >On Jul 9, 11:42?pm, Paul McGuire wrote: > >> On Jul 9, 11:21 pm, "Jim Langston" wrote:> In Python 2.5 on intel, the statement > >> > 2**2**2**2**2 > >> > evaluates to>>> 2**2**2**2**2 > > >> > 200352993040684646497907235156025575044782547556975141926501697371089405955 63114 > >> > 530895061308809333481010382343429072631818229493821188126688695063647615470 29165 > >> > 041871916351587966347219442930927982084309104855990570159318959639524863372 36720 > > >> > > >> Exponentiation is right associative, so this is the same as: > > >> 2**(2**(2**(2**2))) > >> 2**2**2**4 > >> 2**2**16 > >> 2**65536 > > >> 2=10**0.3010, so 2**65536 is approx 10**19726 > > >> There are 19730 digits in your answer, > > >>>> import gmpy > >>>> n = 2**2**2**2**2 > >>>> gmpy.numdigits(n) > >19729 > > >Did you count the 'L'? > > numdigits(n)? >>> import gmpy >>> help(gmpy.numdigits) Help on built-in function numdigits in module gmpy: numdigits(...) numdigits(x[,base]): returns length of string representing x in the given base (2 to 36, default 10 if omitted or 0); the value returned may sometimes be 1 more than necessary; no provision for any 'sign' characte, nor leading '0' or '0x' decoration, is made in the returned length. x must be an mpz, or else gets coerced into one. > > What? 'L' is a digit in Python? No, but it's a character. Don't you know the difference between str() and repr()? >>> n = 2**2**2**2**2 >>> m = -n >>> len(str(n)) 19729 >>> len(repr(n)) 19730 >>> len(str(m)) 19730 >>> len(repr(m)) 19731 So why would you ever do it the stupid way, when it's just as easy to get these things right? >>> gmpy.numdigits(n) 19729 >>> gmpy.numdigits(m) 19729 > I'm going back to Fortran! Sounds like you never left. > > wwwayne > > >>so this seems to be at least in > >> the ball park. > > >> -- Paul From attn.steven.kuo at gmail.com Thu Jul 26 22:55:14 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 26 Jul 2007 19:55:14 -0700 Subject: instantiate a 'classobj' In-Reply-To: <1185501791.311662.220980@57g2000hsv.googlegroups.com> References: <1185501791.311662.220980@57g2000hsv.googlegroups.com> Message-ID: <1185504914.336486.33200@e16g2000pri.googlegroups.com> On Jul 26, 7:03 pm, westymatt wrote: > I have a class where a parameter to its constructor is a type(param) = > 'classobj'. How would I go about instantiating that given it has no > constructor. A old style class may not have a __new__ attribute, but it's still callable, right? class NewStyle(object): def __init__(self, old_style_cls): self.osc_instance = old_style_cls() self.osc_type = type(old_style_cls) def introspection(self): print "Instrospection shows..." print self print self.osc_instance print self.osc_type class OldStyle: pass print type(OldStyle) ns = NewStyle(OldStyle) ns.introspection() -- Hope this helps, Steven From ratchetgrid at googlemail.com Tue Jul 3 14:14:35 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Tue, 3 Jul 2007 19:14:35 +0100 Subject: Programming Idiomatic Code In-Reply-To: References: <468a0768$0$14120$426a74cc@news.free.fr> Message-ID: <676224240707031114j706b4e21t6768ce3d43b4af66@mail.gmail.com> > "Clipper-derived unreadable drivel" > > I'm intrigued, what language are you working in? > > Clipper v5 was a pretty impressive development language for 1990 - with > code blocks, a flexible pre-processor, garbage collection, exception > handling, decent speed and an API to allow easy integration with > routines written in c. > > It doesn't have to be unreadable at all (unless it's written by someone > who thinks it is dBase). > Whilst I ve never programmed in standard clipper this language is an inhouse language (I would tell you the company but then they would know I wasnt working) developed from Clipper. It has no exception handling, no code blocks, the subroutines arent really subroutines and dont return anything they just write to a global variable which you access after the call. The speed is amazingly slow, it crawls. And dont even start me on GOTOs....you try to make your code easy to read and maintain but it just looks like you ve gone on a 2 day binge and been ill over your VDU. Perl IMO is a 1 day binge problem. They do use real clipper here and it sounds a lot better than this bstard son. C integration, oh to do some real programming would be amazing. I think its just a poor implementation of Clipper and it makes it appreciate the genius of python, the indentation, the ease of reading, ease of maintaining....its so perfect. Now if only I could convince them to move to Python....................dreams..... Nathan From deets at nospam.web.de Wed Jul 18 13:14:49 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 18 Jul 2007 19:14:49 +0200 Subject: New guy question - user form In-Reply-To: <1184763774.604632.187310@j4g2000prf.googlegroups.com> References: <1184763774.604632.187310@j4g2000prf.googlegroups.com> Message-ID: <5g704gF396josU1@mid.uni-berlin.de> meg99 schrieb: > I am using a scheduling sw package that uses Python as its scripting > language much like Excel uses Visual Basic. I am fluent in VB but I > am just beginning in Python. > > What I need to do is this: I need to create a user form that will > contain some predefined data (captured from the scheduling sw > database) and some fields that the user will enter. When the user is > finished, he will write the data to the database via a command button > on the form. > > I have looked at some of the tutorials and I have a couple of books > but I don't see a user form utility like there is in VB. > > I am using version 1.5.2 (the sw I am using does not now support > anything else). > > Can I do what I have described with what I have? AFAIK Python 1.5 featured Tkinter, which should do what you want. But given the embedded nature of your python, I'm not sure if that really works (the python interpreter could be crippled), or what that software of yours offers itself. Diez From robert.rawlins at thinkbluemedia.co.uk Tue Jul 10 12:40:14 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Tue, 10 Jul 2007 17:40:14 +0100 Subject: Time A Script Message-ID: <024b01c7c310$fdecb4f0$f9c61ed0$@rawlins@thinkbluemedia.co.uk> Hello Guys, What's the best way to time how long it takes a script to run, from top to bottom and then have it print that execution time at the end? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Wed Jul 25 08:18:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 25 Jul 2007 09:18:44 -0300 Subject: classmethod & staticmethod References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> <46a5b2ad$0$18903$426a74cc@news.free.fr> Message-ID: En Tue, 24 Jul 2007 21:55:17 -0300, Alex Popescu escribi?: > Neil Cerutti wrote in news:eRwpi.36813$G23.28496 > @newsreading01.news.tds.net: >> On 2007-07-25, Alex Popescu wrote: >>> As a matter of style, how do you figure out that class_list is >>> a class attribute and not an instance attribute? (I don't >>> remember seeing anything in the PEP describing the coding >>> style). >> >> Check out dir(MyClass) and dir(MyClass()) for some insight, if it >> turns out that it matters. > > I must confess that I am a bit confused by this advise, as both are > returning exactly the same thing. Perhaps he meant to say vars(MyClass) and vars(MyClass()) >> Preferably, the user of a class >> doesn't have to really think about it much. > I know that this would be prefered, but in case you are getting 3rd party > code and you modify a class attribute without knowing it is a class > attribute then you may get into trouble (indeed the real problem is with > the designer of the 3rd party code, but still I think it is a valid > concern). Well, you should read its documentation before modifying 3rd. party code... :) If you access (read) an attribute through an instance (let's say, you write x = self.name inside a method) the attribute is first searched in the instance, and when not found, in the class (The actual rules are more complicated but this will suffice for now). If you assign an attribute, it is always set on the instance (never on the class). So you can use a class attribute as a default value for an instance attribute. For this use case, you don't care whether it's an instance attribute or class attribute: py> class Title: ... color = "white" ... def __init__(self, text, color=None): ... self.text = text ... if color is not None: ... self.color = color ... py> t1 = Title("Hello") py> vars(t1) {'text': 'Hello'} py> t1.color 'white' py> Title.color 'white' py> t1.color = "red" py> vars(t1) {'color': 'red', 'text': 'Hello'} py> Title.color 'white' py> t2 = Title("Goodbye", "blue") py> vars(t2) {'color': 'blue', 'text': 'Goodbye'} -- Gabriel Genellina From ricaraoz at gmail.com Tue Jul 31 08:01:42 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 31 Jul 2007 09:01:42 -0300 Subject: What is the "functional" way of doing this? In-Reply-To: <1185839713.412656.242950@i13g2000prf.googlegroups.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> Message-ID: <46AF24A6.9080709@bigfoot.com> 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). Of course my little test may me wrong (just started with this language), in which case I would appreciate any corrections, or comments. ------------------------------------------------ lists1.py : def f(n): if n > 0: return ([n%26] + f(n/26)) else: return [] import time start = time.time() for x in range(1,1000000): f(2100000000) end = time.time() print end - start ----------------------------------------------- lists2.py : def f(n): def mseq(n): while n > 0: n,a = divmod(n, 26) yield a return list(mseq(n)) import time start = time.time() for x in range(1,1000000): f(2100000000) end = time.time() print end - start ------------------------------------------------ From nis at superlativ.dk Thu Jul 5 04:49:04 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Thu, 05 Jul 2007 10:49:04 +0200 Subject: Proposal: s1.intersects(s2) In-Reply-To: References: <5f1pldF3a62csU5@mid.uni-berlin.de> Message-ID: <468cb090$0$90268$14726298@news.sunsite.dk> Steven D'Aprano skrev: > On Wed, 04 Jul 2007 23:53:15 -0400, David Abrahams wrote: > >> on Wed Jul 04 2007, "Steven D'Aprano" wrote: >> >>> On Wed, 04 Jul 2007 14:37:34 +0000, Marc 'BlackJack' Rintsch wrote: >>> >>>> On Wed, 04 Jul 2007 09:59:24 -0400, David Abrahams wrote: >>>> >>>>> Here's an implementation of the functionality I propose, as a >>>>> free-standing function: >>>>> >>>>> def intersects(s1,s2): >>>>> if len(s1) < len(s2): >>>>> for x in s1: >>>>> if x in s2: return True >>>>> else: >>>>> for x in s2: >>>>> if x in s1 return True >>>>> return False >>>> In Python 2.5 this can be written a bit more concise: >>>> >>>> def intersects(set_a, set_b): >>>> if len(set_a) < len(set_b): >>>> set_a, set_b = set_b, set_a >>>> return any(item in set_a for item in set_b) >>> >>> I'd rather see sets gain an method "isintersect()" >> And why is that a good name? It's not even grammatical. > > Neither is "It's not even grammatical", but all but purists use it > regardless. > > A common Python convention is to have test functions named something > like "isfoo", e.g. str.isdigit(), isspace(), islower() etc. They're not > exactly grammatical either, e.g. isdigit() should actually be "contains > one or more digits, and nothing but digits". (Presumably the pedantically > correct name was rejected as being too long.) I was just following that > convention. The problem is, these functions can be read as "X is [consisting only of] digit[s]", "X is lower [case]" etc, where the bits in brackets have been removed for brewity. In the case of "s1 is intersect s2" there is no way I can see of adding words to get a correct sentence. The "obvious" naming is "s1.intersects(s2)" which reads as "s1 intersects s2", a perfectly cromulent sentence. Nis From claird at lairds.us Tue Jul 24 15:24:02 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 24 Jul 2007 19:24:02 +0000 Subject: Where do they tech Python officialy ? References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <1185265091.276958.239910@r34g2000hsd.googlegroups.com> <7x8x96fa3q.fsf@ruckus.brouhaha.com> <1185274675.038893.71200@d55g2000hsg.googlegroups.com> Message-ID: In article <1185274675.038893.71200 at d55g2000hsg.googlegroups.com>, NicolasG wrote: . . . >Yes true , I'm already a programmer.. doing technical support for my >company products in a call center. I hate my job, I hate the moment I >have to wake up to go work ! I hate that moment I have to go sleep >when I think of the next working day morning. >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 .. > > What repetitive, mind-numbing, soul-killing, dreary, tedious aspects of your current job are susceptible to automation with the help of the computer in front of you? Let Python be the vehicle for this automation--and you've become a Python programmer. From cousinstanley at hotmail.com Mon Jul 9 16:34:26 2007 From: cousinstanley at hotmail.com (Cousin Stanley) Date: Mon, 09 Jul 2007 15:34:26 -0500 Subject: What is the preferred doc extraction tool? References: <32e43bb70707090743r6df891eeo3500e0893d05aa54@mail.gmail.com> Message-ID: <1184013266_64417@sp12lax.superfeed.net> > .... > The tool is Latex plus a lot of utilities > that help make the HTML output good looking. > .... I spent several hours yesterday editing some html doc files for a python module that had been generated by a tool called LaTeX2HTML .... That was some of the ugliest and most non-standards compliant html code I have ever seen .... Even the
    tags included rgb color value styles ! Latex apparently provides nice looking printed documents but the LaTex2HTML tool surely provides a real mess for html code .... -- 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 westymatt at gmail.com Mon Jul 23 03:05:40 2007 From: westymatt at gmail.com (westymatt) Date: Mon, 23 Jul 2007 07:05:40 -0000 Subject: Catching a key press In-Reply-To: <1185173730.345615.284940@q75g2000hsh.googlegroups.com> References: <1185173730.345615.284940@q75g2000hsh.googlegroups.com> Message-ID: <1185174340.795377.13800@r34g2000hsd.googlegroups.com> This is without a gui toolkit. This is going to be implemented on console i/o From infocat at earthlink.net Sun Jul 1 22:32:24 2007 From: infocat at earthlink.net (Frank Swarbrick) Date: Sun, 01 Jul 2007 20:32:24 -0600 Subject: howto resend args and kwargs to other func? In-Reply-To: <1183282733.179683.174350@c77g2000hse.googlegroups.com> References: <1183279997.244378.105810@n60g2000hse.googlegroups.com> <1183280667.542964.175570@u2g2000hsc.googlegroups.com> <1183282733.179683.174350@c77g2000hse.googlegroups.com> Message-ID: <5er6doF31bulkU1@mid.individual.net> dmitrey wrote: > Thanks all, I have solved the problem. Why do people do this without posting what the actual solution is!!!! From see.signature at no.spam Tue Jul 10 06:22:32 2007 From: see.signature at no.spam (Eric Brunel) Date: Tue, 10 Jul 2007 12:22:32 +0200 Subject: Choosing Tkinter over wxPython... References: <3e384$4692a3c4$4275d90a$11745@FUSE.NET> Message-ID: On Mon, 09 Jul 2007 23:08:20 +0200, Kevin Walzer wrote: > I've spent some time playing with both, and while wxPython is nice, > Tkinter just seems to fit my head better, and with appropriate selection > of widgets and interface design, seems to yield up perfectly usable > GUI's. > > Can anyone else who finds Tkinter better for them than wxPython (or the > other toolkits) explain why it works for them? I am, for more or less the same reasons as you. At the time I started - which is quite some time ago -, there was also no serious alternative to Tkinter's Canvas and Text widgets in the other toolkits. This has changed today, at least for the Text widget. But now, I'm used to Tkinter's way of doing things and I find working with other toolkits weird... -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From horpner at yahoo.com Thu Jul 26 09:23:15 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 26 Jul 2007 13:23:15 GMT Subject: first, second, etc line of text file References: <1185394350.032814.262990@d55g2000hsg.googlegroups.com> Message-ID: On 2007-07-25, George Sakkis wrote: > For random access, the easiest way is to slurp all the file in > a list using file.readlines(). A lazy evaluation scheme might be useful for random access that only slurps as much as you need. class LazySlurper(object): r""" Lazily read a file using readline, allowing random access to the results with __getitem__. >>> import StringIO >>> infile = StringIO.StringIO( ... "Line 0\n" ... "Line 1\n" ... "Line 2\n" ... "Line 3\n" ... "Line 4\n" ... "Line 5\n" ... "Line 6\n" ... "Line 7\n") >>> slurper = LazySlurper(infile) >>> print slurper[0], Line 0 >>> print slurper[5], Line 5 >>> print slurper[1], Line 1 >>> infile.close() """ def __init__(self, fileobj): self.fileobj = fileobj self.upto = 0 self.lines = [] self._readupto(0) def _readupto(self, n): while self.upto <= n: line = self.fileobj.readline() if line == "": break self.lines.append(line) self.upto += 1 def __getitem__(self, n): self._readupto(n) return self.lines[n] -- Neil Cerutti Eddie Robinson is about one word: winning and losing. --Eddie Robinson's agent Paul Collier From hjp-usenet2 at hjp.at Wed Jul 4 17:18:10 2007 From: hjp-usenet2 at hjp.at (Peter J. Holzer) Date: Wed, 4 Jul 2007 23:18:10 +0200 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <1183574760.225389.266470@o61g2000hsh.googlegroups.com> Message-ID: On 2007-07-04 18:46, James Harris wrote: > On 1 Jul, 15:11, "Peter J. Holzer" wrote: > ... >> Stick to unix timestamps but store them as a double precision floating >> point number. The 53 bit mantissa gives you currently a resolution of >> about 200 ns, slowly deteriorating (you will hit ms resolution in about >> 280,000 years, if I haven't miscalculated). Any language and database >> should be able to handle double-precision FP numbers, so that's as >> portable as it gets and conversion from/to system time should be >> trivial. >> >> If you need to represent milliseconds exactly, you can just multiply the >> timestamp with 1000 (and get java timestamps). > > Interesting option. I think my choice is between separate day and sub- > day 32-bit unsigned integers, text, and this 64-bit float option. > > I'm not clear, though. Did you mean to store double precision numbers > where the seconds are the units (I assume this) or where the days are > the units? And what do you think of the other option? I was thinking about using the seconds as units (so 2007-07-04T23:02:04.123 CET is represented as 1183582924.123). It's a natural extension of the unix time stamp, so you can often just pass the values to the normal date routines (especially in languages like perl which don't really distinguish between integers and floating point numbers). But it really doesn't matter much. If you ignore leap seconds, using days instead of seconds is just a constant factor (in fact, the unix timestamp ignores leap seconds, too, so it's always a constant factor). You can't represent a second exactly if the unit is one day (1/86400 is not a multiple of a power of two), but that probably doesn't matter. hp -- _ | Peter J. Holzer | I know I'd be respectful of a pirate |_|_) | Sysadmin WSR | with an emu on his shoulder. | | | hjp at hjp.at | __/ | http://www.hjp.at/ | -- Sam in "Freefall" From aisaac at american.edu Tue Jul 10 12:05:53 2007 From: aisaac at american.edu (Alan Isaac) Date: Tue, 10 Jul 2007 16:05:53 GMT Subject: allow scripts to use .pth files? In-Reply-To: <1183928022.719873.49470@i38g2000prf.googlegroups.com> References: <1183899193.766331.13210@22g2000hsm.googlegroups.com> <1183928022.719873.49470@i38g2000prf.googlegroups.com> Message-ID: John Machin wrote: > I got the impression that the OP was suggesting that the interpreter > look in the directory in which it found the script. Right. > I got the impression that the problem was that the package was not > only not on sys.path but also not in the same directory as the script > that wanted to import it. Right. > I'm curious whether you think that the OP's use of ".pth" was a typo, > and whether you have read this: > http://docs.python.org/lib/module-site.html You seem to understand what I'm getting at. Thanks John. Alan Isaac (the OP above) From mike.klaas at gmail.com Mon Jul 16 18:25:27 2007 From: mike.klaas at gmail.com (Klaas) Date: Mon, 16 Jul 2007 15:25:27 -0700 Subject: The ** operator ambiguous? In-Reply-To: <1184607614.904143.219330@w3g2000hsg.googlegroups.com> References: <1184607614.904143.219330@w3g2000hsg.googlegroups.com> Message-ID: <1184624727.479509.134020@e16g2000pri.googlegroups.com> On Jul 16, 10:40 am, Robert Dailey wrote: > I noticed that the ** operator is used as the power operator, however > I've seen it used when passing variables into a function. For example, > I was researching a way to combine dictionaries. I found that if you > do this: > > a = {"t1":"a", "t2":"b"} > b = {"t3":"c"} > dict( a, **b ) > > This combines the two dictionaries. Use dict.update to combine dictionaries. -Mike From kay.schluehr at gmx.net Thu Jul 26 15:42:44 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 26 Jul 2007 12:42:44 -0700 Subject: From D In-Reply-To: <1185384166.503862.236170@d55g2000hsg.googlegroups.com> References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> Message-ID: <1185478964.917817.140730@d55g2000hsg.googlegroups.com> On Jul 25, 7:22 pm, "mensana... at aol.com" wrote: > On Jul 24, 6:08 pm, Steven D'Aprano > > > > wrote: > > On Tue, 24 Jul 2007 20:09:00 +0200, Bjoern Schliessmann wrote: > > > Stargaming wrote: > > >> On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote: > > > >>> While in a syntax like: > > >>> for i in xrange(1_000_000): > > >>> my eyes help me group them at once. > > > >> Sounds like a good thing to be but the arbitrary positioning > > >> doesnt make any sense. > > > > Checking underscore positions would only add complexity. Why not > > > just ignore them, no matter where they are? > > > Underscores in numerics are UGLY. Why not take a leaf out of implicit > > string concatenation and allow numeric literals to implicitly concatenate? > > > Python already does: > > "hello-" "world" => "hello-world" > > > Propose: > > 123 456 789 => 123456789 > > 123.456 789 => 123.456789 > > So, spaces will no longer be delimiters? Won't that cause > much wailing and gnashing of teeth? Nope. Just replace the current grammar rule atom: ... NAME | STRING+ | NUMBER by atom: ... NAME | STRING+ | NUMBER+ The resulting grammar is still free of ambiguities. The tokenizer doesn't complain anyway - not even yet. From samwyse at gmail.com Thu Jul 12 08:26:14 2007 From: samwyse at gmail.com (samwyse) Date: Thu, 12 Jul 2007 12:26:14 -0000 Subject: allow scripts to use .pth files? In-Reply-To: <1183928022.719873.49470@i38g2000prf.googlegroups.com> References: <1183899193.766331.13210@22g2000hsm.googlegroups.com> <1183928022.719873.49470@i38g2000prf.googlegroups.com> Message-ID: <1184243174.833585.82310@22g2000hsm.googlegroups.com> On Jul 8, 3:53 pm, John Machin wrote: > I'm curious whether you think that the OP's use of ".pth" was a typo, > and whether you have read this: > http://docs.python.org/lib/module-site.html I've read it, but not recently; the syntax of the .pyh files was in the back of my head. I had forgotten about the sitecustomize module, though. Unfortunately for the OP, while the documentation states, "After these path manipulations, an attempt is made to import a module named sitecustomize," the import is apparently done *before* the path to the script is prepended to sys.path. (My name isn't Luke, so I don't feel the need to read the source.) I'm guessing that the OP's real question is, "How does one do site customizations when one doesn't have write access to the site directories?" Lots of programs can be installed and run from ~/bin, but locating ~/lib can be hard, at least for arbitrary values of bin and lib. At this point, someone usually tells me to write a PEP; perhaps the OP would like to try his hand? In keeping with the spirit of the site customizations, I'd specify that all .pyh files get imported, not just one matching the name of the script. (This is more robust in the face of hard-links, packages consisting of multiple scripts, etc.) I'd also suggest an attempt to import a module named mycustomize after the path to the invoked script is prepended to sys.path. From tjreedy at udel.edu Wed Jul 11 21:37:00 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Jul 2007 21:37:00 -0400 Subject: 2**2**2**2**2 wrong? Bug? References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> <1184173446.779276.250530@k79g2000hse.googlegroups.com><1184182757.797808.206480@d55g2000hsg.googlegroups.com> Message-ID: "Evan Klitzke" wrote in message news:cfb58d850707111747x4b83cb88wcaf45437e8e14511 at mail.gmail.com... | On 7/11/07, Gabriel Genellina wrote: | > Just for curiosity: This helps to find the answer to the problem "Which is | > the largest number that can be written with only 3 digits?" | > Some people stop at 999, others try 99**9 and 9**99, and the winner is | > 9**9**9, or: | > | > | 9 | > | 9 | > | 9 | > | > Sorry, couldn't resist. | | But you can append ! (i.e. factorial) indefinitely without adding any | digits to make the number arbitrarily large ;-) But as Gabriel showed, 9**9**9 in standard math pen-and-paper or chalk-and-blackboard notation, not the squished computer linear imitation thereof, uses three nines and nothing else ;-) tjr From grflanagan at yahoo.co.uk Mon Jul 16 11:41:28 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Mon, 16 Jul 2007 08:41:28 -0700 Subject: Compiling python2.5 on IBM AIX In-Reply-To: <1184581796.377610.98230@o61g2000hsh.googlegroups.com> References: <1184581796.377610.98230@o61g2000hsh.googlegroups.com> Message-ID: <1184600488.343686.263220@d55g2000hsg.googlegroups.com> On Jul 16, 12:29 pm, bravo.l... at gmail.com wrote: > hi, > > I'm trying to make a local install of python 2.5 on AIX and I'm > getting some trouble with _curses. > > Here is how I tried to compile it : > > export BASE=/usr/local/python251 > > cd Python.2.5.1 > ./configure --prefix=${BASE}/\ > LDFLAGS="-L\${BASE}/lib/"\ > PPFLAGS="-I\${BASE}/include/"\ > > make > make test > make altinstall > I haven't compiled it myself, but I'm told that the installation I work with was compiled with: export PATH=$PATH:/usr/vacpp/bin:/usr/vacpp/lib ./configure --with-gcc="xlc_r -q64" --with-cxx="xlC_r -q64" --disable- ipv6 AR="ar -X64" make make install if that helps. Gerard From rustompmody at gmail.com Wed Jul 18 09:36:12 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 18 Jul 2007 19:06:12 +0530 Subject: The Modernization of Emacs: exists already In-Reply-To: <1184764620.778937.264760@m37g2000prh.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272678.877166.209640@j4g2000prf.googlegroups.com> <1184764620.778937.264760@m37g2000prh.googlegroups.com> Message-ID: Xah Lee: I agree with what you say now and most of what you wrote a month back -- I even learnt something useful from there -- longlines mode. Emacs is important to me and (I guess) to many of the subscribers here. But how does posting an emacs related question help on a python mailing list?? From kyosohma at gmail.com Fri Jul 20 17:20:12 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 20 Jul 2007 21:20:12 -0000 Subject: win32com ppt embedded object numbers reverting back to original numbers In-Reply-To: References: Message-ID: <1184966412.634361.7830@q75g2000hsh.googlegroups.com> On Jul 19, 4:33 pm, Lance Hoffmeyer wrote: > Hey all, > > I have a script that takes numbers from XL and inserts them into an embedded > MSGRAPH dataset in PPT. The problem is that when I reopen the modified document > that has been saved as a new filename and activate the embedded datasheet the > new numbers that were inserted disappear and the old, original numbers come back? > > I thought that adding these lines and resetting these variables was supposed to prevent > this from happening? > > del oGraph > del PWB > del oHEADER > del oVALUE > > Anyone had experience with this and know what I need to do to keep the embedded datasheet > from reverting back to it's original numbers after modification? > > Thanks in advance, > > Lance > > ################################################################################################################################################################################# > ################################################################################################################################################################################# > # ADD THIS INTO A MODULE IN PPT TO OBTAIN THE PROG ID OF A SLIDE > #Sub test() > #MsgBox "The Slide ID of the current slide is:" & _ > # ActiveWindow.View.Slide.SlideID > #End Sub > ################################################################################################################################################################################# > def attributesbyID(row,base,slideID,spreadsheet): > sh = wb.Worksheets (spreadsheet) > sh.Select() > LIST = xlparams(row, base) > ################ POWERPOINT SECTION ###################### > for shape in WB.Slides.FindBySlideID(slideID).Shapes: > if (shape.Type== 7): > for oXLROW,oXLBASE,oXLLASTCOL,oPPTCELL,oPPTHEADERCELL in LIST: > oVALUE = sh.Cells(oXLROW,oXLLASTCOL).Value > oHEADER = sh.Cells(base-1,oXLLASTCOL).Value + " (n=" + str(int(sh.Cells(oXLBASE,oXLLASTCOL).Value)) + ")" > PWB = WB.Slides.FindBySlideID(slideID).Shapes(shape.Name) > oGraph = PWB.OLEFormat.Object > oGraph.Application.datasheet.Range(oPPTCELL).Value = oVALUE > oGraph.Application.datasheet.Range(oPPTHEADERCELL).Value = oHEADER > oGraph.Application.datasheet.Font.Bold=False > del oGraph > del PWB > del oHEADER > del oVALUE > ########################################################### > ################################################################################################################################################################################# > ################################################################################################################################################################################# > ################################################################################################################################################################################# > > def xlparams(row, base): > lastcol=LASTCOL > ############### EXCEL SECTION TO GET NUMBERS ############# > thelist=((row,base,lastcol,"A13","013"),(row,base,lastcol-1,"A14","014"),(row,base,lastcol-2,"A15","015"),(row,base,lastcol-3,"A16","016"), > (row+20,base+20,lastcol,"A9","09"),(row+20,base+20,lastcol-1,"A10","010"),(row+20,base+20,lastcol-2,"A11","011"),(row+20,base+20,lastcol-3,"A12","012"), > (row+40,base+40,lastcol,"A5","05"),(row+40,base+40,lastcol-1,"A6","06" ), (row+40,base+40,lastcol-2,"A7","07" ), (row+40,base+40,lastcol-3,"A8","08" ), > (row+60,base+60,lastcol,"A1","01"),(row+60,base+60,lastcol-1,"A2","02" ), (row+60,base+60,lastcol-2,"A3","03" ), (row+60,base+60,lastcol-3,"A4","04" )) > ########################################################## > return thelist > > ## attribute(ROW NUMBER, BASE ROW NUMBER, SLIDE NUMBER) > attributesbyID(14,12,839,"Attributes(116-144)") # This medication has a convenient dosing frequency I've never done this with Python, but it sounds like your inserting a linked table rather than a copy of the dataset as an Excel worksheet. Try doing the insert manually to see which way keeps the data the way you want, then you'll probably gain insight into what you need to do in Python. Mike From nospam at nospam.com Mon Jul 30 00:07:36 2007 From: nospam at nospam.com (Gilles Ganault) Date: Mon, 30 Jul 2007 06:07:36 +0200 Subject: Why no maintained wrapper to Win32? References: <46ab694e$0$17577$9b622d9e@news.freenet.de> <59kna3p8r0cu2gk6hs5lbig8cjj8klatju@4ax.com> <1185762820.496821.298530@19g2000hsx.googlegroups.com> Message-ID: On Sun, 29 Jul 2007 19:33:40 -0700, sturlamolden wrote: >You mean 'total lack of documentation' besides Mark Hammond's O'Reilly >book on Windows programming in Python? Sorry, I thought that book was way outdated because it uses Python 1.5. >Not to mention MSDN, Charles Petzold's book, and other sources of >Win32 API and MFC documentation? For people who don't konw the Win32 API and don't know C... is the O'Reilly book above the best source of information on how to write Win32 GUI apps in Python? Thanks. From horpner at yahoo.com Wed Jul 25 14:24:24 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 25 Jul 2007 18:24:24 GMT Subject: is_iterable function. Message-ID: def is_iterable(obj): try: iter(obj) return True except TypeError: return False Is there a better way? -- Neil Cerutti From tjreedy at udel.edu Sun Jul 1 23:09:19 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 1 Jul 2007 23:09:19 -0400 Subject: Tiny/small/minimalist Python? References: <1183332951.122782.212720@o11g2000prd.googlegroups.com> Message-ID: "rtk" wrote in message news:1183332951.122782.212720 at o11g2000prd.googlegroups.com... | I'm looking for information on building a tiny/small/minimalist/ | vanilla python interpreter. One that implements the core language and | a few of the key modules but isn't tied to any specific operating | system. | | I guess I'm asking for the smallest subset of the standard Python | source code files that is necessary to get a working interpreter using | a plain C compiler. | | Is this even possible? If so, has someone done it already? I've | looked on Google and in comp.lang.python but nothing comes up. Google 'tinypython' and first entry is Mark Hammond's answer to nearly same question. And some other responses might help you From nospam at nospam.com Sun Jul 29 17:28:46 2007 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 29 Jul 2007 23:28:46 +0200 Subject: Why no maintained wrapper to Win32? References: <46ab694e$0$17577$9b622d9e@news.freenet.de> <59kna3p8r0cu2gk6hs5lbig8cjj8klatju@4ax.com> <46ac1a43$0$7536$9b622d9e@news.freenet.de> Message-ID: <5h1qa3luht8q30vaad0fbn4cpfsddgmt17@4ax.com> On Sun, 29 Jul 2007 06:40:35 +0200, "Martin v. L?wis" wrote: >Why do you say that the Win32 API lacks documentation? I find the >documentation at msdn.microsoft.com to be quite useful. No, I meant documentation on how to write Win32 apps using PyWin. >Yes, there haven't been many changes to Win32 in recent years (there >haven't been many system releases in the first place). Most additions >did not concern GUI programming, which is what you were after, and >even those that are recent additions are rather rarely needed, so >you likely won't miss them. Makes sense. Do you know of good places to hang around when looking for information on writing Win32-based GUI apps in Pythons (web forums, mailing lists, etc.)? Thank you. From horpner at yahoo.com Fri Jul 13 20:33:39 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Sat, 14 Jul 2007 00:33:39 GMT Subject: Can a low-level programmer learn OOP? References: <4697d9f0$0$7614$426a74cc@news.free.fr> Message-ID: On 2007-07-13, Wayne Brehaut wrote: > So Kay actually invented NONE of the concepts that make a PL an > OOPL. He only stated the concepts concisely and named the > result OOP, Naming and categorizing something shouldn't be underestimated as an accomplishment, though. The exercise can have profound results. For example, consider "marriage." ;) > Under a claim of Academic Impunity (or was that "Immunity"), > here's another historical tid-bit. In a previous empolyment we > once had a faculty applicant from CalTech who knew we were > using Simula as our introductory and core language in our CS > program, so he visited Xerox PARC before coming for his > inteview. His estimate of Alan Kay and Smalltalk at that time > (early 80s) was that "They wanted to implement Simula but > didn't understand it--so they invented Smalltalk and now don't > understand _it_!" Heh, heh. Thanks for the intersting info. -- Neil Cerutti From mik3l3374 at gmail.com Sun Jul 22 22:21:53 2007 From: mik3l3374 at gmail.com (mik3l3374 at gmail.com) Date: Sun, 22 Jul 2007 19:21:53 -0700 Subject: idiom for RE matching In-Reply-To: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> Message-ID: <1185157313.356112.159020@z24g2000prh.googlegroups.com> On Jul 19, 12:52 pm, Gordon Airporte wrote: > I have some code which relies on running each line of a file through a > large number of regexes which may or may not apply. For each pattern I > want to match I've been writing > > gotit = mypattern.findall(line) > if gotit: > gotit = gotit[0] > ...do whatever else... > > This seems kind of clunky. Is there a prettier way to handle this? > I've also been assuming that using the re functions that create match > objects is slower/heavier than dealing with the simple list returned by > findall(). I've profiled it and these matches are the biggest part of > the running time of the program, so I really would rather not use > anything slower. if your search is not overly complicated, i think regexp is not needed. if you want, you can post a sample what you want to search, and some sample input. From gagsl-py2 at yahoo.com.ar Mon Jul 30 01:25:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 30 Jul 2007 02:25:19 -0300 Subject: ctypes:passing python class instances through c and back References: <1185463084.435165.260100@i38g2000prf.googlegroups.com> Message-ID: En Thu, 26 Jul 2007 12:18:04 -0300, m2i3k escribi?: > I have C code with requires me to register a python callback. I am > able to get the callback working well using ctypes if I use global > functions without any context argument for the callback. > > Now I want to register a python class member function for callback, > and give "self" as the context argument at the time of callback > registration. Then the c code can invoke the callback with self as the > context argument Use a bound method as the callback -that is, get the method from an instance, not from the class-. Pass it the same way as you would pass a global function; you get the "self" argument for free :) -- Gabriel Genellina From Colin.Prepscius at morganstanley.com Fri Jul 20 11:48:05 2007 From: Colin.Prepscius at morganstanley.com (Prepscius, Colin (IT)) Date: Fri, 20 Jul 2007 11:48:05 -0400 Subject: exec and CodeObjects Message-ID: Does anybody know how to pass parameters to 'exec somefunction.func_code'? def f1(): print 'this is f1' def f2(p): print 'this is f2, p =', str(p) exec f1.func_code THIS RESULTS IN: "this is nf1" WHICH IS NICE exec f2.func_code THIS RESULTS IN: TypeError: f2() takes exactly 1 argument (0 given) WHICH IS EXPECTED exec f2.func_code in {'p':34} THIS RESULTS IN: TypeError: f2() takes exactly 1 argument (0 given) ????? Why? So I can take a function defined in a script or repl and a parameter, marshal them, send the results to a remote host, unmarshal them, and execute the function given the parameter. Am I going about this wrongly? I'd specifically like to avoid having to save the function in a file, send the file and import it on the remote side. thanks! Colin -------------------------------------------------------- NOTICE: If received in error, please destroy and notify sender. Sender does not intend to waive confidentiality or privilege. Use of this email is prohibited when received in error. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Wed Jul 25 13:22:46 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Wed, 25 Jul 2007 10:22:46 -0700 Subject: From D In-Reply-To: References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> Message-ID: <1185384166.503862.236170@d55g2000hsg.googlegroups.com> On Jul 24, 6:08 pm, Steven D'Aprano wrote: > On Tue, 24 Jul 2007 20:09:00 +0200, Bjoern Schliessmann wrote: > > Stargaming wrote: > >> On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote: > > >>> While in a syntax like: > >>> for i in xrange(1_000_000): > >>> my eyes help me group them at once. > > >> Sounds like a good thing to be but the arbitrary positioning > >> doesnt make any sense. > > > Checking underscore positions would only add complexity. Why not > > just ignore them, no matter where they are? > > Underscores in numerics are UGLY. Why not take a leaf out of implicit > string concatenation and allow numeric literals to implicitly concatenate? > > Python already does: > "hello-" "world" => "hello-world" > > Propose: > 123 456 789 => 123456789 > 123.456 789 => 123.456789 So, spaces will no longer be delimiters? Won't that cause much wailing and gnashing of teeth? > > -- > Steven. From martin.clausen at gmail.com Tue Jul 3 05:58:16 2007 From: martin.clausen at gmail.com (Martin) Date: Tue, 03 Jul 2007 09:58:16 -0000 Subject: 15 Exercises to Know A Programming Language Message-ID: <1183456696.168214.114900@o61g2000hsh.googlegroups.com> I am trying to improve my Python skills through some exercises. Currently I am working on Larry's "15 exercises to know a programming language " (http://www.knowing.net/ PermaLink,guid,f3b9ba36-848e-43f8-9caa-232ec216192d.aspx). The first exercise is this: "Write a program that takes as its first argument one of the words 'sum,' 'product,' 'mean,' or 'sqrt' and for further arguments a series of numbers. The program applies the appropriate function to the series." My solution so far is this: http://dpaste.com/13469/ I would really like some feedback. Is this a good solution? is it efficient? robust? what could be improved? any not looking for a revised solution, hints on what to improve are also very welcome. Martin From mail at microcorp.co.za Mon Jul 16 02:51:31 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 16 Jul 2007 08:51:31 +0200 Subject: 2**2**2**2**2 wrong? Bug? References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> <1184351416.166930.290710@k79g2000hse.googlegroups.com> <1184362323.476796.22570@w3g2000hsg.googlegroups.com> <746l93p0mkhljcuc7qsdk7pl908qnpenni@4ax.com> Message-ID: <00a601c7c776$90c2c3a0$03000080@hendrik> "Wayne Brehaut" wrote: > On Sun, 15 Jul 2007 17:37:13 -0400, Steve Holden > wrote: > > >Wayne Brehaut wrote: > >> On Fri, 13 Jul 2007 14:32:03 -0700, "mensanator at aol.com" 8< ------------------------------------------------------------------------- > Also, I tend to follow the general Evolutionarily Stable Strategy > generally called "Retaliator". In the simple game of Hawk vs. Dove a > Hawk always attacks and defends to the death, whereas a Dove always > runs. A mixed strategy would be to sometimes attack-and-defend and > sometimes run, and a special case is to always run except when you're > attacked--then defend to the death; i.e., behave like a Dove to a Dove > and like a Hawk to a Hawk. > > In Game Theory, if not in practice, Retaliator is dominant over both > pure Hawk and pure Dove, partly because some who present like Hawks > are actually Bullies--who behave like Hawks until an opponent defends, > then behave like Doves. *grin* - you realise of course, that this stated strategy leaves you wide open to trolls of the "Lets see what we can provoke him into responding" kind - from people whose sense of humour is either subtle, or evil... - Hendrik From dave at boost-consulting.com Thu Jul 5 21:00:53 2007 From: dave at boost-consulting.com (David Abrahams) Date: Thu, 05 Jul 2007 21:00:53 -0400 Subject: Proposal: s1.intersects(s2) References: <5f1pldF3a62csU5@mid.uni-berlin.de> <1183600138.759015.246040@c77g2000hse.googlegroups.com> Message-ID: <87ps36s5ve.fsf@grogan.peloton> on Thu Jul 05 2007, Christoph Zwerschke wrote: > Steven D'Aprano wrote: >> I'm not a professional set theorist, but in 15-odd years of studying and >> teaching maths I've never come across mathematicians using intersect as a >> verb except as informal short-hand. I often say "North Street and South >> Street don't intersect", but "the intersection of sets A and B is empty". > > I think mathematicians use more often the inverse predicate, namely > "disjoint", which is well defined as having an empty intersection. Doesn't read so well as a method, though. You end up with "a.is_disjoint_with(b)." -- Dave Abrahams Boost Consulting http://www.boost-consulting.com The Astoria Seminar ==> http://www.astoriaseminar.com From S.Mientki-nospam at mailbox.kun.nl Thu Jul 26 15:03:17 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 26 Jul 2007 21:03:17 +0200 Subject: removing items from a dictionary ? Message-ID: <46A8EFF5.4060600@mailbox.kun.nl> hello, I want to remove some items from a dictionary, so I would expect this should work: Nets = {} ... fill the dictionary Nets for net in Nets: if net.upper() in Eagle_Power_Nets : del Nets [ net ] But it gives me Message File Name Line Position Traceback ? D:\data_to_test\JALsPy\Eagle_import.py 380 RuntimeError: dictionary changed size during iteration Now I can solve this problem in the following way power_nets = [] for net in Nets: if net.upper() in Eagle_Power_Nets : power_nets.append ( net ) # remove power nets from netlist for net in power_nets: del Nets [ net ] But I wonder if this is the best way to manipulate a dictionary, because I've to do more "complex" operations on the dictionary, like joining items, I would like to have a better understanding of what can and what can't be done. thanks, Stef Mientki From bignose+hates-spam at benfinney.id.au Tue Jul 10 18:47:20 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 11 Jul 2007 08:47:20 +1000 Subject: bool behavior in Python 3000? References: Message-ID: <87tzsblvuv.fsf@benfinney.id.au> Michael Hoffman writes: > Alan Isaac wrote: > > Is there any discussion of having real booleans > > in Python 3000? > > I'm not sure how the bools we have now are not "real." I'm guessing that Alan is referring (at least in part) to this behaviour: Python 2.4.4 (#2, Apr 5 2007, 20:11:18) [...] >>> True == 1 True >>> False == 0 True Whereas a real bool type would have discrete values for True and False that would not be equal to any other. -- \ "I guess we were all guilty, in a way. We all shot him, we all | `\ skinned him, and we all got a complimentary bumper sticker that | _o__) said, 'I helped skin Bob.'" -- Jack Handey | Ben Finney From knipknap at gmail.com Tue Jul 3 08:12:22 2007 From: knipknap at gmail.com (Samuel) Date: Tue, 03 Jul 2007 05:12:22 -0700 Subject: Debugging "broken pipe" (in telnetlib) Message-ID: <1183464742.148754.120550@w5g2000hsg.googlegroups.com> Hi, When using telnetlib, the connection sometimes breaks with the following error: "error: (32, 'Broken pipe')" where the traceback points to self.sock.send(buffer) in telnetlib.py. The problem is unreproducible, but happens fairly often (approx. 5% of the time). Any idea how to debug such a problem? How can I find out what broke the pipe? -Samuel From zentraders at gmail.com Fri Jul 20 15:27:14 2007 From: zentraders at gmail.com (Zentrader) Date: Fri, 20 Jul 2007 19:27:14 -0000 Subject: Weird errors when trying to access a dictionary key In-Reply-To: <1184956573.702959.96400@d30g2000prg.googlegroups.com> References: <1184956573.702959.96400@d30g2000prg.googlegroups.com> Message-ID: <1184959634.927653.158530@i13g2000prf.googlegroups.com> > rpt_file.writelines('\t' + [song].keys() \ > + '\t' + > I get the following error: > > Traceback (most recent call last): > AttributeError: 'list' object has no attribute 'keys' All of these messages are correct. The first error is AttributeError: 'list' object has no attribute 'keys' You are converting the dictionary to a list on this line, and lists do not have keys > rpt_file.writelines('\t' + [song].keys() \ ---> to a list <--- When you print it, you are printing a dictionary, so it does have keys. Note the first line has braces, not brackets so it is a dictionary. You might want to consider using a dictionary of classes, with each class containing all of the data that is now in the hodgepodge of dictionaries, or simply a list with item[0]=year, item[1]=month, etc. This is an over-simplified version of using classes to store data. There has to be more examples on the web. [code].class my_class : . def __init__(self): . self.field_1 = "init field_1" . self.field_2 = 0 . .objectList = [] .for j in range(0, 2): . objectList.append( my_class() ) . .objectList[0].field_1= "Test [0] Field 1" .objectList[0].field_2= "Data for Field #2 for [0]" .objectList[0].field_3= "Data for Field #3 for [0]" ## not in original[/code] print "objectList[0] =", objectList[0].field_1, "---->", \ objectList[0].field_2, "---->", objectList[0].field_3 print "objectList[1] =", objectList[1].field_1, "---->", objectList[1].field_2 From toddw at activestate.com Tue Jul 3 20:23:39 2007 From: toddw at activestate.com (Todd Whiteman) Date: Tue, 03 Jul 2007 17:23:39 -0700 Subject: Building a Python app with Mozilla In-Reply-To: References: Message-ID: <468AE88B.7060902@activestate.com> Thorsten Kampe wrote: > Hi, > > I've already sent this to the Komodo mailing list (which seemed to me > the more appropriate place) but unfortunately I got no response. Hi Thorsten, I'm sorry that we (Komodo team) missed it, but I did not see such a message on the Komodo mailing list. > > I'd like to build a Python GUI app. Neither Tkinter nor Wxpython nor > PyQT are actually what I want (because the lack of GUI builders and > they don't really look good on Windows and Linux). > > Komodo itself is an excellent example of a - at least Python driven - > application that looks superb and has superior functionality so it > seems natural to use the Komodo approach for me. > > Some questions > > * Is there a simple How-To how to build a very simple (Python) app > with the Mozilla framework? Kind of "Hello world"...? > Just to detail how Komodo works, as there seems to be some confusion on this: * Komodo is based on top of Mozilla (like Firefox, Thunderbird, Democracy, etc... ) * Komodo includes PyXPCOM (XPCOM bindings to the Python language), which enables JavaScript and C++ components to easily interact with python objects inside an embedded Python. * The Komodo UI is written using XUL/JavaScript and most of the backend services are written using Python code. To enable the use of Python from within the Mozilla framework you'll need to build mozilla with the python xpcom extension enabled. For a simple overview of building and making use of PyXPCOM, see these links: * http://developer.mozilla.org/en/docs/PyXPCOM * http://developer.mozilla.org/en/docs/Building_PyXPCOM * http://developer.mozilla.org/en/docs/Creating_a_Python_XPCOM_component > * Is is reasonable to think that building a GUI with Mozilla is easier > than using Python frameworks because Mozilla does most of the GUI > work? > I would not recommend this for a small project, as there are many build related issues (especially since you'll need to build a separate Mozilla/XulRunner application for every platform you support) and a steeper learning curve for getting an application like this to work, packaged and installable. Yes, it is definitely a lot easier to build the UI using XUL and it does look consistently better across multiple platforms. Using Mozilla you'll gain access to a wealth of components with which you can take advantage of within your application. Note also that for the Firefox 3 codebase, it is expected that Python will become usable in the XUL UI, so instead of writing JavaScript you'll be able to write Python code that accesses and manipulates the user interface and the DOM. Cheers, Todd From zyzhu2000 at gmail.com Mon Jul 30 18:48:10 2007 From: zyzhu2000 at gmail.com (beginner) Date: Mon, 30 Jul 2007 22:48:10 -0000 Subject: What is the "functional" way of doing this? Message-ID: <1185835690.530367.66600@m37g2000prh.googlegroups.com> 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. Thanks, beginner From zentraders at gmail.com Fri Jul 27 22:21:03 2007 From: zentraders at gmail.com (Zentrader) Date: Sat, 28 Jul 2007 02:21:03 -0000 Subject: a simple string question In-Reply-To: References: <1185549793.114644.62170@k79g2000hse.googlegroups.com> <1185558406.916313.32980@r34g2000hsd.googlegroups.com> Message-ID: <1185589263.743811.204040@x40g2000prg.googlegroups.com> On Jul 27, 11:26 am, Wildemar Wildenburger wrote: > vedrandeko... at v-programs.com wrote: > >> If I understand you correctly you want to replace ";" by ";\n" and ":" > >> by ":\n\t\t\t\t\t\t\t". > >> Well guess what? The replace() method does just this. Have a read: > >> > > > No,that's not what I need... > > When this function detect ";" or ":" ,it must append character "\n" or > > "\n\t" ahead ":" or ";" another e.g > > > 1) text="Hello world;Hello:Hello2" > > > 2) When function detect ";" or ":" it must append character "\n" or "\n > > \t" ahead ":" or ";", so that must look like this: > > > NEW TEXT : "Hello world;\nHello:\n\t\t\n\n\n\n\n\nHello2" > > Isn't that what I said? > > Please note that appending "\n" to ";" is the very same thing as > replacing ";" with ";\n". > > Also note that the your description of the desired behavior does not > match your example. You say "append "\n\t" after ":"", but thats not > what happens in your example. There you append "\n\t\t\n\n\n\n\n\n" > instead of "\n\t". That is confusing to me. Can you explain? > > /W Confusing to me also. I read this as replace the first ";" with ";/ n", replace the first ":" with "\n\t\t\t\t\t\t\t", and on from there with different requirements. If that is the case then you have to locate the first, second, etc. and add/replace with the appropriate code. String.find and split would have to be used instead of a string.replace if you want to make different changes depending on if it is the first, second..., occurrence. From carsten at uniqsys.com Thu Jul 26 10:07:33 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 26 Jul 2007 10:07:33 -0400 Subject: Generating PDF reports In-Reply-To: References: Message-ID: <1185458853.3447.26.camel@dot.uniqsys.com> On Thu, 2007-07-26 at 16:02 +0200, marcpp wrote: > Hi i'm introducing to do reports from python, any recomendation? www.reportlab.org -- Carsten Haese http://informixdb.sourceforge.net From sebzzz at gmail.com Fri Jul 13 14:57:38 2007 From: sebzzz at gmail.com (sebzzz at gmail.com) Date: Fri, 13 Jul 2007 18:57:38 -0000 Subject: Right tool and method to strip off html files (python, sed, awk?) Message-ID: <1184353058.660535.140110@m3g2000hsh.googlegroups.com> Hi, I'm in the process of refactoring a lot of HTML documents and I'm using html tidy to do a part of this work. (clean up, change to xhtml and remove font and center tags) Now, Tidy will just do a part of the work I need to do, I have to remove all the presentational tags and attributes from the pages (in other words rip off the pages) including the tables that are used for disposition of content (how to differentiate?). I thought about doing that with python (for which I'm in process of learning), but maybe an other tool (like sed?) would be better suited for this job. I kind of know generally what I need to do: 1- Find all html files in the folders (sub-folders ...) 2- Do some file I/O and feed Sed or Python or what else with the file. 3- Apply recursively some regular expression on the file to do the things a want. (delete when it encounters certain tags, certain attributes) 4- Write the changed file, and go through all the files like that. But I don't know how to do it for real, the syntax and everything. I also want to pick-up the tool that's the easiest for this job. I heard about BeautifulSoup and lxml for Python, but I don't know if those modules would help. Now, I know I'm not a the best place to ask if python is the right choice (anyways even my little finger tells me it is), but if I can do the same thing more simply with another tool it would be good to know. An other argument for the other tools is that I know how to use the find unix program to find the files and feed them to grep or sed, but I still don't know what's the syntax with python (fetch files, change them than write them) and I don't know if I should read the files and treat them as a whole or just line by line. Of course I could mix commands with some python, find command to my program's standard input, and my command's standard output to the original file. But I do I control STDIN and STDOUT with python? Sorry if that's a lot of questions in one, and I will probably get a lot of RTFM (which I'm doing btw), but I feel I little lost in all that right now. Any help would be really appreciated. Thanks From kai.kuehne at gmail.com Sun Jul 1 23:22:17 2007 From: kai.kuehne at gmail.com (Kai Kuehne) Date: Mon, 2 Jul 2007 05:22:17 +0200 Subject: delicious.py 0.2.5: Patch to solve the 401 issue Message-ID: Hi, I just wanted to mention that I wrote a patch for delicious.py 0.2.5 that solves the 401 "bug". The delicious guys changed their api to use ssl and stuff. I already sent the patch to the author, but in case you need the library asap (as I did) you can apply it and it should work. Greetings Kai -------------- next part -------------- A non-text attachment was scrubbed... Name: delicious-0.2.5-401.patch Type: application/octet-stream Size: 836 bytes Desc: not available URL: From fabioztessitore at libero.it Tue Jul 31 15:24:13 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 31 Jul 2007 19:24:13 GMT Subject: Error with Tkinter and tkMessageBox References: <46af71b7$0$10619$4fafbaef@reader2.news.tin.it> <1185909168.055341.90910@d30g2000prg.googlegroups.com> Message-ID: <46af8c5d$0$10619$4fafbaef@reader2.news.tin.it> Il Tue, 31 Jul 2007 19:12:48 +0000, kyosohma ha scritto: > > I'm not sure, but I don't think you need the "win" variable at all. I > can get it to work as follows: > > > > from Tkinter import * > from tkMessageBox import showinfo > > def reply(): > showinfo(title='ciao', message='hello') > > Button(text='press me', command=reply).pack(fill=X) mainloop() > > > > Mike You're right. But the problem I have is always there. Tkinter doesn't work properly and I don't understand why. Thanks! From gagsl-py2 at yahoo.com.ar Tue Jul 10 22:40:02 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Jul 2007 23:40:02 -0300 Subject: SafeConfigParser can set unsafe values References: <46940a3e$0$18464$afc38c87@news.optusnet.com.au> <1184111631.293350.106340@o11g2000prd.googlegroups.com> Message-ID: En Tue, 10 Jul 2007 20:53:51 -0300, Matimus escribi?: >> Should SafeConfigParser.set() be escaping automatically? > > It seems like that would be a nice feature. However, may I offer up > that if you are setting an option and then later on getting that value > back in the same program, you probably should have used some other > storage mechanism in the first place. That is, you shouldn't store > values needed during the runtime of your program in a ConfigParser > instance. > > As far as I can tell, these are the valid use cases for ConfigParser: > > 1. Use ConfigParser to read values from an config file > - This implies .read() followed by .get()s > 2. Use ConfigParser to create and write a config file > - This implies .set()s followed by .write() > 3. Use ConfigParser to read, modify and write a config file. > - This implies .read() followed by .get()s followed by .set()s > followed by .write() > > None of the above use cases involve calling .get() after a .set(). > Perhaps I am missing a use case though. > > While I think you have technically pointed out a potential bug, I'm > not sure why it matters. Such a bug only comes about for (IMHO) flawed > use cases. This not only happens when get() after a set(), but with all the use cases above. An intervening write()/read() does not change things. But I'm not sure it is a bug really. If all % were escaped automatically, there is no way to write a templatized value. Maybe SafeConfigParser.set should grow an escape argument, controlling whether one wants the value escaped or not. For compatibility reasons should default to False, for usability reasons should default to True. -- Gabriel Genellina From alpha04 at netvigator.com Sat Jul 21 22:13:22 2007 From: alpha04 at netvigator.com (Andrey) Date: Sat, 21 Jul 2007 19:13:22 -0700 Subject: simpleJSON pack binary data Message-ID: Hi I donno if this is the right place to ask for this question, anyway.... Is it possible to pack binary data into simplejson? d={} d['date'] = xxxxxx d['name'] = xxxxxx d['size'] = xxxxx d['imageBinaryDataJpeg'] = jpegBinaryDataFromcStringIOStringIO simplejson.dumps(d) when i do this, it raises a UTF8 decode error, probably about the binary image data My question is, anyone will suggest a workaround to this error? i really like to pack my raw image data into the JSON, so my other programming script can read the array easily Thanks An K From phus at live.com Sat Jul 14 22:37:20 2007 From: phus at live.com (jigloo) Date: 14 Jul 2007 19:37:20 -0700 Subject: Fastest way to convert a byte of integer into a list In-Reply-To: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> Message-ID: <1184289360.370865.173830@z28g2000prd.googlegroups.com> On 7 13 , 6 34 , Godzilla wrote: > Hello, > > I'm trying to find a way to convert an integer (8-bits long for > starters) and converting them to a list, e.g.: > > num = 255 > numList = [1,1,1,1,1,1,1,1] > > with the first element of the list being the least significant, so > that i can keep appending to that list without having to worry about > the size of the integer. I need to do this because some of the > function call can return a 2 lots of 32-bit numbers. I have to find a > way to transport this in a list... or is there a better way? my clone *bin* function from python3000 def _bin(n, count=32): """returns the binary of integer n, using count number of digits""" return ''.join([str((n >> i) & 1) for i in range(count-1, -1, -1)]) From fumanchu at amor.org Mon Jul 16 12:50:50 2007 From: fumanchu at amor.org (fumanchu) Date: Mon, 16 Jul 2007 09:50:50 -0700 Subject: Re-raising exceptions with modified message In-Reply-To: References: <1183863713.876365.111820@57g2000hsv.googlegroups.com> <1184239885.828717.271410@r34g2000hsd.googlegroups.com> <1184258925.321462.50270@k79g2000hse.googlegroups.com> <1184345588.791872.79010@d55g2000hsg.googlegroups.com> Message-ID: <1184604650.131033.288000@o11g2000prd.googlegroups.com> On Jul 15, 2:55 am, Christoph Zwerschke wrote: > Here is a simple solution, but it depends > on the existence of the args attribute that > "will eventually be deprecated" according > to the docs If you don't mind using .args, then the solution is usually as simple as: try: Thing.do(arg1, arg2) except Exception, e: e.args += (Thing.state, arg1, arg2) raise No over-engineering needed. ;) Robert Brewer System Architect Amor Ministries fumanchu at amor.org From gagsl-py2 at yahoo.com.ar Wed Jul 25 15:19:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 25 Jul 2007 16:19:53 -0300 Subject: How to create a single executable of a Python program References: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> Message-ID: En Wed, 25 Jul 2007 14:20:36 -0300, Larry Bates escribi?: > NicolasG wrote: >> I'm trying to create a executable file using py2exe . Unfortunately >> along with the python executable file it also creates some other files >> > If you want a single file to distribute, look at Inno Installer. Use > it to make a single, setup.exe out of all the files that come out of > py2exe > along with documentation, shortcuts, etc. that a good modern application > needs. Exactly. There is even a sample script (located at samples/extending in the py2exe installation), it generates automatically the InnoSetup script. If you prefer to use NSIS, see this page on the py2exe wiki: http://www.py2exe.org/index.cgi/SingleFileExecutable -- Gabriel Genellina From jstroud at mbi.ucla.edu Fri Jul 13 15:28:47 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 13 Jul 2007 12:28:47 -0700 Subject: Pass by reference or by value? In-Reply-To: <1184353832.314694.228270@n60g2000hse.googlegroups.com> References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> Message-ID: Robert Dailey wrote: > Hi, > > I noticed in Python all function parameters seem to be passed by > reference. This means that when I modify the value of a variable of a > function, the value of the variable externally from the function is > also modified. > > Sometimes I wish to work with "copies", in that when I pass in an > integer variable into a function, I want the function to be modifying > a COPY, not the reference. Is this possible? > > Thanks. > Not only is this possible, that is actually what happens with ints! -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From kevin.t.ryan at gmail.com Fri Jul 27 21:25:07 2007 From: kevin.t.ryan at gmail.com (Kevin T. Ryan) Date: Sat, 28 Jul 2007 01:25:07 -0000 Subject: Packages In-Reply-To: References: <1185576929.136179.174440@b79g2000hse.googlegroups.com> Message-ID: <1185585907.799322.128240@19g2000hsx.googlegroups.com> On Jul 27, 7:21 pm, Alex Popescu wrote: > "Kevin T. Ryan" wrote innews:1185576929.136179.174440 at b79g2000hse.googlegroups.com: > > > > > Hi All - > > > I'm having a problem and I hope you can help. I can't seem to import > > packages from within the package substructure as I think I should be > > able to. For example, I create a directory structure as follows: > > > testpkg > > __init__.py [empty] > > testsub1/ > > __init__.py [empty] > > bad.py [import testpkg.testsub2.good; print "hello from bad"] <- > > error > > testsub2/ > > __init__.py [empty] > > good.py [print "hello from good"] > > > Whenever I try to run bad.py (just python bad.py from within the > > testsub2 subdirectory or from above the testpkg directory) I get an > > error. For example: > > > $ python testpkg/testsub1/bad.py > > Traceback (most recent call last): > > File "testpkg/testsub1/bad.py", line 1, in > import testpkg.testsub2.good > > ImportError: No module named testpkg.testsub2.good > > > How can I get my subpackages to recognize other subpackages in the > > same top-level package? Thanks in advance!! > > > Kevin > > When executing bad.py python will be looking for imported module (in the > standard path) and then in your current directory (so to find it you > should have testsub1/testpkg/testsub2). You can solve this by adding > your toplevel director (the parent of testpkg) to the PYTHONPATH. > > bests, > ./alex > -- > .w( the_mindstorm )p. Ok, thanks. I was under the impression that this wouldn't be necessary (eg, see http://docs.python.org/tut/node8.html#SECTION008420000000000000000), but perhaps I was wrong. Thanks again for the advice :) From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jul 11 06:57:33 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 11 Jul 2007 12:57:33 +0200 Subject: What is the most efficient way to test for False in a list? In-Reply-To: <7x8x9oogjj.fsf@ruckus.brouhaha.com> References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <7x7ipajvst.fsf@ruckus.brouhaha.com> <5fejp2F3cp3igU1@mid.individual.net> <5feju0F3c7pd1U1@mid.uni-berlin.de> <7xsl7xmxcl.fsf@ruckus.brouhaha.com> <7x8x9oogjj.fsf@ruckus.brouhaha.com> Message-ID: <4694b780$0$22393$426a74cc@news.free.fr> Paul Rubin a ?crit : > Duncan Booth writes: >>> status = not (False in list) >> That is an equality test, not an identity test: >> >>>>> False in [0] >> True > > Arrggggh! Strongly typed language, my eye ;-) Thanks. We're quite a few to still think that the introduction of a boolean type in Python was perhaps not such a great idea. From S.Mientki-nospam at mailbox.kun.nl Thu Jul 26 18:01:05 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 27 Jul 2007 00:01:05 +0200 Subject: removing items from a dictionary ? In-Reply-To: <7xabtikhe1.fsf@ruckus.brouhaha.com> References: <46A8EFF5.4060600@mailbox.kun.nl> <7xabtikhe1.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Stef Mientki writes: >>> for net in Nets.keys(): >>> # Nets.iterkeys() would avoid building the list >>> # but that runs the same risks as your original >>> if net.upper() in in Eagle_Power_Nets : >>> del Nets[net] >>> >> thanks Steve, >> that does the job. > > Depending on the relative sizes of those dicts, maybe > you want to try rebuilding instead of deleting. Untested: > > Nets = dict((k,v) for k,v in Nets.itervalues() > if k.upper() not in Eagle_Power_Nets) thanks Paul, this is a very interesting idea, especially while my dictionaries are quit small, and I have to do some more complex things other than delete. cheers, Stef Mientki From gagsl-py2 at yahoo.com.ar Thu Jul 26 05:14:27 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 26 Jul 2007 06:14:27 -0300 Subject: How to create a single executable of a Python program References: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> <1185431871.579595.234830@l70g2000hse.googlegroups.com> Message-ID: En Thu, 26 Jul 2007 03:37:51 -0300, NicolasG escribi?: > I "want" to create a single file for two of my very simple/small > programs. For very simple/small programs I don't need to distribute > documentation, shortcuts etc.. I just want a single file to run ! See http://www.py2exe.org/old/#the-bundle-option -- Gabriel Genellina From kyosohma at gmail.com Wed Jul 25 14:42:24 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 25 Jul 2007 11:42:24 -0700 Subject: wxGlade: Who knows how to drive this application? In-Reply-To: <73447$46a79894$d443bb3a$28145@news.speedlinq.nl> References: <73447$46a79894$d443bb3a$28145@news.speedlinq.nl> Message-ID: <1185388944.954526.22020@b79g2000hse.googlegroups.com> On Jul 25, 1:44 pm, Stef Mientki wrote: > Roel Schroeven wrote: > > Steve Holden schreef: > >> I've been trying to use wxGlade recently and I am finding it something > >> of a challenge. Is there any user who finds the user interface > >> satisfactory and the operation of the program predictable? > > > I haven't used it much, but it always seems to be a pain to use the > > interface. I actually thought it was just me; I'm glad to see that at > > least one other person has problems with it too. > > count me too, I didn't even got it to work ;-) > > Stef The people on the wxPython list usually list Boa Constructor, SPE or Dabo before they mention wxGlade...so my guess is that most of them don't use it either. Mike From dvd_km at yahoo.com Sat Jul 14 19:41:29 2007 From: dvd_km at yahoo.com (dvd_km) Date: Sat, 14 Jul 2007 16:41:29 -0700 Subject: www.OutpatientSurgicare.com/video/ Message-ID: <1184456489.989169.118850@m37g2000prh.googlegroups.com> www.OutpatientSurgicare.com/video/ Outpatient Doctors Surgery Center is committed to offering the healthcare the community needs. We offer patients a meaningful alternative to traditional surgery. This state-of-the-art outpatient surgery center, located in the heart of Orange County, at 10900 Warner Avenue, Suite 101A, Fountain Valley, Ca 92708, offers the latest innovations in outpatient surgery and technology. Please Call For Our Special Cash Discount Toll Free: 1-877-500-2525 Please Visit Our Websites: We offer extreme cosmetic surgery makeover packages. http://www.SurgeonToTheStars.com http://www.1cosmeticsurgery.com Specializing in the cure of hyperhidrosis, sweaty palms, underarm and foot sweating. http://www.CuresweatyPalms.com http://www.ControlExcessiveSweating.com No. 1 Weight Loss Surgery Center http://www.ControlWeightLossNow.com http://www.FreeLapBandSeminar.com Hernia Treatment Center http://www.HerniaDoc.com Take care of your feet http://www.CureFootPain.com The Experts in CARPAL TUNNEL SYNDROME http://www.CureHandPain.com Accidental Urine Leaks ? End Urinary Incontinence http://www.WomanWellnessCenter.com Hemorrhoid Treatment Center http://www.hemorrhoidtreatmentcenter.com From samwyse at gmail.com Sun Jul 29 11:09:38 2007 From: samwyse at gmail.com (samwyse) Date: Sun, 29 Jul 2007 15:09:38 -0000 Subject: Python 2.5.1 can't find win32file? In-Reply-To: References: <1185628601.992750.55990@e16g2000pri.googlegroups.com> <1185634068.634813.187350@e16g2000pri.googlegroups.com> Message-ID: <1185721778.781676.283140@r34g2000hsd.googlegroups.com> On Jul 28, 12:14 pm, Jay Loden wrote: > samwyse wrote: > > Interestingly enough, this works: > > > C:\Python25>path=%path%;C:\Python25\Lib\site-packages\pywin32-210- > > py2.5-win32.eg > > g\pywin32_system32 > > > C:\Python25>python > > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > > (Intel)] on win32 > > Type "help", "copyright", "credits" or "license" for more information. > >>>> import win32file > > > It looks like the system search path isn't getting updated so that > > PYWINTYPES25.DLL can be found when win32file.pyd is loaded. > > > Anyone have any ideas? > > If you just want to update your PATH, you can do that from My Computer -> Properties -> Advanced -> Environment Variables and just update PATH for your user (or all users if you prefer). > > -Jay Well, I was hoping for something a bit more general. I'd've thought that anyone loading a DLL would set the Windows path beforehand, and that it would all be magically taken care of during the installation. For now, I'm putting this before my 'import' statement: os.environ['PATH'] += r';C:\Python25\Lib\site-packages\pywin32-210- py2.5-win32.egg\pywin32_system32' From noagbodjivictor at gmail.com Thu Jul 19 03:31:06 2007 From: noagbodjivictor at gmail.com (nvictor) Date: Thu, 19 Jul 2007 07:31:06 -0000 Subject: class C: vs class C(object): Message-ID: <1184830266.181714.183320@z24g2000prh.googlegroups.com> Hi, I'm not an experienced developer, and I came across this statement by reading a code. I search for explanation, but can't find anything meaningful. I read the entire document written by python's creator about the features of version 2.2 The one named unifying types and classes. But This document only blew my head away. I ended here and think somebody can explain me more about this. The only thing I have noticed is that when you do dir(C) on a classic class you get a bunch of attributes; and when you do the same thing on a class defined using class C(object), you get less attributes. Thanks for all replies. From cfpete at gmail.com Mon Jul 16 23:16:06 2007 From: cfpete at gmail.com (cfpete at gmail.com) Date: Tue, 17 Jul 2007 03:16:06 -0000 Subject: how to compile python to have gtk and Tkinter modules in Linux environment. Message-ID: <1184642166.978342.154660@o11g2000prd.googlegroups.com> Hello, How do I go about to have python compiled from source so that I can import gtk and Tkinter modules. Those don't seem to be included when I use the default ./configure or python setup.py. Thanks in advance, -Peter From malaclypse2 at gmail.com Sun Jul 22 21:54:23 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Sun, 22 Jul 2007 21:54:23 -0400 Subject: Where is the collections module? In-Reply-To: References: Message-ID: <16651e80707221854n41219e6bo4dad9076efd1b599@mail.gmail.com> On 7/22/07, Gordon Airporte wrote: > Gordon Airporte wrote: > > I was going to try tweaking defaultdict, but I can't for the life of me > > find where the collections module or its structures are defined. Python > > 2.5. > > Thanks all. I was expecting it in Python. Time to dust off my C :-P If you'd rather work with a pure python implementation, Jason Kirtland has written one on the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/523034 -- Jerry From gslindstrom at gmail.com Sat Jul 14 18:20:46 2007 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Sat, 14 Jul 2007 17:20:46 -0500 Subject: Creating Packages Message-ID: Hello, All- I have written a class that allows me to create and manipulate data segments (the type one deals with when reading/writing text files); validating fields, serialization, etc. I would like to put this together as a module and release it to the community while I expand on the features. Is there a preferred way to do this? I have read the docutil information but recall hearing about Python Eggs being the new way to do such things. I have no intention of starting/continuing another debate (vim/emacs, perl/python, take your pick), but would like information/help as to my next step. I believe this package would be helpful to those of us dealing with text files. How do I go about making it available? Thanks, --greg -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Fri Jul 13 02:24:08 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 13 Jul 2007 16:24:08 +1000 Subject: Understanding python functions - Instant Python tutorial References: Message-ID: <878x9kkeif.fsf@benfinney.id.au> Chris Carlen writes: > I don't understand Hetland's terminology though, when he is speaking > of "binding" and "reference." Actually, Hetland's entire first > paragraph is unclear. > > Can anyone reword this in a way that is understandable? I've had some success with the following way of thinking about it. Some languages have "variables", which act like boxes that have names etched on the side. Once created, the box can contain an object, and it can be inspected while in the box; to change the variable, you throw out the object and put a different object in the same box. That's not how Python works. Every value is an object; the assignment operator binds a name to an object. This is more like writing the name on a sticky-note, and sticking it onto the object. * The object itself doesn't change or "move". * The object can be referred to by that name, but isn't "inside" the name in any way. * Assigning multiple names to the same object just means you can refer to that same object by all those names. * When a name goes away, the object still exists -- but it can't be referred to if there are no longer any names left on it. * Assigning a different object to an existing name just means that the same sticky-note has moved from the original object to the new one. Referring to the same name now references a different object, while the existing object keeps all the other names it had. When you pass an object as a parameter to a function, the object receives a new sticky-label: the parameter name under which it was received into the function scope. Assignment is an act of binding a name to an object; no new object is created, and it still has all the other names it had before. When the function ends, all the names that were created inside that function's scope disappear; but the objects still exist under any names they had previously, and if you use those names you'll be looking at the same object as was manipulated inside the function. When the object has lost all its names -- for example, they've disappeared because the scope they were in has closed, or they've been re-bound to other objects -- they can no longer be referenced. At some point after that, the automatic garbage collection will clean that object out of memory. This sticky-note analogy, and the behaviour described, is what is meant by "references". A name refers to an object; changing the object means that by referring to that same object under its different names, you will see the same, modified, object. In Python, all names are references to objects. The assignment operator '=' doesn't create or change a "variable"; instead, it binds a name as reference to an object. All functions receive their parameters as the existing object with a new name -- a reference to that object, just like any other name. Hope that helps. -- \ "If you ever teach a yodeling class, probably the hardest thing | `\ is to keep the students from just trying to yodel right off. | _o__) You see, we build to that." -- Jack Handey | Ben Finney From http Thu Jul 26 21:33:03 2007 From: http (Paul Rubin) Date: 26 Jul 2007 18:33:03 -0700 Subject: zip() function troubles References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> <7xir86wx0p.fsf@ruckus.brouhaha.com> <1185499500.807041.60580@g4g2000hsf.googlegroups.com> Message-ID: <7xzm1ieils.fsf@ruckus.brouhaha.com> Istvan Albert writes: > I tested this on a linux server system with 4Gb of RAM > a = [ 0 ] * 10**7 > takes miliseconds, but say the > b = zip(a,a) > will take a very long time to finish: Do a top or vmstat while that is happening and see if you are swapping. You are allocating 10 million ints and 10 million tuple nodes, = 20 million objects. Although, even at 100 bytes per object that would be 1GB which would fit in your machine easily. Is it a 64 bit cpu? From bdesth.quelquechose at free.quelquepart.fr Sat Jul 21 08:59:52 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Jul 2007 14:59:52 +0200 Subject: Technology solutions for Ruby? In-Reply-To: <1185301513.099804.202870@j4g2000prf.googlegroups.com> References: <469B059C.2050802@cesmail.net> <1184606739.054580.197740@g37g2000prf.googlegroups.com> <469be0e5$0$9556$426a74cc@news.free.fr> <1185301513.099804.202870@j4g2000prf.googlegroups.com> Message-ID: <46a67460$0$662$426a74cc@news.free.fr> vasudevram a ?crit : > Bruno Desthuilliers wrote: > > >>s/some/great/g >> >>Both Ruby and Python are known for this. > > Thanks for the info. This is not exactly a scoop, you know ?-) >>I'd say that - wrt/ "advanced" programming tricks - *most* of what you > > can do with one can be done with the other - but usually in a *very* >> different way. While Ruby and Python have similar features and may >> look very similar at first sight, their respective object models are >> totally different. > > Can you briefly explain what you mean by "their respective object > models are totally different"? Do you refer to how the object- > orientation (classes, objects, etc.) is implemented in the two > languages? Obviously, yes. From http Sat Jul 21 02:40:46 2007 From: http (Paul Rubin) Date: 20 Jul 2007 23:40:46 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <468565a0$0$3686$426a74cc@news.free.fr> <7xvecumrte.fsf@ruckus.brouhaha.com> <1i13w96.kyyobph71qxrN%aleax@mac.com> <7xwsx63we6.fsf@ruckus.brouhaha.com> <878x9llv5x.fsf@benfinney.id.au> <5fovr8F3eglkfU1@mid.uni-berlin.de> <7x1wf8kc6l.fsf@ruckus.brouhaha.com> <5gb5u1F3fip9cU1@mid.uni-berlin.de> <7xr6n3pjhi.fsf@ruckus.brouhaha.com> <5gbrfsF3djtr2U1@mid.uni-berlin.de> Message-ID: <7x644e6yz5.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > > Come on, this is real-time embedded software, > Since when did we restrict ourselves to such an environment? I was under the > impression that this thread is about the merits and capabilities of static > type-checking? One branch of the discussion brought up Spark Ada, and I think the cited article said they used the Ravenscar profile, which means embedded applications. > No, I don't buy that. As I said before: for the most trivial of > tasks that might be a good thing. But I'm not convinced that > restricting one self in such a manner for more complex tasks isn't > going to be a better development path. There are applications where you care first and foremost about the reliability of the end result, and accept whatever difficulty that might cause for the development path. Not all programming is Visual Basic. From robert.rawlins at thinkbluemedia.co.uk Thu Jul 19 04:52:36 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Thu, 19 Jul 2007 09:52:36 +0100 Subject: Log Memory Usage Message-ID: <004201c7c9e2$276598b0$7630ca10$@rawlins@thinkbluemedia.co.uk> Hello Guys, I have an embedded application with a suspected memory leak which I'm trying to confirm. You see, the application seems to crash unexpectedly and when looking at the resource consumption after the crash system memory has crept up to nearly 100%. However this takes quite a long time to occur, so sitting and watching the application run isn't a very effective way of doing it, so I'm looking for the best way to log the system memory every minute or two. I have a scheduled event which occurs every minute, i just need a code solution to give me the systems current memory consumptions details, is there perhaps something in the os module? Thanks for any suggestions guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From simoncelen at gmail.com Fri Jul 27 13:11:08 2007 From: simoncelen at gmail.com (simonbun) Date: Fri, 27 Jul 2007 17:11:08 -0000 Subject: Compiling python2.5.1 results in 3.5MB python lib? Message-ID: <1185556268.287077.258080@d55g2000hsg.googlegroups.com> Hi all, I'm compiling 2.5.1 and end up with a 3.5MB libpython2.5.so file. I seem to remember it should be somewhere around the 1MB mark. What could be causing this? I'm using ./configure --enable-shared This is a problem for me seeing as i'm using apache+mod_python to serve web content. Each apache child process incorporates libpython and ends up starting at 7MB, which is quite large. Especially considering the framework + code I'm using adds another 10+MB. Any help is appreciated. Let me know if i need to give some more information. From supercooper at gmail.com Mon Jul 23 15:57:44 2007 From: supercooper at gmail.com (supercooper) Date: Mon, 23 Jul 2007 12:57:44 -0700 Subject: shutil.copyfile problem for GIS data In-Reply-To: References: Message-ID: <1185220664.333465.255000@n60g2000hse.googlegroups.com> import shutil import os src = "c:\mydata\test\mygeo.mdb" dst = "v:\updated\data\mygeo.mdb" shutil.copyfile(src,dst) This should totally work, do it all the time, but no one can be connected to the database, ie have ArcMap or ArcCatalog open at the time of copy, or the .ldb lock will kill it. I do all of my copies in the early AM. From aboudouvas at panafonet.gr Mon Jul 30 10:58:56 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Mon, 30 Jul 2007 07:58:56 -0700 Subject: Replacing overloaded functions with closures. Message-ID: <1185807536.021216.278500@22g2000hsm.googlegroups.com> Hi, i am trying, to no avail yet, to take a C#'s overloaded functions skeleton and rewrite it in Python by using closures. I read somewhere on the net (http://dirtsimple.org/2004/12/python-is- not-java.html) that in Python we can reduce code duplication for overloaded functions by using closures. I do not quite understand this. Let's say we have the following simple C# code: int func(int i) { return i * 2; } string func(string s) { return s + s; } bool func(bool f) { return !f; } I wasn't able to find a way to express this thing in closures. I even tried to have the parameters i, s and f as parameters with default arguments with None value in the inner function and there to check for the None and do the needed work but i am not sure if this is the correct solution. Any help ? thanks in advance. From steve at holdenweb.com Wed Jul 4 08:29:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Jul 2007 08:29:26 -0400 Subject: ActivePython In-Reply-To: <1183522237.693582.210770@i38g2000prf.googlegroups.com> References: <5f0g54F396io7U1@mid.individual.net> <1i0p0l1.152ee0mcffr6aN%aleax@mac.com> <1183522237.693582.210770@i38g2000prf.googlegroups.com> Message-ID: tleeuwenburg at gmail.com wrote: > On Jul 4, 2:03 pm, a... at mac.com (Alex Martelli) wrote: >> Frank Swarbrick wrote: >>> Why might one choose to use ActivePython instead of using the free CPython? >> I believe ActivePython is also free, and it's packaged up differently >> (with more 3rd party modules accompanying it than the standard Python >> distribution), which might make it attractive to some. Also, I believe >> ActivePython is also available as a pre-built binary for some platforms >> for which CPython is only distributed as sources (e.g., Solaris), and >> again this difference may be seen as favorable by some. >> >> Alex > > Well, Komodo is a nice enough IDE, so you might choose to use > ActivePython for integration reasons, and maybe it's a little easier > on Windows. > > However, I would have thought that if you were planning to distribute > an application, you would want to choose CPython for maximum > interoperability with external packages. > Not only that, but the last time I looked the ActivePython distribution doesn't allow redistribution at all (i.e. it's not technically open source). > ActivePython claims to be ready to install across multiple platforms > (as is CPython) so perhaps a little more work has gone into making a > consistent experience across operating systems. > > I have to say, I am just guessing and would love to hear from an > expert in the area on this topic. The ActiveState web page doesn't > really talk about their reasons very much. > ActiveState do produce a convenient package for many purposes, and I have used it myself in the past, but if you want to redistribute then it isn't a permitted starting point. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- 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 Wed Jul 25 17:58:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Jul 2007 17:58:44 -0400 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185396904.642985.141300@z24g2000prh.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> <1185396904.642985.141300@z24g2000prh.googlegroups.com> Message-ID: walterbyrd wrote: > On Jul 25, 2:12 pm, Carsten Haese wrote: > >> Also, CherryPy's requirements are very >> minimal. > > In terms of memory and CPU, maybe. But I think that *requires* apache > 2.x and a very recent version of mod_python. By web-hosting > standards, those are very steep requirements. > You are wrong. CherryPy is a standalone web server environment. 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 wbrehaut at mcsnet.ca Fri Jul 13 14:08:52 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Fri, 13 Jul 2007 12:08:52 -0600 Subject: Understanding python functions - Instant Python tutorial References: <4697AB4F.80708@freakmail.de> Message-ID: On Fri, 13 Jul 2007 18:49:06 +0200, Wildemar Wildenburger wrote: >Wildemar Wildenburger wrote: >> x = [1, 2, 3] >> y = [1, 2, 3] >> id(x), id(y) >> x == y >> x is y >> >Ooops! > >Make that: > >x = [1, 2, 3] >y = [1, 2, 3] >id(x); id(y) >x == y >x is y > >(had to be a semicolon there) Not "had to be" since a discerning reader will note that the two values in the list: >>> id(x), id(y) (19105872, 19091664) are different, and can guess that id() means "address of". But "nicer to be" perhaps since it makes it even more clea rto discerning readers, and more likely clear to others. ;-) >>> id(x); id(y) 19105872 19091664 wwwayne From erik at myemma.com Mon Jul 16 02:31:18 2007 From: erik at myemma.com (Erik Jones) Date: Mon, 16 Jul 2007 01:31:18 -0500 Subject: How to determine which method was used in an inheritance heirarchy? In-Reply-To: <1184565220.674041.270790@o61g2000hsh.googlegroups.com> References: <1184559788.712146.238190@q75g2000hsh.googlegroups.com> <1184565220.674041.270790@o61g2000hsh.googlegroups.com> Message-ID: On Jul 16, 2007, at 12:53 AM, Michele Simionato wrote: > On Jul 16, 7:18 am, Erik Jones wrote: >> On Jul 15, 2007, at 11:23 PM, Michele Simionato wrote: >> >>> On Jul 16, 5:51 am, Erik Jones wrote: >>>> Say you're given a call event frame for a method call. How can you >>>> tell if the code being executed came from a super class of the >>>> object >>>> or class the method was called on? >> >>>> Erik Jones >> >>> You look if the method was defined in self.__class__.__dict__. >> >>> Michele Simionato >> >> That doesn't seem to cover calling super class __init__ methods. >> > > I am probably missing something. In the following code the > method check_init checks if the current instance > possess an __init__ or if it just inherits one > from the ancestors. Is this what you want? > > class B(object): > def __init__(self): > 'something' > def check_init(self): > if '__init__' in self.__class__.__dict__: > print 'possesses __init__' > else: > print 'inherits __init__' > > class C(B): > 'something else' > def __init__(self): > print 'calling C.__init__' > > class D(B): > pass > > c = C() > d = D() > > c.check_init() #possesses __init__ > d.check_init() #inherits __init__ Ok, I see how I was pretty vague with my original questions. Given the pattern where you need to call a base class's constructor (or, other overriden method of the same name as that being called on the child class object): class A(object): def __init__(self): print self.__class__.__name__ class B(A): def __init__(self): A.__init__(self) print self.__class__.__name__ B() This will output: B B How can I get A B 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 shahmed at sfwmd.gov Mon Jul 16 13:47:30 2007 From: shahmed at sfwmd.gov (Ahmed, Shakir) Date: Mon, 16 Jul 2007 13:47:30 -0400 Subject: shutil.copyfile problem for GIS data In-Reply-To: Message-ID: <14A2A120D369B6469BB154B2D2DC34D20855B29C@EXCHVS01.ad.sfwmd.gov> Need help to copy a personal geodatabase from one location to another: Trying to copy a personal geodatabase from one location to another location where all the users are retrieving data from the second location: 1. I can copy over the updated personal geodatabase to the working location and overwrite it, though the file is opened by ArcGIS users (Local Installation of Arc GIS on the users computers). 2. But problem is that I can't copy over if the same updated personal geodatabase to the working location, if users uses that same geodatabase through CITRIX - ArcGIS ( user does not have permission to edit the data) 3. the python script which I am using as follows: import shutil import os src = "c:\mydata\test\mygeo.mdb" dst = "v:\updated\data\mygeo.mdb" shutil.copyfile(src,dst) I highly appreciate if any one of you can help me and give me a direction that I can solve this problem. Thanks in advance. Shak From aleax at mac.com Tue Jul 31 11:41:45 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 31 Jul 2007 08:41:45 -0700 Subject: Reading a two-column file into an array? References: <1185857837.610635.206270@e9g2000prf.googlegroups.com> <5h81mbF3j641tU1@mid.uni-berlin.de> Message-ID: <1i23xec.1r6z2ai14ntdgxN%aleax@mac.com> Marc 'BlackJack' Rintsch wrote: > On Mon, 30 Jul 2007 21:57:17 -0700, Nagarajan wrote: > > > a = [] > > import csv > > reader = csv.reader(open("filename", "r"), delimiter='\t' ) > > for row in reader: > > a.append( row ) > > I would keep a reference to the file to close it properly and the loop can > be replaced by a call to `list()`: > > import csv > > def main(): > data_file = open('filename', 'rb') > a = list(csv.reader(data_file, delimiter='\t')) > data_file.close() That's what 2.5's with statement is all about...: from __future__ import with_statement def main(): with open('filename', 'rb') as f: return list(csv.reader(f, delimiter='\t')) Alex From kyosohma at gmail.com Fri Jul 13 16:29:55 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 13 Jul 2007 20:29:55 -0000 Subject: help reading cookie values In-Reply-To: References: Message-ID: <1184358595.508448.291700@q75g2000hsh.googlegroups.com> On Jul 13, 3:08 pm, Sean wrote: > I am trying to read a cookie I set but I am not sure if I really set > it correctly or I am not reading it correctly. I was given the > following instructions to set the cookie. It appears to be working > because in Firefox browser I see the cookie listed for my domain > > > you set a cookie in a pythonscript like: > > context.REQUEST.RESPONSE.setCookie('cookie_name', 'some value', > > expires=(DateTime() + 365).toZone('GMT').rfc822(), path='/') > > I have been searching everywhere to find information on reading the > cookie value that I set. I used the following code I found which > returns 'no cookiez' in spite of the fact that I see the cookie in my > browser's cookie listing. I must be doing something wrong in the way > I am testing for its existence > > import Cookie > import os > thiscookie = Cookie.SimpleCookie() > > if 'HTTP_COOKIE' in os.environ: > #if os.environ.has_key('HTTP_COOKIE'): I tried this way also > > thiscookie.load(os.environ['HTTP_COOKIE']) > > a_code = thiscookie['my_cookie'].value > > return a_code > > else: > > return 'no cookiez' This site looks like it has some good information on Cookie handling (see "cookielib and ClientCookie Example" section: http://www.voidspace.org.uk/python/recipebook.shtml Mike From rschroev_nospam_ml at fastmail.fm Sat Jul 28 05:15:50 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 28 Jul 2007 09:15:50 GMT Subject: wxGlade: Who knows how to drive this application? In-Reply-To: References: Message-ID: Alberto Griggio schreef: > Hello, > >> I've been trying to use wxGlade recently and I am finding it something >> of a challenge. Is there any user who finds the user interface >> satisfactory and the operation of the program predictable? >> >> If so I would love to hear from you. > > Do you have some specific example of what you mean? > Sure, wxGlade has bugs and isn't always in sync with the latest wxPython > changes (usually the CVS version is better in this respect), but > suggestions on how to improve it are always welcome... Here are some things I can think of, in no particular order: - I have to find and select the frame I'm working on in the tree to display the preview of that frame. That's especially cumbersome if I'm playing with the properties of a widget to see their effect; then I find myself constantly switching between the frame and the widget. Solutions I can think of: - maybe a "Refresh"-functionality in the preview-window (via a right-click, F5, ctrl-R, window system menu?). - possibility to have multiple Properties window open. - a "Preview" in each Properties window; when used with a widget that doesn't support it, work up the tree until a widget is encountered that does support a preview. - Put a Preview-item in the right-click menu for the frame widget in the tree window. - Changes in preferences don't take effect until wxGlade is restarted. It's workable, but it would be nice if e.g. a change in "Default border width for widgets" would take effect immediately. - It's cumbersome to change the order of widgets in a sizer. Ideally I should be able to drag and drop the widgets into place in the tree window and/or the design window. - I think drag and drop should also work to move widgets from one sizer to another in the tree window. If the target sizer doesn't have a free slot, one should be added automatically. - Suppose I have a frame; the frame contains a sizer with a number slots containing widgets and/or other sizers. Now I realize I need a panel in the frame as a container for all sizers and widgets. I should have thought of that earlier of course, but I still feel there should be an easy way to insert it in the right place in the tree. - Often the keyboard shortcuts (del, ctrl-x, ctrl-v) don't seem to work in the design window. - If I select a widget in the tree, it is visually marked in the design window. I think that should happen for sizers too. - Often when you add an empty slot, you have to make the designer window larger, to show the new slot. I think that should happen automatically. - In general, I find myself switching between the properties window, the tree window and the design window an awful lot of times. I'm not sure how to improve that. - Spacers have the same color as panels, making them invisible in the design window when places on them. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From S.Mientki-nospam at mailbox.kun.nl Mon Jul 16 04:13:42 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 16 Jul 2007 10:13:42 +0200 Subject: running a Delphi part from Python ? Message-ID: <889c1$469b275c$d443bb3a$2876@news.speedlinq.nl> I'm starting to get used to wxPython (coming from Delphi), and it seems it can do almost everything I need. Now one thing I'm missing is a good RichEditor. I've a good RichEdit in Delphi ... ... so what are the possibilities to include that in Python ? The most simple for me to do, seems to create a DLL, which contains the RichEdit and all it's controls, as an MDI child window. So how could I interface to some Delphi-DLL in Python ? And maybe even more complicated, is a MDI-child written in a Delphi-DLL, identical to the wxPython MDI-child ( If I remember well, I read somewhere that MDI is implemented in it's own manner, not equal to the standard Windows MDI interface) thanks, Stef Mientki From rrr at ronadam.com Tue Jul 17 14:26:20 2007 From: rrr at ronadam.com (Ron Adam) Date: Tue, 17 Jul 2007 13:26:20 -0500 Subject: Break up list into groups In-Reply-To: <1184694533.380918.169640@m37g2000prh.googlegroups.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> <1184694533.380918.169640@m37g2000prh.googlegroups.com> Message-ID: <469D09CC.3080402@ronadam.com> Matimus wrote: > I did some more experimenting and came up with the code below. It > shows several methods. When run, the script tests the robustness of > each method (roughly), and profiles it using timeit. The results from > running on my laptop are shown below the code. Try this one... def groupdata(data, fn): start = 0 for n in range(1, len(data)): if fn(data[n]): yield data[start:n] start = n yield data[start:] print list(groupdata(l, lambda x: x & 0x80)) Cheers ;-) Ron > > seqs = [# Original: > [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, > 12, 13, > 0xF0, 14, 0xF1, 15], > # Single entry: > [0xF0, 1, 2, 3], > # empty > [], > # No values with 0x80 set > [1, 2, 3, 14, 15], > # Does not start with a value that has 0x80 set > [1, 2, 3, 14, 15, 0xF0, 1, 2, 3]] > > expected = [# Original: > [[0xF0, 1, 2, 3], [0xF0, 4, 5, 6], [0xF1, 7, 8], [0xF2, 9, > 10, 11, 12, 13], > [0xF0, 14], [0xF1, 15]], > # Single entry: > [[0xF0, 1, 2, 3]], > # empty > [], > # No values with 0x80 set > [], > # Does not start with a value that has 0x80 set > [[0xF0, 1, 2, 3]]] > > def gengroups0(seq): > group = None > for val in seq: > if val & 0x80: > if group: yield group > group = [] > try: > group.append(val) > except AttributeError: > pass > if group: yield group > > def getgroups0(seq): > groups = [] > group = None > for val in seq: > if val & 0x80: > if group: > groups.append(group) > group = [] > try: > group.append(val) > except AttributeError: > pass > if group: > groups.append(group) > return groups > > def gengroups1(seq): > idxs = [i for i,v in enumerate(seq) if v&0x80] > for i,j in zip(idxs,idxs[1:]+[None]): > yield seq[i:j] > > def getgroups1(seq): > idxs = [i for i,v in enumerate(seq) if v&0x80] > return [seq[i:j] for i,j in zip(idxs,idxs[1:]+[None])] > > # Similar to the partition method on strings > def partition(seq,f=None): > if f is None: > f = lambda x:x > for i,v in enumerate(seq): > if f(v): > return seq[:i],[seq[i]],seq[i+1:] > return seq,[],[] > > def rpartition(seq, f=None): > if f is None: > f = lambda x:x > for i,v in zip(range(len(seq)-1,-1,-1),seq[::-1]): > if f(v): > return seq[:i],[seq[i]],seq[i+1:] > return ([],[],seq) > > def gengroups2(seq): > while seq: > seq, key, val = rpartition(seq, lambda x: x&0x80) > if key and val: yield key+val > > def getgroups2(seq): > groups = [] > while seq: > seq, key, val = rpartition(seq, lambda x: x&0x80) > if key and val: > groups.append(key+val) > return groups > > def getgroups3(seq): > groups = [] > for i in seq: > if 0x80 & i: > groups.append([i]) > else: > groups[-1].append(i) > return [x for x in groups if x] > > seq = seqs[0] > if __name__ == "__main__": > from timeit import Timer > import __main__ > for i in range(4): > fname = "getgroups"+str(i) > f = getattr(__main__,fname) > print fname > for i,(s,e) in enumerate(zip(seqs,expected)): > print "test %d:"%i, > try: > if f(s) == e: > print "pass" > else: > print "fail" > except: > print "error" > > t = Timer(fname+'(seq)', > 'from __main__ import seq,'+fname) > print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/ > 100000) > print > > > Output from running the above: > getgroups0 > test 0: pass > test 1: pass > test 2: pass > test 3: pass > test 4: pass > 14.85 usec/pass > > getgroups1 > test 0: pass > test 1: pass > test 2: pass > test 3: pass > test 4: pass > 13.81 usec/pass > > getgroups2 > test 0: fail > test 1: pass > test 2: pass > test 3: pass > test 4: pass > 56.38 usec/pass > > getgroups3 > test 0: pass > test 1: pass > test 2: pass > test 3: error > test 4: error > 16.23 usec/pass > > `getgropus2' fails test 0 because it produces a reversed list. That > can easily be fixed by re-reversing the output before returning. But, > since it is by far the slowest method, I didn't bother. > > `getgroups3' is a method I got from another post in this thread, just > for comparison. > >>From my benchmarks it looks like getgroups1 is the winner. I didn't > scour the thread to test all the methods however. > From robinsiebler at gmail.com Thu Jul 5 19:19:32 2007 From: robinsiebler at gmail.com (robinsiebler at gmail.com) Date: Thu, 05 Jul 2007 16:19:32 -0700 Subject: None returned? Message-ID: <1183677572.648960.49070@m37g2000prh.googlegroups.com> I can't figure out -what- is going wrong here. When the code reaches the 'return' line, there is data to be returned, but when it exits out to the calling function, 'None' is returned! import mx.DateTime def get_weeks(weeks, year, dates, date_list={}): if dates.has_key(year): date_list[year] = dates[year].keys()[-weeks:] if len(dates[year].keys()) >= weeks: return date_list else: weeks = weeks - len(dates[year].keys()) get_weeks(weeks, str(int(year) -1), dates, date_list) def get_report_dates(weeks, dates): today = mx.DateTime.now() this_week = today.iso_week[1] rpt_dates = get_weeks(weeks, str(today.year), dates) print rpt_dates def main(): dates = {'2006': {'50': [50, 'This is the 50th week'], '51': [51, 'This is the 51st week'], '52': [52, 'This is the 52nd week']}, '2007': {'25': [1, 'This is the 1st week'], '26': [2, 'This is the 2nd week'], '27': [3, 'This is the 3rd week'], '28': [4, 'This is the 4th week'], '29': [5, 'This is the 5th week']}} get_report_dates(6, dates) From arkanes at gmail.com Mon Jul 16 15:54:56 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 16 Jul 2007 14:54:56 -0500 Subject: running a Delphi part from Python ? In-Reply-To: <525c5$469bc3be$d443bb3a$23897@news.speedlinq.nl> References: <889c1$469b275c$d443bb3a$2876@news.speedlinq.nl> <469b2b65$0$21672$426a74cc@news.free.fr> <86c61$469b30d1$d443bb3a$15805@news.speedlinq.nl> <469b3530$0$26995$426a74cc@news.free.fr> <47dce$469b3a07$d443bb3a$26795@news.speedlinq.nl> <525c5$469bc3be$d443bb3a$23897@news.speedlinq.nl> Message-ID: <4866bea60707161254l30a38fb9t87f92ceb4d372abb@mail.gmail.com> On 7/16/07, Stef Mientki wrote: > Chris Mellon wrote: > > Delphi components are tightly tied to the Delphi runtime environment > > and its' gui abstractions, so embedding it as is is will be a massive > > hack (and require extensive C code) if its even possible. > The editor I've in mind communicates only through messages, about 20 to the editor and 5 back, > so that doesn't sound too much. If it communicates entirely through messages, then it's likely not a Delphi component at all, and instead a native (to Windows) implementation and the Delphi component you've used is simply a wrapper around the messaging API. If that's the case, then you can probably use it directly in wxPython, using ctypes. Confirm this with your component vendor by finding out if it's usable from C using the Windows API. From mbitten73 at yahoo.com Thu Jul 26 18:41:48 2007 From: mbitten73 at yahoo.com (Matt Bitten) Date: Thu, 26 Jul 2007 22:41:48 -0000 Subject: Learning Jython? Message-ID: <1185489708.437968.74890@57g2000hsv.googlegroups.com> Hi, all. I'm in a situation where I need to be writing a bunch of quick-y (hopefully) self-contained programs that anyone can run from a web page. Java applets are the obvious way to do this. However, I don't know much Java, and, frankly, right now I don't feel much like learning it. I *am* pretty good at Python, however. It looks like Jython is for me. That said, I have two questions: (1) Am I thinking straight here? Or is there some other solution that a knows-Python-but-not-Java programmer might use? (2) Assuming that I'm going with Jython, it looks like I'm not going to be able to come up with any kind of GUI without learning the Java libraries. Can someone point me to a tutorial for Everything I've found are like, "You know the Java libraries forwards and backwards; now learn to call them in Python." That's not what I need. -- Matt From malaclypse2 at gmail.com Wed Jul 4 23:30:54 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 4 Jul 2007 23:30:54 -0400 Subject: using subprocess for non-terminating command In-Reply-To: <20070704192931.GB3393@gmail.com> References: <1183549118.773813.132940@r34g2000hsd.googlegroups.com> <1183550943.531211.306410@n60g2000hse.googlegroups.com> <20070704143641.GA3434@gmail.com> <16651e80707040823y7d8103bbl34da35a776b147f@mail.gmail.com> <20070704192931.GB3393@gmail.com> Message-ID: <16651e80707042030w731d064dr9b0e93fe652d219b@mail.gmail.com> On 7/4/07, O.R.Senthil Kumaran wrote: > Only when the program has executed and the output available, subprocess can > read through PIPE's stdout it seems ( not at any other time). > With killing, I loose the output. I think you have to read the data from the process's stdout before you kill it. If you want to process the output of the program before it's done, do something like this: import subprocess process = subprocess.Popen("ping 127.0.0.1", stdout=subprocess.PIPE, shell=True) for i in xrange(10): line = process.stdout.readline() print "line:", repr(line) Then you can decide to kill the subprocess when you have enough data, or whatever. Also, even though the output from ping appears to be pretty easy to read, there can be problems with buffering when you connect a pipe to the stdout of some programs. The pexpect faq talks a little bit about that - http://pexpect.sourceforge.net/#faq . If you're working under a unix system, pexpect is really useful for automating interactive programs that are otherwise difficult to work with. -- Jerry From stephane.larouche at polymtl.ca Fri Jul 6 09:45:32 2007 From: stephane.larouche at polymtl.ca (=?utf-8?b?U3TDqXBoYW5l?= Larouche) Date: Fri, 6 Jul 2007 13:45:32 +0000 (UTC) Subject: Mixing Python and C threads Message-ID: I am currently developing a software called OpenFilters (available at www.polymtl.ca/larfis). Most of the software is written in Python, but the classes that do the hard work are written in C++ modules. Since, nowadays, most new computers have multiple cores and that I want to speed up the software, I am currently trying to add some multithreading to the C++ modules using openmp. If I call the methods in the C++ modules from the Python main thread, I don't have any problem. However, they are usually called from another Python thread (using the threading module) to keep the GUI responsive and, then, Python crashes. The C++ multithreaded part does not call any Python function. It crashes whether it is surrounded by Py_BEGIN_ALLOW_THREADS/Py_END_ALLOW_THREADS or not. I am using Python 2.5 on Windows XP. The modules are compiled with gcc 4.2 (MinGW unofficial release available at http://www.esnips.com/doc/9dba8ac7-70c7-4f98-a0fa-8ea315267073/gcc-4.2.0mingw- release-patched-SSE). Has anybody had a similar problem? Do you know how to solve it? Thank you for your help, St?phane Larouche From http Sat Jul 21 14:06:12 2007 From: http (Paul Rubin) Date: 21 Jul 2007 11:06:12 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <7x8x9lwka9.fsf@ruckus.brouhaha.com> <7xbqe7ox9n.fsf@ruckus.brouhaha.com> <1185040314.501879.266230@22g2000hsm.googlegroups.com> Message-ID: <7xvecdr5rf.fsf@ruckus.brouhaha.com> Kay Schluehr writes: > When I remember correctly the FDIV bug was due to a wrongly filled > lookup table and occurred only for certain bitpattern in the divisor. > I'm not sure how a formal proof on the structure of the algorithm > could help here? Intel repaired the table i.e. the data not the > algorithm that acted upon it. I would expect the table contents to be part of the stuff being proved. I hear that they do use formal proofs for their floating point stuff now, as does AMD. AMD apparently uses ACL2 (a theorem prover written in Common Lisp, info about AMD is from the ACL2 web site) but I don't know what Intel uses. I've figured that the FDIV problem was one of the motivations for this but I'm not certain of it. From steven at REMOVE.THIS.cybersource.com.au Tue Jul 10 04:41:54 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 10 Jul 2007 08:41:54 GMT Subject: Simple operator associativity and precedence rules (was: 2**2**2**2**2 wrong? Bug?) References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> <87zm24lm3m.fsf_-_@benfinney.id.au> Message-ID: On Tue, 10 Jul 2007 18:05:49 +1000, Ben Finney wrote: > I have never gone wrong with mathematical expressions since I reduced > the set of operator associativity and precedence rules to these: > > 1. Addition and subtraction have the same precedence, and are > left-to-right associative > > 2. Multiplication and division have the same precedence, and are > left-to-right associative > > 3. Use parentheses to make explicit all other precedence and > associativity > > The specific programming language I use at any given moment might follow > more complex rules, but I ignore them in favour of the above set. I thus > spend less time uselessly thinking about tasks I should be delegating to > explicit expression syntax, and am never surprised by a misunderstood > mathematical associativity or precedence rule. However... floating point issues can still bite you. _Neither_ floating point addition nor multiplication are associative, or rather, they are not *always* associative. And it doesn't take weird examples, complicated formulae, or wildly differing numbers to find examples: >>> 0.1*(0.2*0.3) == (0.1*0.2)*0.3 False >>> 0.1+(0.2+0.3) == (0.1+0.2)+0.3 False (Depending on the version of Python, operating system, chip set, underlying C libraries and solar tides, your millage may vary.) The difference between the left and right hand sides are small, but real. Or rather, float. *wink* -- Steven. From gagsl-py2 at yahoo.com.ar Tue Jul 10 21:52:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Jul 2007 22:52:53 -0300 Subject: Parsing Help References: <26382.8357718468$1184078225@news.gmane.org> Message-ID: En Tue, 10 Jul 2007 11:32:48 -0300, Robert Rawlins - Think Blue escribi?: > I'm looking for some help building a function which can parse some XML > for > me using ElementTree. The document is of a very consistent format and > I've > copied an example of the document below. > Now, the piece of information I'm looking to retrieve is inside the > element and is, in this example value="0x05" > />, however I want the function to return the standard integer value and > not > the unit8 encoded version, so instead of my function returning '0x05' it > just needs to return '5' which is the standard integer version. Try this: def myFunction(xmlAsString): doc = ET.fromstring(xmlAsString) for att in doc.findall("attribute"): if att.get("id")=="0x0004": # obtain the second grandchildren whose tag="sequence" (begin its parent "sequence" too) seq = att.findall("sequence/sequence")[1] value = seq.find("uint8").get("value") if value[:2]=="0x": return int(value, 16) else: return int(value) Using lxml you could use XPath notation to simplify the navigation a little. -- Gabriel Genellina From news2 at mystrobl.de Sun Jul 22 10:19:26 2007 From: news2 at mystrobl.de (Wolfgang Strobl) Date: Sun, 22 Jul 2007 16:19:26 +0200 Subject: Can a low-level programmer learn OOP? References: <7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com> <7xy7hfyqcv.fsf@ruckus.brouhaha.com> Message-ID: <93p6a39vcqb11uilo129ie5lm1tflgq6e0@4ax.com> Paul Rubin : >aahz at pythoncraft.com (Aahz) writes: >> .So adding SNOBOL patterns to another library would be a wonderful >> gift to the Python community... > >Snobol patterns were invented at a time when nobody knew anything >about parsing. But Snobol patterns aren't mainly about building parsers. >They were extremely powerful (recursive with arbitrary >amounts of backtracking) but could use exponential time and maybe even >exponential space. Sure. Like any Turing complete language feature. > >These days, it makes more sense to use something like pyparsing. Probably, yes. -- Wir danken f?r die Beachtung aller Sicherheitsbestimmungen From bj_666 at gmx.net Mon Jul 30 02:17:25 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Jul 2007 06:17:25 GMT Subject: making a variable available in a function from decorator References: Message-ID: <5h5e3lF3hmufcU1@mid.uni-berlin.de> On Sun, 29 Jul 2007 15:22:47 -0700, rkmr.em at gmail.com wrote: > I create a variable in a decorator. i want to be able to access that > variable in the function to be decorated. How to do this? Pass it as argument to the function: def deco(func): eggs = 42 def decorated(*args, **kwargs): kwargs['spam'] = eggs func(*args, **kwargs) return decorated @deco def test(parrot, spam): print parrot, spam Ciao, Marc 'BlackJack' Rintsch From carsten at uniqsys.com Fri Jul 27 17:01:29 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 27 Jul 2007 17:01:29 -0400 Subject: Is access to locals() of "parent" namespace possible? In-Reply-To: <1185569180.544092.283620@57g2000hsv.googlegroups.com> References: <1185569180.544092.283620@57g2000hsv.googlegroups.com> Message-ID: <1185570089.3381.24.camel@dot.uniqsys.com> On Fri, 2007-07-27 at 20:46 +0000, Andr? wrote: > I want to give a user the possibility of "restarting" an interactive > session, by removing all the objects defined by her since the > beginning. The way I make this possible is by having a "function" > that can be called during the interactive session using locals() as an > argument, as follows: > > restart(locals()) > > It works. However, I would like to make this "friendlier", i.e. > requiring the user to simply type > > restart() > > and have the code extract out the value of locals() of the "parent" > namespace. I thought it might be possible using sys._getframe, but I > have not been able to figure out why. inspect.currentframe(1).f_locals The same caveats for locals() apply here: Modifications to this dictionary may or may not be visible to the caller. HTH, -- Carsten Haese http://informixdb.sourceforge.net From nogradi at gmail.com Sun Jul 1 04:00:38 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 1 Jul 2007 10:00:38 +0200 Subject: Memory leak in PyQt application In-Reply-To: References: Message-ID: <5f56302b0707010100x2726c6e7h9b482177e43a83ae@mail.gmail.com> > Python 2.5.1 > Boost.Python > Qt 4.2.2 > SIP 4.6 > PyQt 4.2 > WinXp > > I've a memory leak in a PyQt application and no idea how to find it. What > happens in the application ? > > From QWindow a QDialog is called on a button "pressed()" signal, that > instantiate a QThread and waits for it. If the thread has finished, the > QDialog > closes. > > I've stipped down everything that nothing more happens (to me obviously). > Boost.Python is used to wrap a C++ Lib (used in the thread). Every time > memory > usage increases for ~70 KB. > > Sometimes the application crash on closing QWindow. (QtCore.dll) > > - One thing I ask me is weather garbage collection is done in the PyQt main > loop? > > What hints do you have to find the leak? Have a look at valgrind: http://valgrind.org/ HTH, Daniel From alan.franzoni_invalid at geemail.invalid Wed Jul 4 10:58:52 2007 From: alan.franzoni_invalid at geemail.invalid (Alan Franzoni) Date: Wed, 04 Jul 2007 14:58:52 GMT Subject: Memory leak issue with complex data structure Message-ID: Hello, I've got a complex data structure (graph-like). Each of my nodes may reference zero or more other nodes, internally managed by a set() object. I have a root node which is not referenced by any other node. So, I created a "clear()" method which is called on all children (by calling their clear() method" and then clears the set with the references of the node itself. I have a serious "leak" issue; even though I clear all those sets and I delete all the references I can have to the current namespace, memory is not freed. I have tried the gc module and it couldn't help (I can't determine where the references are) and I tried using weakref.ref as well to connect object, but then I have problems (objects have no more references to them beside their parents, hence they get deleted). I understand it's impossibile to tell what's my problem without seeing the actual code (which I can't post) but I'm asking if there's any tool/debugger I could employ in order to track what's happening. Thanks! -- Alan Franzoni - Togli .xyz dalla mia email per contattarmi. Remove .xyz from my address in order to contact me. - GPG Key Fingerprint (Key ID = FE068F3E): 5C77 9DC3 BD5B 3A28 E7BC 921A 0255 42AA FE06 8F3E From no at no.no Sun Jul 22 09:44:08 2007 From: no at no.no (Daniel) Date: Sun, 22 Jul 2007 16:44:08 +0300 Subject: Sort lines in a text file References: <1185073397.821811.143260@k79g2000hse.googlegroups.com> Message-ID: On Sun, 22 Jul 2007 06:03:17 +0300, leegold wrote: > say I have a text file: > > zz3 uaa4a ss 7 uu > zz 3 zzzz66 ppazz9 > aaaaaaaaa00000zz0 > > I want to sort the text file. I want the key to be the number after > the two "zz". Or I guess a string of two zz then a number....So > that's 3, 9, 0 > > I'm trying to say that I want to sort lines in a file based on a > regular expression. How could I do that in Python? I'm limited to > Python 2.1, I can't add any 2nd party newer tools. Do your own homework. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jul 16 04:10:05 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 16 Jul 2007 10:10:05 +0200 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: <4697d9f0$0$7614$426a74cc@news.free.fr> <1184485640.495801.194200@z28g2000prd.googlegroups.com> Message-ID: <469b27dd$0$21672$426a74cc@news.free.fr> Wayne Brehaut a ?crit : (snip) > after Bruno made the > claim: "OO is about machines - at least as conceveid by Alan Key, who > invented the term and most of the concept." Please reread more carefully the above. I do give credit to Smalltalk's author for the *term* "OOP", and *most* (not *all*) of the concepts (I strongly disagree with your opinion that message-passing is not a core concept of OO). FWIW, I first mentionned Simula too (about the state-machine and simulation aspect), then sniped this mention because I thought it was getting a bit too much OT - we're not on comp.object here. From raims at dot.com Mon Jul 30 08:17:58 2007 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 30 Jul 2007 14:17:58 +0200 Subject: Detecting __future__ features References: Message-ID: <1i22ic1.mkdgv718veezaN%raims@dot.com> Steven D'Aprano wrote: > Is there any general mechanism? I'd just use the expected future feature and if the result is not what I expect (or Python raises any kind of exception, like using a keyword not present) I'd think I'm in the past :-) -- 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 orsenthil at users.sourceforge.net Wed Jul 4 15:29:31 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Thu, 5 Jul 2007 00:59:31 +0530 Subject: using subprocess for non-terminating command In-Reply-To: <16651e80707040823y7d8103bbl34da35a776b147f@mail.gmail.com> References: <1183549118.773813.132940@r34g2000hsd.googlegroups.com> <1183550943.531211.306410@n60g2000hse.googlegroups.com> <20070704143641.GA3434@gmail.com> <16651e80707040823y7d8103bbl34da35a776b147f@mail.gmail.com> Message-ID: <20070704192931.GB3393@gmail.com> * Jerry Hill [2007-07-04 11:23:33]: > > That's because you tied stdin to a pipe in your Popen call, but then > tried to read from stdout. Try this instead: My mistake. I had just 'typed' the command in the mail itself and forgot to include the stdin, stdout, and stderr and mentioned it as hung based on some recollection. > > >>> process = subprocess.Popen("ping -c 10 127.0.0.1", > stdout=subprocess.PIPE, shell=True) > >>> process.stdout.readlines() I tried it again and found that giving the -c 10 returns a well defined output. Only when the program has executed and the output available, subprocess can read through PIPE's stdout it seems ( not at any other time). With killing, I loose the output. >>> process = subprocess.Popen('ping 10 127.0.0.1', stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True) >>> process.pid 3475 >>> import os >>> import signal >>> os.kill(process.pid,signal.SIGINT) >>> process.stdout.read() '' >>> # required output is lost! -- O.R.Senthil Kumaran http://uthcode.sarovar.org From carsten at uniqsys.com Wed Jul 25 14:11:19 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 25 Jul 2007 14:11:19 -0400 Subject: How do I 'stat' online files? In-Reply-To: References: <1185284836.3370.11.camel@dot.uniqsys.com> Message-ID: <1185387079.4432.9.camel@dot.uniqsys.com> On Tue, 2007-07-24 at 22:23 -0300, Gabriel Genellina wrote: > En Tue, 24 Jul 2007 10:47:16 -0300, Carsten Haese > escribi?: > > > On Tue, 2007-07-24 at 09:07 -0400, DB Daniel Brown wrote: > >> I am working on a program that needs to stat files (gif, swf, xml, > >> dirs, etc) from the web. I know how to stat a local file? > >> but I can?t figure out how to stat a file that resides on a web > >> server. > > > > That's because urlopen returns a file-like object, not a file. The best > > you can hope for is to inspect the headers that the web server returns: > > > >>>> import urllib > >>>> f = urllib.urlopen("http://www.python.org") > >>>> f.headers['last-modified'] > > 'Mon, 23 Jul 2007 20:35:52 GMT' > >>>> f.headers.items() > > [('content-length', '14053'), ('accept-ranges', 'bytes'), ('server', > > 'Apache/2.2.3 (Debian) DAV/2 SVN/1.4.2 mod_ssl/2.2.3 OpenSSL/0.9.8c'), > > ('last-modified', 'Mon, 23 Jul 2007 20:35:52 GMT'), ('connection', > > 'close'), ('etag', '"60193-36e5-39089a00"'), ('date', 'Tue, 24 Jul 2007 > > 13:42:57 GMT'), ('content-type', 'text/html')] > > > > Maybe that's good enough for your needs. > > This generates an HTTP GET request - transfering the contents too, > innecesarily. Yes, but how much of that content will actually be transferred if I don't call f.read? Consider this little test: # urltest.py import time, urllib t1 = time.time() f = urllib.urlopen("http://data.phishtank.com/data/online-valid/") print f.headers.items() t2 = time.time() f.close() print t2-t1 # eof $ python urltest.py [('content-length', '4390510'), ('accept-ranges', 'bytes'), ('server', 'Apache/2.2.4 (FreeBSD) mod_ssl/2.2.4 OpenSSL/0.9.7e-p1 DAV/2 PHP/5.2.0 with Suhosin-Patch'), ('last-modified', 'Wed, 25 Jul 2007 17:58:04 GMT'), ('connection', 'close'), ('etag', '"5705e1-42fe6e-40612300"'), ('date', 'Wed, 25 Jul 2007 18:07:46 GMT'), ('content-type', 'application/xml')] 0.303626060486 I doubt that my computer just downloaded 4 MB of stuff in 0.3 seconds. -- Carsten Haese http://informixdb.sourceforge.net From graemeglass at gmail.com Wed Jul 25 06:19:55 2007 From: graemeglass at gmail.com (Graeme Glass) Date: Wed, 25 Jul 2007 10:19:55 -0000 Subject: How to create a single executable of a Python program In-Reply-To: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> References: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> Message-ID: <1185358795.401588.61580@b79g2000hse.googlegroups.com> On Jul 25, 8:34 am, NicolasG wrote: > Dear fellows, > > I'm trying to create a executable file using py2exe . Unfortunately > along with the python executable file it also creates some other files > that are needed in order to the executable be able to run in a system > that doesn't have Python installed. Can some one guide me on how can I > merge all this files created by py2exe in a single exe file ? If I > have a python program that uses an image file I don't want this image > file to be exposed in the folder but only to be accessible through the > program flow.. > > Regards, > Nicolas. Have you taken a look at cx_Freeze? (http://python.net/crew/atuining/ cx_Freeze/) http://www.velocityreviews.com/forums/t354325-singlefile-executables.html From aisaac at american.edu Wed Jul 11 02:50:56 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 11 Jul 2007 06:50:56 GMT Subject: bool behavior in Python 3000? In-Reply-To: <469472f4$0$1293$9b622d9e@news.freenet.de> References: <5ficp9F3cram2U2@mid.individual.net> <469472f4$0$1293$9b622d9e@news.freenet.de> Message-ID: Stargaming wrote: > I think Bjoern just wanted to point out that all those binary > boolean operators already work *perfectly*. >>> bool(False-True) True But reread Steven. Cheers, Alan Isaac From bignose+hates-spam at benfinney.id.au Thu Jul 26 20:05:26 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 27 Jul 2007 10:05:26 +1000 Subject: removing items from a dictionary ? References: Message-ID: <87ir86hfsp.fsf@benfinney.id.au> Stef Mientki writes: > I want to remove some items from a dictionary, > so I would expect this should work: > > Nets = {} > ... fill the dictionary Nets > > for net in Nets: > if net.upper() in Eagle_Power_Nets : > del Nets [ net ] Don't change the thing you're currently iterating over. Instead, iterate over a copy: >>> eagle_power_nets = ['eggs', 'beans'] >>> nets = {'spam': 10, 'eggs': 20, 'ham': 30} >>> for name in list(nets.keys()): ... if name in eagle_power_nets: ... del nets[name] ... >>> nets {'ham': 30, 'spam': 10} Style hints (from ): * Don't name an instance with Upper_Case; the convention is for instances to be named as lower_case_with_underscores, and classes to be named in TitleCase. * Don't put spaces inside the bracketing characters '[]', '{}', '()'. * Don't separate the item specifier '[foo]' or the function parameters '(bar)' from the identifier; instead follow it immediately, 'foo_list[foo]', 'bar_func(bar)'. None of these are mandatory, but they'll make your code comply with what Python programmers expect and thus be more easily maintained. -- \ "Are you pondering what I'm pondering?" "Umm, I think so, | `\ Brain, but what if the chicken won't wear the nylons?" -- | _o__) _Pinky and The Brain_ | Ben Finney From mail at microcorp.co.za Tue Jul 17 01:46:30 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 17 Jul 2007 07:46:30 +0200 Subject: Access Object From 2 Applications or Fix Scheduler References: <015201c7c71a$2be05df0$83a119d0$@rawlins@thinkbluemedia.co.uk><00a501c7c776$900ba8a0$03000080@hendrik> <018b01c7c788$47ea3700$d7bea500$@rawlins@thinkbluemedia.co.uk> Message-ID: <019901c7c83d$1d9df580$03000080@hendrik> "Robert Rawlins - Think Blue" top posted: >Also Hendrik, > >I should probably mention that the second application is a constant running >application, it's nothing something that can just be 'started' by the first >one, its running non-stop and just needs data passed into it regularly when >the first application finds it. > >Application 1 Application 2 >Work with dict >Work with dict >Work with dict >Work with dict >New XML Found, Parse Into Dict --------------> Work with new dict >Work with new dict >Work with new dict >Work with new dict > >You see how that works? Application 1 has a function that runs every minute >and _may_ find a new xml file, if it does then I need it to parse that file >into a list of dictionary and then pass that into application 2, which then >starts using it :-) ok - I see the difference - when you said schedule, I was thinking something like a cron job.. > >Now we may be able to avoid this if there is some type of file watcher >function available in python, my second application could then just watch >the XML file and as soon as a new one is available parse it itself. Is that >something you've heard of? no to the tail like functionality - but then I am not an expert on what is available Now being a thread fanatic, I would do this sort of thing with a thread for scanning the world for the new XML, and if it finds a new thing, have it create the new dict. (While it is doing this, the main thread is still using the old one). Then, when the new dict is ready, I would put it on a Queue, which the main thread checks every time before it accesses the working dict, and then if there is a new one, "overwrites" the old working one with the new one by assigning the working dict name to the one from the queue: try: workdict = dict_q.get() except Queue.Empty: pass where dict_q is the instance of Queue.Queue() that is used to link the two threads - create it in __main__ before starting the seeker thread so that it is visible to both the seeker and worker that __main__ calls. " dict_q = Queue.Queue() " After making the new dict, the seeker simply puts it on the queue like this: dict_q.put(new_dict) Can't be simpler. This has the advantage that the swap is made at a sensible point in the worker thread, and the scheduling can be done in the seeker thread simply by calling time.sleep(60.0) at the start of a while True loop. - it won't give you exactly sixty seconds to the millisecond, but this probably does not matter for something like this. - as long as you start using the new data "soon" its probably all right. For starting a thread, look at thread for basics and threading for fancy, if you don't know already. I use thread because I am simple minded. - Hendrik From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jul 16 04:26:44 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 16 Jul 2007 10:26:44 +0200 Subject: Trying to choose between python and java In-Reply-To: References: Message-ID: <469b2bc4$0$21672$426a74cc@news.free.fr> Anthony Irwin a ?crit : > Hi All, > (snip) > Also does anyone else have any useful comments about python vs java > without starting a flame war. I guess I'd better not answer, then !-) From Brad.Johnson at ballardtech.com Fri Jul 27 17:56:47 2007 From: Brad.Johnson at ballardtech.com (Brad Johnson) Date: Fri, 27 Jul 2007 21:56:47 +0000 (UTC) Subject: Problem embedding in small Win32 App References: Message-ID: Gabriel Genellina yahoo.com.ar> writes: > > By far, the most common problem extending/embedding Python is to do wrong > reference counts. > Read http://docs.python.org/ext/refcounts.html again (I hope you already > did!) and make sure you don't hold a pointer to an object without > incrementing its reference count, by example. > If you can shrink your application to the minimum code that shows the > problem, try posting it here. > Thanks for the advice! Adding the requisite Py_INCREFs has fixed my problem. Please forgive my ignorance in forgetting this basic piece of information. I did read the section you provided, and rereading it reminded me that I was only doing one half of the equation with Py_DECREF. From http Tue Jul 3 04:10:03 2007 From: http (Paul Rubin) Date: 03 Jul 2007 01:10:03 -0700 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> <7x645al8kc.fsf@ruckus.brouhaha.com> <1182894003.920335.317620@a26g2000pre.googlegroups.com> <7x7ipoy6cf.fsf@ruckus.brouhaha.com> <1183041149.275562.114490@o11g2000prd.googlegroups.com> Message-ID: <7xbqethpr8.fsf@ruckus.brouhaha.com> sla29970 at gmail.com writes: > As for the primacy of UTC vs. TAI, this is the classical chicken and > egg problem. The bureaucratic reality is opposed to the physical > reality. Well, if you're trying to pick just one timestamp standard, I'd say you're better off using a worldwide one rather than a national one, no matter how the bureaucracies work. TAI is derived from atomic clocks all over the world, while the national metrology labs are more subject to error and desynchronization, and whatever legal primacy they have is good in only one country. From max at alcyone.com Wed Jul 4 20:32:54 2007 From: max at alcyone.com (Erik Max Francis) Date: Wed, 04 Jul 2007 17:32:54 -0700 Subject: Proposal: s1.intersects(s2) In-Reply-To: References: <5f1pldF3a62csU5@mid.uni-berlin.de> Message-ID: Steven D'Aprano wrote: > The problem comes if we (perhaps naively) try to say that if a set A is a > subset of set B, set A must intersect with B. (Not all intersecting sets > are subsets, but all subsets are intersecting sets.) Unfortunately that is > not the same as asking if the intersection between two sets is not empty: Well, sure. If you're dealing with empty sets, then you should know what you're getting yourself into if you're asking about set intersections. If you don't, then an .intersects method isn't going to help you out of your conundrum of not understanding how the null set relates to intersections. -- 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 Perfect girl / She was never me -- Lamya From robert.dodier at gmail.com Tue Jul 3 23:41:20 2007 From: robert.dodier at gmail.com (Robert Dodier) Date: Wed, 04 Jul 2007 03:41:20 -0000 Subject: Questions about input lines (maximum length and continuation) Message-ID: <1183520480.036284.254770@n60g2000hse.googlegroups.com> Hello, I'm planning to write a program which automatically generates Python code. (1) Is there a limit on the length of a line in a Python program? (2) From what I understand, symbols, operators, and numbers cannot be broken across lines continued with the backslash character. Is there any way to allow symbols, operators, and numbers to be broken across lines? Thanks a lot for any information. I appreciate your help. Robert Dodier From kimiraikkonen85 at gmail.com Sun Jul 1 15:34:27 2007 From: kimiraikkonen85 at gmail.com (kimiraikkonen) Date: Sun, 01 Jul 2007 12:34:27 -0700 Subject: The best platform and editor for Python In-Reply-To: References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> Message-ID: <1183318467.806694.47300@57g2000hsv.googlegroups.com> On Jul 1, 10:30 pm, "S?nmez Kartal" wrote: > Hello, > > Emacs is the best for anything for me. Some people prefers Eclipse > with PyDev extension. > > Build some real world applications with Python. Pick what do you need > from SourceForge or similar one then write it. If it is something you > need then you probably will make it more special then you found and > this will take you to the more coding and more... > > By the way, thanks for winning Magny Cours grand prix Kimi... :-P > > On 7/1/07, kimiraikkonen wrote: > > > > > Hi, > > For experienced with Pyhton users, which developing software and > > enviroment would you suggest for Pyhton programming? Compiler+Editor > > +Debugger. > > > Also what are your suggestions for beginners of Pyhton programming? > > > Thank you. > > > -- > >http://mail.python.org/mailman/listinfo/python-list- Hide quoted text - > > - Show quoted text - Sa ol say n Kartal :-) From carsten at uniqsys.com Fri Jul 13 01:41:02 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 13 Jul 2007 01:41:02 -0400 Subject: Fast powerset function In-Reply-To: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> References: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> Message-ID: <20070713053718.M56281@uniqsys.com> On Thu, 12 Jul 2007 21:33:11 -0700, Arash Arfaee wrote > I need a powerset generator function. It's really slow with recursion. Does anybody have any idea or code(!!) to do it in an acceptable time? 1) Don't use recursion. 2) Google is your friend. -Carsten From dr.death.tm at gmail.com Wed Jul 11 06:51:27 2007 From: dr.death.tm at gmail.com (ddtm) Date: Wed, 11 Jul 2007 03:51:27 -0700 Subject: Python IRC bot using Twisted In-Reply-To: <1183538567.128025.224430@q75g2000hsh.googlegroups.com> References: <1183477890.690319.182400@m36g2000hse.googlegroups.com> <1183538567.128025.224430@q75g2000hsh.googlegroups.com> Message-ID: <1184151087.537830.40790@n60g2000hse.googlegroups.com> I have another problem with my IRC bot. There is privmsg(self, user, channel, msg) function (this function handles the incoming IRC data) in the code that was mentioned above. I have a special condition in this function that if a user sends to bot a private message (in other words: if channel == self.nickname) bot sends it to the main channel. Everything works fine except sending message to the main channel (for example #www). I write something like this: if channel == self.nickname: self.msg('www', msg) This code doesn't work. But if try to send private message back to user: if channel == self.nickname: self.msg(user, msg) everything works fine. I really don't know what to do. From aleax at mac.com Thu Jul 19 10:46:45 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 19 Jul 2007 07:46:45 -0700 Subject: Real-time Update References: <1184747090.102324.265230@i13g2000prf.googlegroups.com> Message-ID: <1i1hmwc.8aomfq13e95mpN%aleax@mac.com> Hendrik van Rooyen wrote: > "ReTrY" wrote: > > > I'm writing a program with Tkinter GUI, When the program is running it > > need to be updated every five seconds (data comes from internet). How > > should I do that ? How to make a function in main loop ? > > Short answer: > > use the after method to set up a periodic scan of a queue. > > In another thread, look for the new stuff, and put it on the queue when found. > > there is a recipe for this sort of thing, but I keep losing links. . Alex From marduk at nbk.hopto.org Mon Jul 16 17:56:06 2007 From: marduk at nbk.hopto.org (marduk) Date: Mon, 16 Jul 2007 16:56:06 -0500 Subject: Break up list into groups In-Reply-To: <1184621479.15828.23.camel@blackwidow.nbk> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> <1184621479.15828.23.camel@blackwidow.nbk> Message-ID: <1184622966.15828.27.camel@blackwidow.nbk> On Mon, 2007-07-16 at 16:31 -0500, marduk wrote: > Assuming you meant '0xF0' instead of '0x80'.... do you mean any value > >=240 starts a new group? If so: > > groups = [] > current = [] # probably not necessary, but as a safety > for i in l: > if i >= 240: > current = [] > groups.append(current) > current.append(i) > > Misunderstood... actually that should have read groups = [] current = [] # probably not necessary, but as a safety for i in l: if 240 & i: current = [] groups.append(current) current.append(i) From stargaming at gmail.com Wed Jul 25 13:08:49 2007 From: stargaming at gmail.com (Stargaming) Date: 25 Jul 2007 17:08:49 GMT Subject: Reading files, splitting on a delimiter and newlines. References: <1185378363.166434.172190@r34g2000hsd.googlegroups.com> <1185380186.215288.83990@b79g2000hse.googlegroups.com> Message-ID: <46a783a1$0$25842$9b622d9e@news.freenet.de> On Wed, 25 Jul 2007 09:16:26 -0700, kyosohma wrote: > On Jul 25, 10:46 am, chris... at gmail.com wrote: >> Hello, >> >> I have a situation where I have a file that contains text similar to: >> >> myValue1 = contents of value1 >> myValue2 = contents of value2 but >> with a new line here >> myValue3 = contents of value3 >> >> My first approach was to open the file, use readlines to split the >> lines on the "=" delimiter into a key/value pair (to be stored in a >> dict). >> >> After processing a couple files I noticed its possible that a newline >> can be present in the value as shown in myValue2. >> >> In this case its not an option to say remove the newlines if its a >> "multi line" value as the value data needs to stay intact. >> >> I'm a bit confused as how to go about getting this to work. >> >> Any suggestions on an approach would be greatly appreciated! > > I'm confused. You don't want the newline to be present, but you can't > remove it because the data has to stay intact? If you don't want to > change it, then what's the problem? > > Mike It's obviously that simple line-by-line filtering won't handle multi-line statements. You could solve that by saving the last item you added something to and, if the line currently handles doesn't look like an assignment, append it to this item. You might run into problems with such data: foo = modern maths proved that 1 = 1 bar = single If your dataset always has indendation on subsequent lines, you might use this. Or if the key's name is always just one word. HTH, Stargaming From gherron at islandtraining.com Mon Jul 2 01:01:46 2007 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 01 Jul 2007 22:01:46 -0700 Subject: Probably simple syntax error In-Reply-To: <1183351228.878746.233430@o61g2000hsh.googlegroups.com> References: <1183351228.878746.233430@o61g2000hsh.googlegroups.com> Message-ID: <468886BA.4070704@islandtraining.com> Dustin MacDonald wrote: > Hi everyone. > > This is my first time posting to this newsgroup, and although I > maintain my netiquette I might've missed something specific to the > newsgroup, so hopefully you can avoid flaming me if I have :) I > apologize for the length of this post but I figure the more > information the better. > > My problem is that I'm getting a syntax error in some Python code that > looks quite simple. The original code was in Object Pascal as I'm a > recent Delphi-turned-Python programmer. > > I took the code (which is only about 130 lines in OP) and 'translated' > it the best I could into Python (ended up being one line shy of 80 > when I was done). I can't see any problems with the code but it's > coming up with a bunch of errors, which I'm guessing are probably my > assuming something is the same in Python as it is in Pascal, and being > wrong. > > Anyway, here's the code I'm having trouble with (the same error comes > up several times but this is the first part of the code it shows up > in): > > [code] > randomizing_counter = 0 > # Put the loop counter for the randomizing to zero. > until_val = 36 > # Set the "until val" to 36. We'll compare them to make sure we're not > at the end of our wordlist_both. > > while randomizing_counter < until_val: > big_randomized_int = RandRange(0,100) > # Make a random value and store it. > small_randomized_int = big_randomized_int / 100 > # Divide that random value and store it in a different variable. > small_randomized_int = Round(small_randomized_int, 2) > # Round that value to 2 decimal places > **weights_array(randomizing_counter) = small_randomized_int > If weights_array is a list or dictionary then use weights_array[randomizing_counter] = ... to choose which element of the list gets the assignment. If weights_array is a function, then weights_array(randomizing_counter) is the proper way to call the function, but the value returned cannot be the object of an assignment. Gary Herron > # Assign the first randomized value to our first word to be weighted. > randomizing_counter = randomizing_counter + 1 > # Up the counter and repeat. > [/code] > > The starred line is the one getting the error message: "SyntaxError: > can't assign to function call" > > Now, I do understand what this means. I'm trying to assign to a > function instead of the value that the function should create. But > since when is weights_array or small_randomizing_int a function? Both > are being declared in the code on their first usage. This one has got > me stumped, maybe you guys can help me out with it? > > Thanks, > ~Dustin > > From deets at nospam.web.de Mon Jul 9 06:53:43 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jul 2007 12:53:43 +0200 Subject: A clean way to program an interface References: <1183957402.819499.227350@o11g2000prd.googlegroups.com> Message-ID: <5feidnF3au460U1@mid.uni-berlin.de> rh0dium wrote: > Hi all, > > I got this new radio scanner (toy!!) this weekend and I can access it > via a serial cable. I want to write a interface around it but I am > looking for some suggestions. I thought at first I would simply class > the Scanner and write the various methods as attibutes similar to > below.. But then I thought about it and I don't like it for a couple > of obvious reasons - there isn't any data checking, and it's terribly > repetitive. > > So I started searching on google - and I think it might be better to > use a (sub)class for each function ( class STS, PRG, etc.). where the > attributes are accessible as both dict items and lists - which > ultimately go and "set" the scanner. > > I guess my question is this. > > I have a function SIN which when one argument is given does an > effective "get" from the scanner - this returns some 10+ values. When > some 10+ parameters are given it does an effective "set" to the > scanner. Given that I can't remember all 10+ parameters I attempted > below to represent them as a dict where the key tells me what the heck > the parameter is supposed to represent. So a simple translation > occurs on both the set and get which splits the list into a named dict > and vice versa. Question 1 - I think I should be checking the data > before a set - is this a smart thing or should I just do a try/ > except? Question 2 - Since I only want to do this once (ok twice) > should I represent each function as a class or should I keep the code > I have below? THROW IT AWAY!!!! Seriously. That's one of the most convoluted, incomprehensible pieces of python I've seen. Ever. All the sys._getframe()-stuff has to go. Really. There are about a dozen pieces of code worldwide that are allowed to have that in them. Maybe two dozen. And while I'm having difficulties grasping what you actually mean by " I represent each function as a class or should I keep the code I have below?", I've done my fair share of serial programming. And I would say that having one class that exposes different methods for commands is the way to go. But first - throw that code away. Fast. Faster. Diez From gagsl-py2 at yahoo.com.ar Tue Jul 24 21:23:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Jul 2007 22:23:49 -0300 Subject: How do I 'stat' online files? References: <1185284836.3370.11.camel@dot.uniqsys.com> Message-ID: En Tue, 24 Jul 2007 10:47:16 -0300, Carsten Haese escribi?: > On Tue, 2007-07-24 at 09:07 -0400, DB Daniel Brown wrote: >> I am working on a program that needs to stat files (gif, swf, xml, >> dirs, etc) from the web. I know how to stat a local file? >> but I can?t figure out how to stat a file that resides on a web >> server. > > That's because urlopen returns a file-like object, not a file. The best > you can hope for is to inspect the headers that the web server returns: > >>>> import urllib >>>> f = urllib.urlopen("http://www.python.org") >>>> f.headers['last-modified'] > 'Mon, 23 Jul 2007 20:35:52 GMT' >>>> f.headers.items() > [('content-length', '14053'), ('accept-ranges', 'bytes'), ('server', > 'Apache/2.2.3 (Debian) DAV/2 SVN/1.4.2 mod_ssl/2.2.3 OpenSSL/0.9.8c'), > ('last-modified', 'Mon, 23 Jul 2007 20:35:52 GMT'), ('connection', > 'close'), ('etag', '"60193-36e5-39089a00"'), ('date', 'Tue, 24 Jul 2007 > 13:42:57 GMT'), ('content-type', 'text/html')] > > Maybe that's good enough for your needs. This generates an HTTP GET request - transfering the contents too, innecesarily. Using an HTTP HEAD request would be better, as only the headers are transfered. Since urllib can't generate a HEAD request, one has to use httplib instead (it's just a bit more "low level"): py> import httplib py> conn = httplib.HTTPConnection("www.python.org") py> conn.request("HEAD", "/images/python-logo.gif") py> resp = conn.getresponse() py> resp.getheaders() [('content-length', '2549'), ('accept-ranges', 'bytes'), ('server', 'Apache/2.2. 3 (Debian) DAV/2 SVN/1.4.2 mod_ssl/2.2.3 OpenSSL/0.9.8c'), ('last-modified', 'Tu e, 24 Jul 2007 23:41:20 GMT'), ('etag', '"6015b-9f5-ee27c800"'), ('date', 'Wed, 25 Jul 2007 01:12:43 GMT'), ('content-type', 'image/gif')] py> conn.close() -- Gabriel Genellina From kusarpi at gmail.com Sat Jul 21 18:03:42 2007 From: kusarpi at gmail.com (KU) Date: Sat, 21 Jul 2007 22:03:42 -0000 Subject: The Convenience of Online Learning. The Benefits of a Respected Degree.Try Ellis College for Free. Message-ID: <1185055422.764735.15870@x35g2000prf.googlegroups.com> A fully accredited extension of The New York Institute of Technology (NYIT), Ellis College gives you the prestige of earning your Bachelor's Degree from a respected university with the convenience of learning online on your own schedule. Whether you're looking to begin a new career or advance an existing one, Ellis offers an array of flexible online Undergraduate Degree programs to help you achieve your goal. Fully Accredited. Esteemed Faculty. An academic division of the New York Institute of Technology, Ellis College is accredited by the Middle States Commission on Higher Education, one of six regional accrediting bodies for higher education recognized by the U.S. Secretary of Education. Every Ellis instructor holds a Ph.D. or Masters Degree in their subject matter, with nearly half of all teaching faculty holding a Doctorate or other terminal degree. Get a free guest pass to Ellis College and experience a fully- accredited online college like no other. You'll have access to Ellis CourseBites? mini-courses, educational Webcasts, and our interactive course demonstrations. Getting started is easy! Just fill out the form to get your free pass. Click Here:http://www.anrdoezrs.net/ot114fv2rz1GJKJOOOIGIHLOJLKI From mail at microcorp.co.za Thu Jul 26 02:45:55 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 26 Jul 2007 08:45:55 +0200 Subject: Reading files, splitting on a delimiter and newlines. References: <1185378363.166434.172190@r34g2000hsd.googlegroups.com> <1185380186.215288.83990@b79g2000hse.googlegroups.com> Message-ID: <009701c7cf50$ac347200$03000080@hendrik> : Wrote: > On Jul 25, 10:46 am, chris... at gmail.com wrote: > > Hello, > > > > I have a situation where I have a file that contains text similar to: > > > > myValue1 = contents of value1 > > myValue2 = contents of value2 but > > with a new line here > > myValue3 = contents of value3 > > > > My first approach was to open the file, use readlines to split the > > lines on the "=" delimiter into a key/value pair (to be stored in a > > dict). > > > > After processing a couple files I noticed its possible that a newline > > can be present in the value as shown in myValue2. > > > > In this case its not an option to say remove the newlines if its a > > "multi line" value as the value data needs to stay intact. > > > > I'm a bit confused as how to go about getting this to work. > > > > Any suggestions on an approach would be greatly appreciated! > > I'm confused. You don't want the newline to be present, but you can't > remove it because the data has to stay intact? If you don't want to > change it, then what's the problem? I think the OP's trouble is that the value he wants gets split up by the newline at the end of the line when he uses readline(). One can try adding the single value to the previous value in the previous key/value pair when the split does not yield two values - a bit hackish, but given structured input data it might work. - Hendrik From alanwilter at gmail.com Thu Jul 26 06:59:01 2007 From: alanwilter at gmail.com (Alan) Date: Thu, 26 Jul 2007 11:59:01 +0100 Subject: Tix.Tk() on Mac Intel Message-ID: Hi List! I have I Macbook Pro Intel running OSX 10.4.10. I downloaded Python 2.5 and tried TclTkAquaBI-8.4.10.0.dmg, but I got: Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py", line 210, in __init__ self.tk.eval('package require Tix') _tkinter.TclError: no suitable image found. Did find: /Library/Tcl/Tix8.4/libTix8.4.dylib: mach-o, but wrong architecture Which make sense since tcltkaqua is released only for PPC. Googling a bit, since tcltkaqua stopped development, I found they recommended ActiveTcl, but Tix is not included in the package. So removing tcltkaqua and ActiveTcl, when trying Tix.Tk() I got: >>> Tix.Tk() Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py", line 210, in __init__ self.tk.eval('package require Tix') _tkinter.TclError: can't find package Tix The only way I got Tix.Tk() working so far was using Fink but I want the nice aqua visual for python. Is there any way of getting it working? I would appreciate any help here. Many thanks in advance. Cheers, Alan From restycena at gmail.com Thu Jul 12 12:09:43 2007 From: restycena at gmail.com (kublai) Date: Thu, 12 Jul 2007 16:09:43 -0000 Subject: web page text extractor In-Reply-To: <2007071209225175249-jon@turnthepageorg> References: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> <2007071209225175249-jon@turnthepageorg> Message-ID: <1184256583.060492.196610@m3g2000hsh.googlegroups.com> On Jul 12, 10:22 pm, Jon Rosebaugh wrote: > On 2007-07-12 04:42:25 -0500, kublai said: > > > For a project, I need to develop a corpus of online news stories. I'm > > looking for an application that, given the url of a web page, "copies" > > the rendered text of the web page (not the source HTNL text), opens a > > text editor (Notepad), and displays the copied text for the user to > > examine and save into a text file. Graphics and sidebars to be > > ignored. The examples I have come across are much too complex for me > > to customize for this simple job. Can anyone lead me to the right > > direction? > > You may find BeautifulSoup or templatemaker to be of assistance: > > http://www.crummy.com/software/BeautifulSoup/http://www.holovaty.com/blog/archive/2007/07/06/0128 Thanks all for your suggestions. I will try first the Lynx solution. Cheers, gk From adayattheoffice at gmail.com Sun Jul 29 10:52:11 2007 From: adayattheoffice at gmail.com (adayattheoffice at gmail.com) Date: Sun, 29 Jul 2007 07:52:11 -0700 Subject: Why Is This The Best Program Online ? Message-ID: <1185720731.155067.96830@d30g2000prg.googlegroups.com> If You Want To Make Money ..This Is What You Do. I Spent 2 Years Trying To Make Money And Thankfully Now I Am No Longer Trying ,I Am Actively Doing So. This Is What It Takes.. http://trakclix.com/ct/t.php?l=353 From the.mindstorm.mailinglist at gmail.com Tue Jul 10 10:23:32 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Tue, 10 Jul 2007 07:23:32 -0700 Subject: Dynamic method In-Reply-To: References: Message-ID: <1184077412.119564.74960@g4g2000hsf.googlegroups.com> On Jul 10, 5:07 pm, "Daniel Nogradi" wrote: > > I have an issue I think Python could handle. But I do not have the knowledge > > to do it. > > > Suppose I have a class 'myClass' and instance 'var'. There is function > > 'myFunc(..)'. I have to add (or bind) somehow the function to the class, or > > the instance. Any help, info or point of reference is wellcome.... > > How about this (note the first argument 'self' which is the instance > itself in the second case): > > def method_for_instance( message ): > print message > > def method_for_class( self, message ): > print message > > class myClass( object ): > pass > > inst = myClass( ) > inst.method = method_for_instance > > inst.method( 'hello' ) > > myClass.method = method_for_class > > inst = myClass( ) > inst.method( 'hello' ) I think a solution may be using the new module and the function instancemethod: instancemethod(function, instance, class) This function will return a method object, bound to instance, or unbound if instance is None. function must be callable. ./alex -- .w( the_mindstorm )p. From mail at microcorp.co.za Sat Jul 28 04:40:06 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 28 Jul 2007 10:40:06 +0200 Subject: Process Control Help References: <1185570527.665048.48780@e9g2000prf.googlegroups.com> Message-ID: <001301c7d0f2$fde42980$03000080@hendrik> wrote: > > > I'm attempting to start some process control using Python. I've have > quite a bit of literature on networking, and have made some tinkering > servers and clients for different protocols HTTP, FTP, etc... But now > it's time for the murky web of industrial protocol. I'm looking to > start with IO and servo controls via Ethernet. > > Questions: > > Is there an existing forum on this already? > What protocols are the most python friendly? i.e. are transparent > enough that i can create my own python driver. (or do these drivers > exist?) > What ethernet accesible servo and IO industrial devices have people > had success with? What is it that you are trying to do? Some of the commercial devices come with their own software, and you may not need python or anything else. A lot of the industrial connectivity is still RS-485 or RS-422 and not Ethernet based - although some of the protocols, have, I think, been ported. If you say more, then someone can maybe help you, as there are quite a few people on this group who seem to dabble in process control. - Hendrik From damienlmoore at gmail.com Mon Jul 16 09:45:33 2007 From: damienlmoore at gmail.com (dmoore) Date: Mon, 16 Jul 2007 13:45:33 -0000 Subject: Embedding/Extending Python in/with C++: non-static members? Message-ID: <1184593533.995878.123010@k79g2000hse.googlegroups.com> Hi Folks: I have a question about the use of static members in Python/C extensions. Take the simple example from the "Extending and Embedding the Python Interpreter" docs: A simple module method: static PyObject * spam_system(PyObject *self, PyObject *args) { ... } listed in a method table: static PyMethodDef SpamMethods[] = { ... {"system", spam_system, METH_VARARGS, "Execute a shell command."}, ... {NULL, NULL, 0, NULL} /* Sentinel */ }; that is registered with: PyMODINIT_FUNC initspam(void) { (void) Py_InitModule("spam", SpamMethods); } I have an application that embed multiple interpreters. I want to be able to register methods for each interpreter that access C++ state data relevant to that particular interpreter. In other words I want to be able to register non-static class members in a class like the following: class PythonSpamModuleInstance { PythonSpamModuleInstance() { SpamMethods[0]={"system", spam_system, METH_VARARGS,"Execute a shell command."}; SpamMethods[1]={NULL, NULL, 0, NULL}; PyObject *spammodule=Py_InitModule("spam", SpamMethods); // Needs an INCREF call? } ~PythonSpamModuleInstance() { PyObject_Del("spam", SpamMethods); } PyObject *spam_system(PyObject *self, PyObject *args) { // accesses non-static data in this class } PyMethodDef SpamMethods[2]; PyObject *spammodule; // Other data specific to this instance of the module }; The idea is that each time my app launches an embedded Interpreter it will create an accompanying instance of PythonSpamModuleInstance that allows the Interpreter to call the registered non-static C++ member function spam_system. Calls to that member function will also affect state information. So the questions: will this work? In particular, will the use of non- static member functions cause problems? Is there a better way of creating extension modules for multiple embedded interpreters? If I am forced to use static methods, how do i figure out which interpreter is calling them? From maxkhesin at gmail.com Sun Jul 15 14:59:30 2007 From: maxkhesin at gmail.com (xamdam) Date: Sun, 15 Jul 2007 18:59:30 -0000 Subject: zipfile 2GB problems? In-Reply-To: <1184474112.081258.111490@n60g2000hse.googlegroups.com> References: <1184474112.081258.111490@n60g2000hse.googlegroups.com> Message-ID: <1184525970.082235.238200@q75g2000hsh.googlegroups.com> On Jul 15, 12:35 am, xamdam wrote: > Hi fellas, > I am experiencing problems reading a 2GB zipfile consisting of > multiple zipped files. I found a thread http://mail.python.org/pipermail/python-dev/2005-April/053027.html > that mentions a problem on the writing side, does such a problem exist > on a reading side? I am using 2.4.1, perhaps there is a fix in a later > version? Additional info: my file is from a data provider, do not know what they used to compress it. Previous files worked ok, this one is the 1st over 2GB. Winzip has no problem with it. From zacherates at gmail.com Sat Jul 21 10:36:58 2007 From: zacherates at gmail.com (zacherates) Date: Sat, 21 Jul 2007 14:36:58 -0000 Subject: Sorting dict keys In-Reply-To: <5ge3ujF3fk7i6U2@mid.individual.net> References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> <1185007449.179903.5480@w3g2000hsg.googlegroups.com> <5ge3ujF3fk7i6U2@mid.individual.net> Message-ID: <1185028618.008818.142920@n2g2000hse.googlegroups.com> >From ESR's "Why python?" b = a.keys(); b.sort() Two statements, one line. Doesn't create an incidental copy the way sorted does but I'm not sure how much you like to jam on one line. Cheers, Aaron From benruza at gmail.com Mon Jul 2 06:39:18 2007 From: benruza at gmail.com (Bruza) Date: Mon, 02 Jul 2007 10:39:18 -0000 Subject: Bug in Python class static variable? Message-ID: <1183372758.251109.34550@z28g2000prd.googlegroups.com> I am trying to define a class static variable. But the value of the static variable seems to be only defined inside the file that the class is declared. See the code below. When I run "python w.py", I got: 000=======> Hello World 001=======> Hello World 002=======> Not Initialized 003=======> Not Initialized 004=======> Not Initialized 005=======> Hello World Looks like even though the class variable "ClassW.w_classStaticVar" was set inside "startup()", the value never carried over to functions in "a.py". Is this a bug in Python's static variable handling. I am running Python 2.4.4. Ben #===== file: w.py ======== from a import * class ClassW: w_classStaticVar = "Not Initialized" def initA(self): print "001=======>", ClassW.w_classStaticVar obj = ClassA() obj.init2() print "005=======>", ClassW.w_classStaticVar def startup(): ClassW.w_classStaticVar = "Hello World" wo = ClassW() print "000=======>", ClassW.w_classStaticVar wo.initA() if __name__ == '__main__': startup() #===== file: a.py ======== from w import * class ClassA: def __init__(self): print "002=======>", ClassW.w_classStaticVar def init2(self): print "003=======>", ClassW.w_classStaticVar w = ClassW() print "004=======>", ClassW.w_classStaticVar From richyjsm at gmail.com Wed Jul 4 21:48:58 2007 From: richyjsm at gmail.com (richyjsm at gmail.com) Date: Thu, 05 Jul 2007 01:48:58 -0000 Subject: Proposal: s1.intersects(s2) In-Reply-To: References: <5f1pldF3a62csU5@mid.uni-berlin.de> Message-ID: <1183600138.759015.246040@c77g2000hse.googlegroups.com> On Jul 4, 8:14 pm, Steven D'Aprano wrote: > However, there's a very subtle flaw in the idea. While "the intersection" > of two sets is well-defined, "these two sets intersect" is (surprisingly!) > _not_ well-defined. Poppycock! It's perfectly well defined: two sets intersect if and only if their intersection is nonempty. There's absolutely no reason to single out the empty set for special treatment in this definition. > The problem comes if we (perhaps naively) try to say that if a set A is a > subset of set B, set A must intersect with B. Well of course false statements are going to cause problems. > (Not all intersecting sets are subsets, but all subsets are intersecting sets.) Not true. > As a result, any proposed function or method that returns a True/False > value for whether set A intersects with set B needs to define (and > justify) what it means to say that two sets intersect when one or both are > the empty set. Nope. There's one, obvious, correct definition, as given above. No need to mention the empty set at all. Richard From gagsl-py2 at yahoo.com.ar Fri Jul 27 05:24:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 27 Jul 2007 06:24:48 -0300 Subject: adding a docstring to an instancemethod References: <1185361537.733690.238280@k79g2000hse.googlegroups.com> <1185438522.978804.118010@19g2000hsx.googlegroups.com> <1185472092.427646.266270@g4g2000hsf.googlegroups.com> Message-ID: En Thu, 26 Jul 2007 14:48:12 -0300, jelle escribi?: > Hi Gabriella, > thanks for pointing me in the right direction: Twice in a week... I'll have to revise my own masculinity... -- Gabriel Genellina From rbsharp at gmx.de Tue Jul 3 03:09:12 2007 From: rbsharp at gmx.de (rbsharp at gmx.de) Date: Tue, 03 Jul 2007 00:09:12 -0700 Subject: unify els database In-Reply-To: <1183383335.842730.41600@q69g2000hsb.googlegroups.com> References: <1183383335.842730.41600@q69g2000hsb.googlegroups.com> Message-ID: <1183446552.345276.44930@k29g2000hsd.googlegroups.com> On Jul 2, 3:35 pm, luca72 wrote: > Hello > > How i can use to connect to a unify els database with python > > Regards > > Luca Hello, could you be more specific. I know that there is a ODBC-Driver for unify, if this is an option then it might be easier. Or do you want to connect to the unify-database using HLI? And if so, on what platform? I work with the unify database using HLI on various unix platforms. It was by no means easy, but it can be made to work. Greetings, Richard Sharp From wildemar at freakmail.de Mon Jul 16 08:31:16 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Mon, 16 Jul 2007 14:31:16 +0200 Subject: questions about functions inside a function In-Reply-To: <469B6186.3060709@freakmail.de> References: <469B5B3B.8040901@gmail.com> <469B6186.3060709@freakmail.de> Message-ID: <469B6514.1030207@freakmail.de> Wildemar Wildenburger wrote: >> for f in a: >> print f() >> 0 >> 1 >> 4 >> 9 >> >> How to achieve this? >> >> Thanks a lot! >> >> >> > I fail to see the point, sorry. Why would you want that? If you simply > want a list of values you do: > > >>>> a = [i**2 for i in range(4)] >>>> > > Can you elaborarate on what it is you really want. > > /W > Sorry, I'm an idiot. Nevermind. :-/ /W From evan at yelp.com Wed Jul 18 19:31:35 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 18 Jul 2007 16:31:35 -0700 Subject: Newbie: freebsd admin scripting In-Reply-To: References: Message-ID: On 7/17/07, Muffin wrote: > I am using python for the first time on Unix and on FBSD. I need a few > pointer, tips or tricks on scripting on config files. Mostly admin type > configs like the rc.conf file usually setup like: > > someiteam=somevalue #sometype of description > > Where I would like to toggle the somevalue in an easy way. I realize I > could parse it with reg expression but that sounds kinda complicated. Is > there an easer way a Unix python way of dealing with these type of > config files. > > I found a built in mod for parseconfig but it deal with .ini file styles > (windows) that include a [section] header as well as uses > someiteam=somevalue format. I believe it requires the header though. I think you're referring to ConfigParser. This is the standard way to do config files in Python, and it is very simple to use and work with, so I would recommend using it. The documentation can be found at http://docs.python.org/lib/module-ConfigParser.html > Books or howtos regarding Unix admin scripting(python) would be great. > Is this type of scripting mainly executing a Unix command and capturing > and parsing its output like this: > > x=command.getoutput("ifconfig") > > and them parsing x for what I want or is there a name space I can call > to get , for example, a list of all interfaces? > > I have mainly used python in windows using the com space or win32 api > aside from the base python lib, on Unix I am lost on what to do or how > things are generally done. Advise on how to "think" in Unix python terms > if that makes any sense. You should use the subprocess module for interacting with other programs, although it can be a little burdensome to work with. Ideally you'll have a module that implements the functionality that you need to use directly, rather than trying to control other processes from Python. Also, you should keep a collection of the scripts you write and try to look for common patterns that come up. If you're diligent with this you can start writing your own sysadmin python toolkit to make your job a lot easier. -- Evan Klitzke From UrsusMaximus at gmail.com Sat Jul 14 12:25:50 2007 From: UrsusMaximus at gmail.com (UrsusMaximus at gmail.com) Date: Sat, 14 Jul 2007 16:25:50 -0000 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: <1184430350.574293.222130@57g2000hsv.googlegroups.com> The Tkinter tutorial refrrred to is at http://infohost.nmt.edu/tcc/help/pubs/tkinter// and it is a great starting point ... Ron Stephens On Jul 14, 3:01 am, "Hendrik van Rooyen" wrote: > "Chris Carlen" wrote: > > > Form 2: Use Python and PySerial and TkInter or wxWidgets. > > > Pro: Cross-platform goal will likely be achieved fully. Have a > > programmer nearby with extensive experience who can help. > > Con: Must learn new language and library. Must possibly learn a > > completely new way of thinking (OOP) not just a new language syntax. > > This might be difficult. > > This is the way to go. - Trust me on this. > > When you describe your history, it is almost an exact parallel to mine. > In my case, I have been doing real low level stuff (mostly 8031 assembler) > since 1982 or so. And then I found python in a GSM module (Telit), and > I was intrigued. > > I really appreciate your comments on OO - it parallels a lot of what I feel > as there is a lot of apparent BS that does not seem to "do anything" at first > sight. > > However- for the GUI stuff, there is an easily understood relationship between > the objects and what you see on the screen - so its a great way of getting > into OO - as far as people like you and me will go with it, which is not very > far, as we tend to think in machine instructions... > > And for what its worth - you can programme assembler-like python, and it also > works. > > The best thing to do is just to spend a few days playing with say Tkinter. > I use a reference from the web written by John W Shipman at New Mexico > Tech - it is succinct and clear, and deserves more widespread publicity. > > Google for it - I have lost the link, although I still have the pdf file. > > You will also find the interactive prompt that you get when you type > python at a command prompt invaluable - it lets you play with and debug > small code snippets so that you can learn as you go along - it really speeds > up the whole learning process, and makes it almost painless. > > All this talking is just wasting time - you could have had your first frame up > on the screen already, with a blank canvas, ready for drawing. It really goes > that quick, once you start. > > So the answer to the title question is: Yes - a low level programmer can learn > OOP, and its in fact easier than it looks, as almost all the heavy lifting has > been done for you by others. > > - Hendrik From nospam.themindstorm at gmail.com Tue Jul 24 20:22:18 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Wed, 25 Jul 2007 00:22:18 +0000 (UTC) Subject: classmethod & staticmethod References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> <46a5b2ad$0$18903$426a74cc@news.free.fr> Message-ID: "Steven D'Aprano" wrote in news:pan.2007.07.24.23.21.20.988798 at REMOVE.THIS.cybersource.com.au: > On Tue, 24 Jul 2007 21:35:58 +0000, Alex Popescu wrote: > >> Neil Cerutti wrote in >> news:slrnfaccgl.1gk.horpner at FIAD06.norwich.edu: >> >>> On 2007-07-24, Alex Popescu wrote: >>>> Bruno Desthuilliers >>>> wrote in >>>> news:46a5b2ad$0$18903$426a74cc at news.free.fr: >>>> >>> >>> [snip...] >>> > > Use self.class_list when you want to use inheritance. > As a matter of style, how do you figure out that class_list is a class attribute and not an instance attribute? (I don't remember seeing anything in the PEP describing the coding style). tia, ./alex -- .w( the_mindstorm )p. From sjmachin at lexicon.net Wed Jul 11 16:56:22 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 11 Jul 2007 13:56:22 -0700 Subject: Encode Bytes In-Reply-To: References: Message-ID: <1184187382.298949.211560@j4g2000prf.googlegroups.com> On Jul 12, 4:40 am, "albert_k_arhin" wrote: > Hi All, > I am new to python and I am using a strip down version of > python that does not support struc,pack,etc. > > I have a binary protocol that is define as follows: > > PART OffSet Lenght > ============================ > ID 0 2 > VER 2 1 > CMD 3 2 > PGKID 5 2 > DATE 7 3 > TIME 10 3 > CRC 13 2 > DLEN 15 2 > > How do I encode these the offset is in Bytes. > You haven't defined your data precisely enough to allow use of struct.pack even if it were available to you. Are all of the 1-byte fields unsigned integers (range 0 to 255 inclusive), or are some signed (range -128 to 127)? Are all of the 2-byte fields unsigned integers (range 0 to 65535 inclusive) or are some signed (-32768 to 32767)? What is the format of the 3-byte DATE and TIME fields? What type is your starting value -- datetime.datetime? Littlendian or bigendian? Here's an example of the sort of function you'll need to write: >>> def packu2le(anint): ... """Produce a 2-byte littlendian string from an unsigned integer""" ... assert 0 <= anint <= 65535 ... byte0 = anint & 0xff ... byte1 = anint >> 8 ... return chr(byte0) + chr(byte1) ... >>> packu2le(0) '\x00\x00' >>> packu2le(255) '\xff\x00' >>> packu2le(256) '\x00\x01' >>> packu2le(65535) '\xff\xff' >>> packu2le(-1) Traceback (most recent call last): File "", line 1, in File "", line 2, in packu2le AssertionError >>> HTH, John From mensanator at aol.com Fri Jul 27 15:01:41 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Fri, 27 Jul 2007 12:01:41 -0700 Subject: 128 or 96 bit integer types? In-Reply-To: References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com> Message-ID: <1185562901.206212.52570@j4g2000prf.googlegroups.com> On Jul 27, 1:27 pm, Peter Otten <__pete... at web.de> wrote: > Robert Dailey wrote: > > Is there build-in or third party support for large integer types, such > > as 96 or 128 bits in size? I require such large sizes for precision > > issues (nanoseconds). Thanks. > >>> SECOND = 10**9 > >>> YEAR = 365*24*60*60 > >>> 2**128/SECOND/YEAR > > 10790283070806014188970L > > What are you measuring? The age of the universe? In nanoseconds? > > :-) Well, 2**96 would only be 2512308552583 years. > > Peter From kar1107 at gmail.com Wed Jul 4 17:52:03 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Wed, 04 Jul 2007 21:52:03 -0000 Subject: using subprocess for non-terminating command In-Reply-To: <1183549118.773813.132940@r34g2000hsd.googlegroups.com> References: <1183549118.773813.132940@r34g2000hsd.googlegroups.com> Message-ID: <1183585923.737596.220730@j4g2000prf.googlegroups.com> On Jul 4, 4:38 am, Phoe6 wrote: > Hi all, > Consider this scenario, where in I need to use subprocess to execute a > command like 'ping 127.0.0.1' which will have a continuous non- > terminating output in Linux. > > # code > > >>>import subprocess > >>>process = subprocess.Popen('ping 127.0.0.1', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) > >>>print process.pid # returns pid > >>>print process.poll() # returns None!!! this is strange. It's expected behavior. It means the child process is still running. > >>>print process.stdout.read() > > # This hangs at this point. This too is expected behavior. 'ping ' runs forever generating continuous output. It doesn't stop by itself. read() reads until there is data available in the file object. Thus it doesn't ever finish since the child never stops generating data. If you do read(n), then it reads n bytes and returns. > How should I handle these kind of commands (ping 127.0.0.1) with > subprocess module. I am using subprocess, instead of os.system because > at anypoint in time, I need access to stdout and stderr of execution. > Using subprocess is good. Just ensure your child stops data generation at some point. For ping, you can use '-c ' or some other application, you can try closing it's stdin (e.g. cat, bc, gdb) Thanks, Karthik > Thanks, > Senthil From nagle at animats.com Fri Jul 6 15:57:42 2007 From: nagle at animats.com (John Nagle) Date: Fri, 06 Jul 2007 12:57:42 -0700 Subject: Auto-parallelizing without decorators? In-Reply-To: References: Message-ID: Kirk Strauser wrote: > I was thinking about how a lot of Lisp proponents claim that Lisp is > inherently parallelizable because its functions don't have (or are not > supposed to have) side effects, and therefore the compiler can easily tell > which calls may be run in parallel instead of strictly serially. I'm not a > Lisp expert so I can't say whether that's true or not, but it seems like an > interesting idea for Python. > > Suppose that Python had a new decorator, say "@parallelizable". Functions > so decorated would be eligible for multi-processed or multi-threaded > execution by such native constructs as list comprehensions, or the map() > function. That implies much smarter compilers than we've seen to date for Python. A more useful idea might be to provide a map/reduce library in the sense that Google uses the term. Google's concept of "map/reduce" is that the mapped function is applied to all the elements of the list simultaneously, up to the limits of resources available. The result of each function is a name/value tuple. The reduction process consists of collecting all tuples with the same name and feeding them to copies of the "reduce" function in no particular order, with the "reduce" function producing fewer output tuples than input tuples. The "reduce" function is applied repeatedly in a tree sense until all output tuples have been reduced. See: http://labs.google.com/papers/mapreduce.html Contrast this with Python's "reduce", which is inherently sequential. John Nagle From Eric_Dexter at msn.com Mon Jul 9 04:36:26 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 09 Jul 2007 01:36:26 -0700 Subject: trouble controlling vim with subprocess on windows machine Message-ID: <1183970186.663847.4380@o61g2000hsh.googlegroups.com> I am having trouble contolling vim with subprocess on a windows machine. It appears that vim comes up on the machine all right and it sometimes looks like it is doing the searchs what I am asking it to do but when I am asking it to load a file it doesn't do anything. Is there something I need to do to push the data through the pipe?? Here is a couple different ways I am trying to do it. def load_instrument(instr_name, csdname): "load an instrument using vim a path should be defined for vim currently I am doing that with the .bat file that loads the program" f = open('csdfile.tmp','w') my_path = "/dex tracker" cmd = ["gvim",csdname] vimin = subprocess.Popen(cmd,stdin=subprocess.PIPE)#.comunicate() [0] #, stdout = f, stderr = f, cwd = my_path ) #f.close #x = subprocess.Popen("clear").communicate(None)[0] innum = csr.return_unique_instr_number(csdname) - 1 cmd = """/;' +'\n' print(cmd) vimin.stdin.write(cmd) cmd = """/;""" +'\n' vimin.stdin.communicate(cmd) cmd = ':r ' + instr_name +'\n' print(cmd) vimin.stdin.write(cmd) #vimin.stdin.write(instr_name + '\n') cmd = instr_name + '\n' f.close() def load_instrument2(instr_name, csdname): "second try uses comunicate" cmd = ["gvim",csdname] proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, ) cmd = """/;start""" + '\n' proc.communicate(cmd)[0] cmd = """/;""" + '\n' proc.communicate(cmd)[0] cmd = ':r ' + instr_name + '/n' proc.communicate(cmd)[0] proc.close() I am calling these with load_instrument2("""strings.orc""",'bay-at-night.csd') and I define the path of vim in a batch file befour I call the routines path c:\program files\vim\vim71 python_awk_bridge.py pause From nick at craig-wood.com Tue Jul 10 18:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 10 Jul 2007 17:30:03 -0500 Subject: subprocess popen trouble References: <1184085837.104954.235230@n2g2000hse.googlegroups.com> Message-ID: nik wrote: > I am having trouble using subprocess popen and stdin/stdout > > I have the following simple test application written in C++, that just > echoes back the stdin. It works fine running from the command line: > > #include > #include > > int main (int argc, char * const argv[]) { > int currenttemp = 0; > int settemp = 0; > char* str; > > while(currenttemp < 500){ > gets(str); > sscanf(str, ">%d", &settemp); > currenttemp = settemp; > printf("<%d\n", currenttemp++); > } > return 0; > } You are being caught out by stdio buffering. You can a) put a fflush(stdout); after the printf() b) change the buffering mode of stdin/stdout with setvbuf() c) use pexpect which will connect to your prog with pseudo-ttys I recommend c) - subprocess isn't really very good at interactive conversations between the main process and the subprocess - buffering will cause you problems. You may in this simple case get it to work with a) or b) though! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From yinghe.chen at jeppesen.com Tue Jul 24 06:32:44 2007 From: yinghe.chen at jeppesen.com (Yinghe Chen) Date: Tue, 24 Jul 2007 12:32:44 +0200 Subject: how to get next month string? References: Message-ID: My bad, for Dec 07, it shall output as JAN08. "Yinghe Chen" wrote in message news:f84kee$q32$1 at wake.carmen.se... > Hi, > Could someone help on how to use python to output the next month string > like this? > > "AUG07", suppose now is July 2007. > > I think also need to consider Dec 07 case, it is supposed to output as > below: > "JAN07". > > datetime module seems not supporting the arithmatic operations, any hints? > > Thanks in advance, > > Yinghe Chen > From jakub.stolarski at gmail.com Wed Jul 25 03:32:12 2007 From: jakub.stolarski at gmail.com (Jakub Stolarski) Date: Wed, 25 Jul 2007 07:32:12 -0000 Subject: From D In-Reply-To: References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> Message-ID: <1185348732.805841.14450@w3g2000hsg.googlegroups.com> On Jul 25, 1:08 am, Steven D'Aprano wrote: > Underscores in numerics are UGLY. Why not take a leaf out of implicit > string concatenation and allow numeric literals to implicitly concatenate? > > Python already does: > "hello-" "world" => "hello-world" > > Propose: > 123 456 789 => 123456789 > 123.456 789 => 123.456789 > I like that. From robert.rawlins at thinkbluemedia.co.uk Wed Jul 4 06:03:20 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 4 Jul 2007 11:03:20 +0100 Subject: Which Python Version Message-ID: <00b601c7be22$9cf81ce0$d6e856a0$@rawlins@thinkbluemedia.co.uk> Hello Chaps, Is there a command I can run to confirm which version of python I'm running? Another thing I've always wondered, should i be running my applications using './MyFile.py' or 'Python MyFile.Py' what are the benefits of each method? One thing I have noticed is that when I used 'Python MyFile.Py' my processor usage was a lot higher, is that normal? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From harelmalka at gmail.com Tue Jul 10 10:21:01 2007 From: harelmalka at gmail.com (Harel) Date: Tue, 10 Jul 2007 14:21:01 -0000 Subject: Can I Redirect debug output from HTTPConnection to a file? In-Reply-To: <1184059924.122878.241210@o61g2000hsh.googlegroups.com> References: <1184059924.122878.241210@o61g2000hsh.googlegroups.com> Message-ID: <1184077261.171795.112960@w3g2000hsg.googlegroups.com> I'll answer myself then: import os ioLogFile = file(LOG_FILE_PATH + IO_LOG_FILE, "w") #get a log file created os.dup2(config.ioLogFile.fileno(), 1) #route stdout (file descriptor 1) to the log file's one Thanks Harel On Jul 10, 10:32 am, Harel wrote: > I'm using httplib.HTTPConnection to perform http connections and > during the beta period of the application I wanted to log its verbose > output [set_debuglevel(5)]. However, raising the debuglevel just > outputs it to stdout. can I redirect that to a file? My app uses the > logging module for logging and I'd like to use that to log into the > standard log it generates. > > Any ideas? > Thanks, > Harel From gagsl-py2 at yahoo.com.ar Mon Jul 16 14:13:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jul 2007 15:13:09 -0300 Subject: The ** operator ambiguous? References: <1184607614.904143.219330@w3g2000hsg.googlegroups.com> Message-ID: En Mon, 16 Jul 2007 14:40:14 -0300, Robert Dailey escribi?: > I noticed that the ** operator is used as the power operator, however > I've seen it used when passing variables into a function. For example, > I was researching a way to combine dictionaries. I found that if you > do this: > > a = {"t1":"a", "t2":"b"} > b = {"t3":"c"} > dict( a, **b ) > > > This combines the two dictionaries. However, I have no idea what the > ** operator is here. I know that when you specify ** as a parameter in > a function definition, it represents a dictionary of parameters passed > in. However, in this example it is NOT being used in a function > definition. It is being used when passing variables into a function. > Can someone explain what this means? I looked in the documentation but > I couldn't find anything. See this section in the tutorial . If you want the dirty details: -- Gabriel Genellina From bignose+hates-spam at benfinney.id.au Sun Jul 15 21:44:17 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 16 Jul 2007 11:44:17 +1000 Subject: 2**2**2**2**2 wrong? Bug? References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> <1184351416.166930.290710@k79g2000hse.googlegroups.com> <1184362323.476796.22570@w3g2000hsg.googlegroups.com> Message-ID: <87ejj9gm1a.fsf@benfinney.id.au> Wayne Brehaut writes: > On Fri, 13 Jul 2007 14:32:03 -0700, "mensanator at aol.com" > wrote: > >You can call Roman Numerals a Tally System of Radix 1. > > I can call it what I want--within reason--so long as those I'm mainly > addressing understand what I mean and the context in which I'm saying > it. Just don't call it late for dinner. -- \ "I bet one legend that keeps recurring throughout history, in | `\ every culture, is the story of Popeye." -- Jack Handey | _o__) | Ben Finney From http Tue Jul 31 23:38:52 2007 From: http (Paul Rubin) Date: 31 Jul 2007 20:38:52 -0700 Subject: [OT] Google message munging (was: Live editing...) References: <1185914335.472511.172040@m37g2000prh.googlegroups.com> <87r6moc4il.fsf@benfinney.id.au> Message-ID: <7xwswfdiur.fsf@ruckus.brouhaha.com> 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. From inigoserna at gmail.com Sun Jul 8 15:56:58 2007 From: inigoserna at gmail.com (Inigo Serna) Date: Sun, 8 Jul 2007 21:56:58 +0200 Subject: Changing the user-agent in urllib In-Reply-To: <8a6b8e350707081221k6d010246t832e6d6f9c9235a@mail.gmail.com> References: <8a6b8e350707081221k6d010246t832e6d6f9c9235a@mail.gmail.com> Message-ID: <20070708195658.GA30201@inigo.katxi.org> On Sun, Jul 08, 2007 at 12:21:38PM -0700, James Matthews wrote: > Is there anyway of changing the user-agent in urllib without sub classing > it? Yes, >>> import urllib >>> urllib.URLopener.version = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0; T312461)' Regards, I?igo Serna From rcdailey at gmail.com Fri Jul 6 15:31:56 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 06 Jul 2007 19:31:56 -0000 Subject: ImportError: "No Module named xxx" Message-ID: <1183750316.740239.257010@m36g2000hse.googlegroups.com> I created a basic python file and made an attempt to execute it from the command line, however it gives me a weird error after the python file has been executed: Traceback (most recent call last): File "C:\Python25\lib\runpy.py", line 87, in run_module raise ImportError("No module named " + mod_name) ImportError: No module named compile.py The command I executed was: "python -m compile.py" (compile.py is my python script) Can anyone help me figure out why it's doing this? From carsten at uniqsys.com Wed Jul 25 15:46:14 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 25 Jul 2007 15:46:14 -0400 Subject: is_iterable function. In-Reply-To: <5gplj6F3gg2e0U3@mid.uni-berlin.de> References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> <5gplj6F3gg2e0U3@mid.uni-berlin.de> Message-ID: <1185392774.4432.60.camel@dot.uniqsys.com> On Wed, 2007-07-25 at 19:11 +0000, Marc 'BlackJack' Rintsch wrote: > And just calling `iter()` doesn't work either: > > In [72]: class A: > ....: def __getitem__(self, key): > ....: if key == 42: > ....: return 'answer' > ....: raise KeyError > ....: > > In [73]: iter(A()) > Out[73]: > > In [74]: a = iter(A()) > > In [75]: a.next() > --------------------------------------------------------------------------- > Traceback (most recent call last) > > /home/bj/ in () > > /home/bj/ in __getitem__(self, key) > > : > > > So there's no reliable way to test for "iterables" other than actually > iterate over the object. You seem to say that your 'a' object is not iterable. I disagree. While it's true that it raises an exception upon retrieval of the zeroth iteration, that situation is quite different from attempting to iterate over the number 10, where you can't even ask for a zeroth iteration. To illustrate this point further, imagine you write an object that iterates over the lines of text read from a socket. If the connection is faulty and closes the socket before you read the first line, the zeroth iteration raises an exception. Does that mean the object is iterable or not depending on the reliability of the socket connection? I find that notion hard to swallow. -- Carsten Haese http://informixdb.sourceforge.net From steve at holdenweb.com Tue Jul 31 14:11:14 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 31 Jul 2007 14:11:14 -0400 Subject: standalone process to interact with the web In-Reply-To: <1185904623.754078.198910@e9g2000prf.googlegroups.com> References: <1185899130.331170.151980@e16g2000pri.googlegroups.com> <1185904623.754078.198910@e9g2000prf.googlegroups.com> Message-ID: beginner wrote: > Hi Steve, > > On Jul 31, 11:42 am, Steve Holden 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 - >> >> http://wwwsearch.sourceforge.net/mechanize/ >> >> With mechanize and its partner ClientForm you can rule the web world ;-) >> >> 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 ------------- > > 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. > > > > Well, surely in that case you can use any protocol you like. It's up to the web server and your "web server server" to agree how to communicate. Take a look at the SocketServer library, for example. regartds 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 claird at lairds.us Sun Jul 1 23:50:45 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 2 Jul 2007 03:50:45 +0000 Subject: Tiny/small/minimalist Python? References: <1183332951.122782.212720@o11g2000prd.googlegroups.com> Message-ID: In article <1183332951.122782.212720 at o11g2000prd.googlegroups.com>, rtk wrote: >I'm looking for information on building a tiny/small/minimalist/ >vanilla python interpreter. One that implements the core language and >a few of the key modules but isn't tied to any specific operating >system. > >I guess I'm asking for the smallest subset of the standard Python >source code files that is necessary to get a working interpreter using >a plain C compiler. > >Is this even possible? If so, has someone done it already? I've >looked on Google and in comp.lang.python but nothing comes up. . . . Tiny Python, PyMite, EmbeddedPython, Diet Python, deeply embedded python, ...--I need to write up a page that explains these. From evan at yelp.com Tue Jul 3 14:59:30 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 3 Jul 2007 11:59:30 -0700 Subject: Python compilation ?? In-Reply-To: <468a0850$0$14120$426a74cc@news.free.fr> References: <468a0850$0$14120$426a74cc@news.free.fr> Message-ID: On 7/3/07, Bruno Desthuilliers wrote: > Evan Klitzke a ?crit : > > On 7/2/07, Cathy Murphy wrote: > >> Is python a compiler language or interpreted language. If it is > >> interpreter > >> , then why do we have to compile it? > > > > It's an interpreted language. It is compiled into bytecode > > By this definition, Java is an interpreted language. Sorry, I didn't say that it's an interpreted language because it's compiled into bytecode, only that it is an interpreted language and it is compiled into bytecode. Sorry if there was a confusion. -- Evan Klitzke From aleax at mac.com Fri Jul 6 23:25:59 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 6 Jul 2007 20:25:59 -0700 Subject: object references/memory access References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1183407411.397142.304790@e16g2000pri.googlegroups.com> <1183417108.245203.158830@x35g2000prf.googlegroups.com> <4689e535$0$23896$9b622d9e@news.freenet.de> <1183488824.131448.62720@x35g2000prf.googlegroups.com> <5f32o8F3aeadqU1@mid.individual.net> Message-ID: <1i0uj8l.1v69lbi12bjin0N%aleax@mac.com> Dennis Lee Bieber wrote: ... > Think VMS was the most applicable for that behavior... Haven't seen > any dynamic priorities on the UNIX/Linux/Solaris systems I've > encountered... Dynamic priority scheduling is extremely common in Unixen today (and has been for many years); see e.g. for the _enhancements_ FreeBSD 5.2 brought to this idea a few years ago, for example. Alex From nospam at nospam.com Mon Jul 30 22:35:55 2007 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 31 Jul 2007 04:35:55 +0200 Subject: Why no maintained wrapper to Win32? References: <46ab694e$0$17577$9b622d9e@news.freenet.de> <59kna3p8r0cu2gk6hs5lbig8cjj8klatju@4ax.com> <1185762820.496821.298530@19g2000hsx.googlegroups.com> <1185770944.301464.85060@b79g2000hse.googlegroups.com> Message-ID: On Sun, 29 Jul 2007 21:49:04 -0700, sturlamolden wrote: >Why inflict suffering on yourself with MFC when you can use wxPython >or PyGTK? Because I'd like to avoid having to pack several MB + having to install the toolkit. Considering the size of the typical Python script, it seemed overkill. >Sure, you could use ctypes to make calls into user32.dll, gdi32.dll >and kernel32.dll. Then you can program Python GUIs using the plain >Win32 API, avoiding PyWin32's MFC or wxPython. But who would do such a >thing? So the PyWin32 interface doesn't make it easier to program Win32 GUI apps? It's just C that looks like Python? Guess I have the answer as to no one seems to write GUI apps for Windows natively :-) Thanks. From http Thu Jul 12 23:14:51 2007 From: http (Paul Rubin) Date: 12 Jul 2007 20:14:51 -0700 Subject: Fastest way to convert a byte of integer into a list References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> <1184284461.506663.75500@g12g2000prg.googlegroups.com> <1184284861.695430.99300@e9g2000prf.googlegroups.com> <7xr6ndtae7.fsf@ruckus.brouhaha.com> <1184287796.252097.46660@x35g2000prf.googlegroups.com> <1184289204.494179.244820@w3g2000hsg.googlegroups.com> <1184295931.938495.239720@x35g2000prf.googlegroups.com> Message-ID: <7x7ip5yoyc.fsf@ruckus.brouhaha.com> Godzilla writes: > Regarding to the 32-bit number, the lenght is variable but it is > usually defined at design time... That you're trying to represent it as a list of bits at all is weird, and probably likely to slow the program down. You do know that python has arbitrary sized ints, right? From istvan.albert at gmail.com Fri Jul 27 09:24:24 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 27 Jul 2007 13:24:24 -0000 Subject: zip() function troubles In-Reply-To: References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> <1185502539.598349.159330@l70g2000hse.googlegroups.com> Message-ID: <1185542664.266274.72370@w3g2000hsg.googlegroups.com> On Jul 27, 2:16 am, "Terry Reedy" wrote: > References are not objects. yes this a valid objection, but in all fairness the example in the original post operates on comparably sized objects and also exhibited unexpected performance degradation as it turns out the garbage collection is the culprit, I never used to have to care about gc (and that's great!), but now that I'm that I'm shuffling 1Gb chunks I have to be more careful. best, Istvan From fdemmer at gmail.com Tue Jul 3 05:49:30 2007 From: fdemmer at gmail.com (Florian Demmer) Date: Tue, 03 Jul 2007 02:49:30 -0700 Subject: Python 2.5 from source without tcl/tk Message-ID: <1183456170.547500.118910@n60g2000hse.googlegroups.com> Hi, I am going nuts here... I thought had a solution for this a few weekas ago but my hdd crashed and i put the note i wrote somewhere I had no backup. The system is a RedHat Enterprise 4 and I cannot install additional rpms. While the ./configure seems to go through fine I get a "INFO: Can't locate Tcl/Tk libs and/or headers" during the make. tk.h and tcl.h are in /usr/include In other discussions I found that a missing X11/Xlib.h can be the problem. That I don't have and cannot install. Is there a way to completely leave out the tcl stuff when compiling? I think what i did few weeks back was temporarily moving some tcl/tk files away and back after the installation... but I cannot get it to work now :( From gagsl-py2 at yahoo.com.ar Fri Jul 27 15:59:02 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 27 Jul 2007 16:59:02 -0300 Subject: Problem embedding in small Win32 App References: Message-ID: En Fri, 27 Jul 2007 16:06:32 -0300, Brad Johnson escribi?: > PyObject* o = PyDict_GetItemString(_d, "_outcatcher"); > PyObject* a = PyObject_GetAttrString(o, "data"); > ::MessageBox(NULL, PyString_AsString(a), _T(""), NULL); > > However, it only works twice. On the third try, I get an access > violation trying to access the stdout object (for a print statement). > The pointer appears to be valid, but all of the data has overwritten > with 0xDBDBDBDB, with obvious consequences. By far, the most common problem extending/embedding Python is to do wrong reference counts. Read http://docs.python.org/ext/refcounts.html again (I hope you already did!) and make sure you don't hold a pointer to an object without incrementing its reference count, by example. If you can shrink your application to the minimum code that shows the problem, try posting it here. -- Gabriel Genellina From kimiraikkonen85 at gmail.com Mon Jul 2 13:19:14 2007 From: kimiraikkonen85 at gmail.com (kimiraikkonen) Date: Mon, 02 Jul 2007 10:19:14 -0700 Subject: The best platform and editor for Python In-Reply-To: <1183380558.135204.83790@e16g2000pri.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> Message-ID: <1183396754.359291.197340@n2g2000hse.googlegroups.com> On Jul 2, 3:49 pm, evil tabby cat wrote: > On Jul 2, 5:10 am, kimiraikkonen wrote: > > > Hi, > > For experienced with Pyhton users, which developing software and > > enviroment would you suggest for Pyhton programming? Compiler+Editor > > +Debugger. > > > Also what are your suggestions for beginners of Pyhton programming? > > > Thank you. > > http://www.wingware.com/is pretty impressive but non-free of both > beer & speech varieties Thanks for the replies so far. Also i have to learn: What is the most reliable and easy way to start learning Ptyhon? Books? Trusted code sammples(where?)? I know the importance and eases of Python quite. Thanks. From diener896092_no_spam_here at bellsouth.net Sat Jul 7 00:28:08 2007 From: diener896092_no_spam_here at bellsouth.net (Edward Diener) Date: Sat, 07 Jul 2007 00:28:08 -0400 Subject: Getting the home directory in Python and a bug in os.path.expanduser Message-ID: What is the generic operating system way of getting the home directory ? I am guessing it is os.path.expanduser("~"). Is there a better way or an alternate way ? If it is as I surmise, the aforementioned expanduser("~") of os.path seems incorrect to me under Windows. The document says: "On Windows, only "~" is supported; it is replaced by the environment variable HOME or by a combination of HOMEDRIVE and HOMEPATH." But HOME is never the home directory for Windows, only the combination of HOMEDRIVE and HOMEPATH is valid, which is always set. If MSYS is installed under Windows, where HOME must be set to the MSYS home directory for a given user in order to emulate Linux/Unix, attempting to use os.path.expanduser("~") will incorrectly return the MSYS home directory for a given user rather than the Windows home directory for the logged in user. So I think the os.path.expanduser("~") works incorrectly in this case and needs to be fixed, else you are telling users never to use MSYS under Windows. From stefan.behnel-n05pAM at web.de Thu Jul 26 12:17:56 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 26 Jul 2007 18:17:56 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? In-Reply-To: <0T49d313I3ogNv8%stesch@parsec.no-spoon.de> References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49d313I3ogNv8%stesch@parsec.no-spoon.de> Message-ID: <46A8C934.3010601@web.de> Stefan Scholl wrote: > Stefan Behnel wrote: >> Stefan Scholl wrote: >>> Stefan Behnel wrote: >>>> Stefan Scholl wrote: >>>>> Well, http://docs.python.org/lib/module-xml.sax.html is missing >>>>> the fact, that I can't use Unicode with parseString(). >>>>> >>>>> This parseString() uses cStringIO. >>>> Well, Python unicode is not a valid *byte* encoding for XML. >>>> >>>> lxml.etree can parse unicode, if you really want, but otherwise, you should >>>> maybe stick to well-formed XML. >>> The XML is well-formed. Works perfect in Python 2.4 with Python >>> unicode and Python sax parser. >> The XML is *not* well-formed if you pass Python unicode instead of a byte >> encoded string. Read the XML spec. >> >> It would be well-formed if you added the proper XML declaration, but that is >> system specific (UCS-4 or UTF-16, BE or LE). So don't even try. > > Who cares? I'm not calling any external tools. XML cares. If you want to work with something that is not XML, do not expect XML tools to help you do it. XML tools work with XML, and there is a spec that says what XML is. Your string is not XML. Stefan From mail at microcorp.co.za Sun Jul 8 04:59:58 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 8 Jul 2007 10:59:58 +0200 Subject: Where is the syntax for the dict() constructor ?! References: <468D1D9D.6060002@gmail.com><468D3445.2060408@gmail.com><1183675552.466967.136360@i13g2000prf.googlegroups.com><5f6fo1F3b25tsU1@mid.uni-berlin.de><5f8rrpF3c8qopU1@mid.uni-berlin.de> <1183853628.296224.107400@i13g2000prf.googlegroups.com> Message-ID: <00bc01c7c13f$573770a0$03000080@hendrik> "John Machin" wrote: 8<------------ nice explanation of quoting problems ------------- > (2) A field containing an odd number of " characters (or more > generally, not meeting whatever quoting convention might be expected > in the underlying data) should be treated with suspicion. How does one program to treat something with suspicion? My stuff tends to either accept or reject... This reminds me (for no discernible reason) of the word "eschew", and of an illustration in a Goon author's book of someone eschewing an architectural example with a pocket sized eschewing instrument - a "pocket eschewer". (He is shown peering at it through the eyepiece) Maybe such fields should be eschewed instead. - Hendrik From vasudevram at gmail.com Sun Jul 1 14:21:33 2007 From: vasudevram at gmail.com (vasudevram) Date: Sun, 01 Jul 2007 18:21:33 -0000 Subject: How does py2exe work? Message-ID: <1183314093.002061.310700@m37g2000prh.googlegroups.com> Hi, I recently checked out py2exe (on Windows). Looks good. Was able to build an EXE out of one of my Python apps. Wondering how it works? Does it actually compile the Python source of your script into machine language, or does it do something more like bundling the Python interpreter, the Python libraries and the script itself, into a file? Will look at the source code but would like to get some ideas ... Thanks ... Vasudev Ram Dancing Bison Enterprises Biz site: http://www.dancingbison.com Blog on software innovation: http://jugad.livejournal.com xtopdf: PDF creation/construction toolkit: http://www.dancingbison.com/products.html From gabe at dragffy.com Wed Jul 25 17:51:07 2007 From: gabe at dragffy.com (Gabriel Dragffy) Date: Wed, 25 Jul 2007 22:51:07 +0100 Subject: Reading data from an ISA port In-Reply-To: <5gkn9lF3g5b6vU1@mid.uni-berlin.de> References: <5gkn9lF3g5b6vU1@mid.uni-berlin.de> Message-ID: <8ADDEED7-BBE5-4F9B-A21A-80E49CDF734E@dragffy.com> On 23 Jul 2007, at 23:09, Diez B. Roggisch wrote: > Gabriel Dragffy schrieb: >> Dear list members >> >> I must admit I am a new user of Python, but it is a language that I >> enjoy using. >> >> For one of my university projects I need to write a program that can >> read several bytes from an ISA port. It has been suggested to me >> that I >> look at using C or Pyinline. If I can I would prefer to continue >> to use >> Python, and Pyinline won't play ball. >> >> I am sure Python can do this for me, but the question is how? What >> modules and code do I need to look? I'd be very grateful for any >> suggestions and advice. > > Python as-is won't help. It has no concept of memory addresses and > direct access to them. However, a trivial C-extension together with > the > struct and/or ctypes module will help. > > What you essentially need to code is a C-extension that will allow you > to directly access memory. Wrap that either in an extension or > using ctypes. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list Thanks for your information. Are you able to tell me where or how to get or make this trivial C extension, please? Regards Gabriel From abhingar at bellsouth.net Mon Jul 9 03:14:54 2007 From: abhingar at bellsouth.net (Atul Bhingarde) Date: Mon, 9 Jul 2007 03:14:54 -0400 Subject: highly einteractive editor for python Message-ID: Does anybody know an editor that facilitates, interactive python development. Where GUI etc developed will be possible to see in real time mode. Thanks Atul From see.signature at no.spam Mon Jul 30 10:46:35 2007 From: see.signature at no.spam (Eric Brunel) Date: Mon, 30 Jul 2007 16:46:35 +0200 Subject: Making Gridded Widgets Expandable References: <1185803688.860152.54210@x40g2000prg.googlegroups.com> Message-ID: On Mon, 30 Jul 2007 15:59:21 +0200, Jim wrote: > Hi, > I'm looking at page 548 of Programming Python (3rd Edition) by Mark > Lutz. > The following GUI script works with no problem, i.e., the rows and > columns expand: > ================================================================= > # Gridded Widgets Expandable page 548 > > from Tkinter import * > colors = ["red", "white", "blue"] > > def gridbox(root): > Label(root, text = 'Grid').grid(columnspan = 2) > r = 1 > for c in colors: > l = Label(root, text=c, relief=RIDGE, width=25) > e = Entry(root, bg=c, relief=SUNKEN, width=50) > l.grid(row=r, column=0, sticky=NSEW) > e.grid(row=r, column=1, sticky=NSEW) > root.rowconfigure(r, weight=1) > r += 1 > root.columnconfigure(0, weight=1) > root.columnconfigure(1, weight=1) > > root = Tk() > gridbox(Toplevel(root)) > Button(root, text="Quit", command=root.quit).grid() > mainloop() > ================================================================= > However, the following GUI script using class does not expand rows and > columns: > ================================================================= > # Gridded Widgets Expandable 2 > > from Tkinter import * > colors = ["red", "white", "blue"] > > class GUI(Frame): > def __init__(self,master): > Frame.__init__(self,master) > self.grid() > self.gridbox() > > def gridbox(self): > Label(self, text = 'Grid').grid(columnspan = 2) > r = 1 > for c in colors: > l = Label(self, text=c, relief=RIDGE, width=25) > e = Entry(self, bg=c, relief=SUNKEN, width=50) > l.grid(row=r, column=0, sticky=NSEW) > e.grid(row=r, column=1, sticky=NSEW) > self.rowconfigure(r, weight=1) > r += 1 > self.columnconfigure(0, weight=1) > self.columnconfigure(1, weight=1) > > root = Tk() > root.title("Gridded Widgets Expandable") > app = GUI(root) > Button(root, text="Quit", command=root.quit).grid() > root.mainloop() > ================================================================= > What am I missing? Hint: when you get this kind of problem, the problem is usually that an intermedaite Frame does not expand as it does. Since you have only one Frame here (your GUI instance), you should already have the solution. If you don't, or in case you get this kind of problem later with a more complex layout, adding a visible border on all Frame's usually helps. Here, for example, you can't do: Frame.__init__(self,master, border=2, bg='green') in GUI.__init__, and this will definitely show that the Frame does not resize itself when you resize the window. So the solution is clear: you should add a sticky option to your self.grid in GUI.__init__ and the corresponding (row|column)_configure(..., weight=1) on the window. BTW, why do you create a sub-class of Frame (yes: this is a trick question)? HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From jjl at pobox.com Fri Jul 6 15:10:38 2007 From: jjl at pobox.com (John J. Lee) Date: Fri, 06 Jul 2007 19:10:38 GMT Subject: IDEs for COM scripting: C# v. Python v. Iron Python v. JPython References: <468c844b$0$27401$ba4acef3@news.orange.fr> Message-ID: <87sl81s5zl.fsf@pobox.com> "M?ta-MCI" writes: [...] > And, all COM-servers builds with Python are dynamic-COM-server. Not true. Look for "comtypes" on this page: http://python.net/crew/theller/ctypes/ [...] > about Iron Python: is there a good IDE for it that has a typing assist? MS calls this "typing assist" feature IntelliSense: http://msdn.microsoft.com//msdnmag/issues/06/10/clrinsideout/default.aspx """ The Visual Studio SDK ships with a Visual Studio Integration sample of IronPython. This features IronPython projects to be created, syntax coloring, debugging, and IntelliSense? in Python files and the IronPython console. This is another example of the benefits of being a full-fledged .NET citizen: Visual Studio support! """ But things are changing very quickly with IronPython ATM. If you want to do anything with IronPython ATM, you'd be mad not to be subscribed to the IronPython mailing list. Try reading recent messages there, and asking there if still in doubt, what the current situation is (may *well* have changed since that article, and in particular you're very likely to need just the right versions of everything for this to work -- not necessarily the latest versions). John From willmaier at ml1.net Thu Jul 19 05:35:56 2007 From: willmaier at ml1.net (Will Maier) Date: Thu, 19 Jul 2007 04:35:56 -0500 Subject: Log Memory Usage Message-ID: <20070719093556.GO12728@lass.lfod.us> On Thu, Jul 19, 2007 at 09:52:36AM +0100, Robert Rawlins - Think Blue wrote: > I have a scheduled event which occurs every minute, i just need a > code solution to give me the systems current memory consumptions > details, is there perhaps something in the os module? I don't know of anything in the standard library that does this sort of thing. Instead, you'll probably need to rely on your system's tools. sysstat is available on Linux and provides the sar(1) command for examining logs of various system attributes. The tool to use depends on the system you're running. -- [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] From NuclearOnslaught at gmail.com Wed Jul 25 14:25:18 2007 From: NuclearOnslaught at gmail.com (Aneesh Goel) Date: Wed, 25 Jul 2007 11:25:18 -0700 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <1185384793.577650.256310@d55g2000hsg.googlegroups.com> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <1185379218.286977.124040@19g2000hsx.googlegroups.com> <1185384306.104549.287510@19g2000hsx.googlegroups.com> <1185384793.577650.256310@d55g2000hsg.googlegroups.com> Message-ID: <1185387918.702268.54360@l70g2000hse.googlegroups.com> On Jul 25, 10:33 am, Jeff wrote: > def flatten(obj): > if type(obj) not in (list, tuple, str): > raise TypeError("String, list, or tuple expected in > flatten().") > if len(obj) == 1: > if type(obj[0]) in (tuple, list): > return flatten(obj[0]) > else: > return [obj[0]] > else: > return [obj[0]] + flatten(obj[1:]) This seems to work fine only if the last object is the only one with the tuple or list. For example: >>> y = [(1,2),3,4] >>> y [(1, 2), 3, 4] >>> print flatten(y) [(1, 2), 3, 4] if the last line is changed to return flatten([obj[0]]) + flatten(obj[1:]) then it will unpack tuples/lists anywhere in the main collection being flattened: >>> y [(1, 2), 3, 4] >>> flatten(y) [1, 2, 3, 4] >>> z = [1,(2,3),4] >>> flatten(z) [1, 2, 3, 4] >>> x [1, 2, (3, 4)] >>> flatten(x) [1, 2, 3, 4] >>> k = [(1,2),(3,4)] >>> flatten(k) [1, 2, 3, 4] From aleax at mac.com Mon Jul 16 01:28:08 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 15 Jul 2007 22:28:08 -0700 Subject: Trying to choose between python and java References: <1184363375.352036@smirk> Message-ID: <1i1bcty.j0nnz4hkz078N%aleax@mac.com> James T. Dennis wrote: ... > You can start writing all your code now as: print() --- calling > the statement as if it were a function. Then you're future Python ...except that your output format will thereby become disgusting...: >>> name = 'Alex' >>> print 'Hello', name, 'and welcome to my program!' Hello Alex and welcome to my program! >>> print('Hello', name, 'and welcome to my program!') ('Hello', 'Alex', 'and welcome to my program!') In Python 2.*, the parentheses will make a tuple, and so you'll get an output full of parentheses, quotes and commas. I think it's pretty bad advice to give a newbie, to make his output as ugly as this. Alex From goon12 at gmail.com Wed Jul 18 08:44:26 2007 From: goon12 at gmail.com (Joe Riopel) Date: Wed, 18 Jul 2007 08:44:26 -0400 Subject: Copy List In-Reply-To: <-29831789359750479@unknownmsgid> References: <-29831789359750479@unknownmsgid> Message-ID: <6a2ccd190707180544k4909ad3enc6a962917a26f43d@mail.gmail.com> On 7/18/07, Robert Rawlins - Think Blue wrote: > What's the best way to create a copy of a list? I am pretty new to python but this works: >>> list_one = [0,1,2,3,4,5,6,7,8,9] >>> list_two = [i for i in list_one] >>> print list_two [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> From duncan.booth at invalid.invalid Tue Jul 24 15:28:20 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Jul 2007 19:28:20 GMT Subject: Good String Tokenizer References: <1185304914.344369.275770@q75g2000hsh.googlegroups.com> Message-ID: JamesHoward wrote: > I have searched the board what board? I don't see any boards here. > > And my splitting points are comma, and exclamation point then I would > expect to get back. > > ["Hello", ",", " World", "!", " How are you?"] > > Does anyone know of a tokenizer that will allow for this sort of use? > >>> import re >>> re.split("([!,])", "Hello, World! How are you?") ['Hello', ',', ' World', '!', ' How are you?'] From jeff at jmcneil.net Thu Jul 5 15:37:49 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 5 Jul 2007 15:37:49 -0400 Subject: SMTP server w/o using Twisted framework In-Reply-To: <1183661809.613856.312100@57g2000hsv.googlegroups.com> References: <1183659790.338100.199900@g4g2000hsf.googlegroups.com> <1183661809.613856.312100@57g2000hsv.googlegroups.com> Message-ID: <82d28c40707051237n950019al652cfdc4d10d07c4@mail.gmail.com> Inline... On 7/5/07, _spitFIRE wrote: > On Jul 5, 1:34 pm, "Jeff McNeil" wrote: > > If you just want to send mail, you should be able to use the standard > > smtplib module (http://docs.python.org/lib/module-smtplib.html). If > > your recipients are on the Internet, you would need to handle MX > > resolution yourself. > > > > How complicated is to handle the MX resolution by myself? I'm sorry > that I don't have a clue regarding that. Any pointers would be greatly > appreciated. You could try pyDNS (http://pydns.sourceforge.net). You should simply be able to call the 'DNS.mxlookup' function. The other option would be twisted.names... > > > I know you said you want to avoid a relay server, but it's probably > > the best bet unless you control the SMTP infrastructure or are simply > > sending messages locally. > > The problem is that with the scenario I'm faced with, I don't have any > reliable SMTP server that I can use. Hence, I though I will spawn my > own light-weight SMTP server that can send mails to the people I want, > on the Internet. But, from what you are saying it seems, it might not > be that light weight after all! What about simply running an SMTP server on the machine running your application? Is that a possible approach? > > > Otherwise, you'll probably need to also > > implement queuing and retry logic (depending on your requirements). > > Isn't there a library module that can help me implement all this? Not that I know of. The protocol is standard, the queuing and retry logic, not so much. Someone else may know more than I, though. > > > There are also some warning lights that may go off and flag your mail > > as spam if you're using a method like that... > > > > -Jeff > > Would you please fill me in with some pointers as to why my mail might > get flagged as spam? Would it be considered spam even if I've a valid > from address, and a proper message/subject? Does the spam filter also > rely on the sending server's DNS etc because of which you say it might > get flagged as spam? > http://mtamark.space.net/draft-stumpf-dns-mtamark-04.html http://en.wikipedia.org/wiki/Sender_Policy_Framework > -- > http://mail.python.org/mailman/listinfo/python-list > From jstroud at mbi.ucla.edu Thu Jul 19 18:47:27 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 19 Jul 2007 15:47:27 -0700 Subject: class C: vs class C(object): In-Reply-To: References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> Message-ID: Aahz wrote: > In article , > Steven D'Aprano wrote: > >>It isn't wrong to use the old style, but it is deprecated, [...] > > > Really? Can you point to some official documentation for this? AFAIK, > new-style classes still have not been integrated into the standard > documentation. Maybe I missed something, though. > > Note very carefully that "going away eventually" is *not* the same as > deprecation. How about "broke" instead of "deprecated": >>> class Old: ... def __init__(self): ... self._value = 'broke' ... value = property(lambda self: self._value) ... >>> >>> class New(object): ... def __init__(self): ... self._value = 'works' ... value = property(lambda self: self._value) ... >>> broke = Old() >>> broke.value 'broke' >>> broke.value = 'still broke' >>> broke.value 'still broke' >>> >>> works = New() >>> works.value 'works' >>> works.value = 'expected result of assignment here' Traceback (most recent call last): File "", line 1, in AttributeError: can't set attribute James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From boris.smirnov at gmail.com Thu Jul 26 03:42:14 2007 From: boris.smirnov at gmail.com (boriq) Date: Thu, 26 Jul 2007 07:42:14 -0000 Subject: compiling sip on vista Message-ID: <1185435734.855452.30640@r34g2000hsd.googlegroups.com> Hi, I'm trying to compile sip 4.6 on windows vista. I have Python 2.5 installed in c:\Python25. I have Qt 4.3.0 installed in c:\Qt\4.3.0 together with MinGW in c: \MinGW. I have environment variable PATH set to c:\Qt\4.3.0\bin;c:\MinGW\bin And here is what I did: C:\sip-4.6>configure.py -p win32-g++ This is SIP 4.6 for Python 2.5 on win32. The SIP code generator will be installed in C:\Python25. The SIP module will be installed in C:\Python25\Lib\site-packages. The SIP header file will be installed in C:\Python25\include. The default directory to install .sip files in is C:\Python25\sip. The platform/compiler configuration is win32-g++. Creating sipconfig.py? Creating top level Makefile? Creating sip code generator Makefile? Creating sip module Makefile? C:\sip-4.6>make makefile:29: warning: overriding commands for target `.c.o' makefile:26: warning: ignoring old commands for target `.c.o' mingw32-make[1]: Entering directory `C:/sip-4.6/sipgen' gcc -c -O2 -w -DUNICODE -DQT_LARGEFILE_SUPPORT -I. -o main.o main.c gcc: installation problem, cannot exec `cc1?: No such file or directory mingw32-make[1]: *** [main.o] Error 1 mingw32-make[1]: Leaving directory `C:/sip-4.6/sipgen' mingw32-make: *** [all] Error 2 C:\sip-4.6> Could anybody tell me what's wrong here and what should I make to correct that? Thanks in advance. Rg, Boris From benruza at gmail.com Mon Jul 2 15:53:32 2007 From: benruza at gmail.com (Bruza) Date: Mon, 02 Jul 2007 19:53:32 -0000 Subject: Bug in Python class static variable? In-Reply-To: References: <1183372758.251109.34550@z28g2000prd.googlegroups.com> Message-ID: <1183406012.465981.35700@z28g2000prd.googlegroups.com> On Jul 2, 3:52 am, Duncan Booth wrote: > Bruza wrote: > > I am trying to define a class static variable. But the value of the > > static variable seems to be only defined inside the file that the > > class is declared. See the code below. When I run "python w.py", I > > got: > > When you run "python w.py" the *script* w.py is loaded as the module > __main__. Importing a module called 'w' creates a new module which is > unrelated to __main__. If you want access to variables defined in the main > script then you need to import __main__. > > Don't use 'from module import *': > > The import statements are executed when the interpreter reaches them in the > source. Even if you fix your code to import from __main__, the values you > try to import from __main__ won't exist when the import statement executes: > the first 'from a import *' will load and execute all of module 'a', but > when that executes 'from __main__ import *' it just imports names defined > in the main script *before* a was imported. > > In general, don't try to do this: put all your classes into modules and > just put minimal startup code into a script. Duncan, Thanks for replying. However, I am still confused... Even if I put "from __main__ import *" in both "a.py" and "w.py", I still got the same results. So, how should I re-structure my program to make the class static variable works??? Thanks, Ben From star.public at gmail.com Mon Jul 30 16:16:57 2007 From: star.public at gmail.com (star.public at gmail.com) Date: Mon, 30 Jul 2007 20:16:57 -0000 Subject: How to write GUI and event separately in wxPython?? In-Reply-To: References: <1185777254.925902.204500@z28g2000prd.googlegroups.com> <5h5kmiF3hmufcU3@mid.uni-berlin.de> <5h5upbF3hmufcU5@mid.uni-berlin.de> Message-ID: <1185826617.556482.23530@g4g2000hsf.googlegroups.com> On Jul 30, 11:42 am, "Chris Mellon" wrote: > > > On Mon, 30 Jul 2007 06:32:55 -0400, Steve Holden wrote: > > > >> >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)] > > >> True > nitpick: list(xrange(42)) == list(xrange(42)) is slightly more concise > than the list comp.. Not that it has anything to do with this topic anymore, but I find the list comp a bit clearer for expressing the thought 'each element in one is the same as the coresponding element in the other, or: the sequences are identical' -- the list() version would proabably have had me going 'huh?' even longer ^_^. -- [star for star in weaver] From mcshutterbug at dwx.com Thu Jul 19 23:39:05 2007 From: mcshutterbug at dwx.com (Marcus) Date: Thu, 19 Jul 2007 22:39:05 -0500 Subject: Using eggs or py2exe to distribute apps Message-ID: Hi, I'm to the stage where I need to deploy the app I built with wxPython. I've been able to successfully build it w/py2exe into a binary (about 10MB size in total). What I'd like to do is create an automatic updater, so that I can have users download updated versions of my *application code* without having to have them redownload everything (the interpreter, etc) via a complete redownload (I want to package some things as "components"). Eggs seem like an ideal solution, but I haven't had any luck using them in conjunction with py2exe. It would seem that the most effective solution would be to package a python interpreter (with wxPython, etc already included) into the distributed app's directory and not use py2exe at all; however, since everything would be included in the distribution, it would seem that the full python distro would be huge (50MB at least), which defeats the purpose of wanting to build the app into "components". Worst-case scenario would be to have them redownload the 10MB update each time, but that's less than ideal, since the audience for my program would have more frequent/less substantial updates over time, rather than big updates all at once. Any guidance or suggestions are very much appreciated. Marcus From arnoreg at gmail.com Tue Jul 10 09:24:55 2007 From: arnoreg at gmail.com (Arno Stienen) Date: Tue, 10 Jul 2007 15:24:55 +0200 Subject: xmlrpclib hangs execution In-Reply-To: <1184068392.683491.48920@22g2000hsm.googlegroups.com> References: <45AC0631.8080601@ctw.utwente.nl><465A9DC7.2010708@gmail.com> <465d9040$0$326$e4fe514c@news.xs4all.nl> <1182162228.246643.135210@u2g2000hsc.googlegroups.com> <1184068392.683491.48920@22g2000hsm.googlegroups.com> Message-ID: <469388A7.6020909@gmail.com> Thanks! I'll try that one too to find the easiest solution. For portability, it is easier to use a new transport class and not have to patch files of the Python distribution. Using a similar strategy, I used this class just before I read about your patch, which works fine too: http://mail.python.org/pipermail/python-list/2004-April/256360.html Could you comment on the difference between this class and yours? You might want to include on your site how to use the class in a reallife example, i.e. like the other class does: import httplib, xmlrpclib s = xmlrpclib.ServerProxy('http://SOMEURL', transport=PersistTransport()) I agree with you on xmlrpclib needed an upgrade, but in the past could not find anybody 'responsible' and knowledgeable enough to do this. Although I do feel responsible for open source development, I do not have the python knowledge to propose a fix myself! Bye, Arno. itkovian wrote: > Arno, > >> Your patches solves the problem too. Thanks! >> >> One thing: if I use the unpatched xmlrpclib.py, the printed output of >> xml calls look like: >> >> {'state': 0, 'str': 'Info_RT'} >> >> But if I use your patch, they look like: >> >> state0strInfo_RT >> >> I prefer the former, as it is easier to extract the info. Why did this >> change with your patch? > > I've no idea, I'll look into this as soon as possible. Thanks for > letting me know. > > I want to point you to another possible solution, which is using a > derived > transport class. I've posted this on my blog, see > > http://www.itkovian.net/base/transport-class-pythons-xml-rpc-lib > > I'm not sure if this might solve the problem you pointed out. > > -- Andy > From B.Ogryczak at gmail.com Thu Jul 12 10:20:11 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: Thu, 12 Jul 2007 14:20:11 -0000 Subject: lists and dictionaries In-Reply-To: <1184208542.948772.50700@w3g2000hsg.googlegroups.com> References: <1184184582.330491.326600@e9g2000prf.googlegroups.com> <1184208542.948772.50700@w3g2000hsg.googlegroups.com> Message-ID: <1184250011.187346.70470@r34g2000hsd.googlegroups.com> On 12 jul, 04:49, anethema wrote: > > li = [ {'index': 0, 'transport': 'udp', 'service_domain': > > 'dp0.example.com'}, > > {'index': 1, 'transport': 'udp', 'service_domain': > > 'dp1.example.com'}, > > {'index': 0, 'transport': 'tcp', 'service_domain': > > 'dp0.example.com'}, > > {'index': 1, 'transport': 'tcp', 'service_domain': > > 'dp1.example.com'}] > > I like this solution: > > [{ 'transports' : [d['transport'] for d in li if > d['service_domain'] == dom], > 'service_domain': dom, > } for dom in set(d2['service_domain'] for d2 in li)] > > merely because it takes one line. Humorously enough, it appears to be > twice as efficient, Correct me if I?m wrong, that is a O(n**2) solution, to O(n) problem. From mensanator at aol.com Wed Jul 11 16:34:04 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Wed, 11 Jul 2007 13:34:04 -0700 Subject: binascii.unhexlify ... not clear about usage, and output In-Reply-To: <5fkmdeF3cu82eU3@mid.uni-berlin.de> References: <1180511251.625790.280260@h2g2000hsg.googlegroups.com> <1184142108.846958.189080@k79g2000hse.googlegroups.com> <1184175983.898310.321630@q75g2000hsh.googlegroups.com> <5fkmdeF3cu82eU3@mid.uni-berlin.de> Message-ID: <1184186044.390255.20310@k79g2000hse.googlegroups.com> On Jul 11, 1:38 pm, Marc 'BlackJack' Rintsch wrote: > On Wed, 11 Jul 2007 10:46:23 -0700, mensana... at aol.com wrote: > > You can with gmpy: > > >>>> import gmpy > >>>> x = 0x0164 > >>>> s = gmpy.digits(x,2) # convert to base 2 > >>>> y = '0'*(16-len(s)) + s # pad to 16 bits > >>>> y > > '0000000101100100' > > For the padding I'd use the `zfill()` method. > > In [15]: a = 0x0164 > > In [16]: gmpy.digits(a, 2).zfill(16) > Out[16]: '0000000101100100' > > Ciao, > Marc 'BlackJack' Rintsch Damn, I didn't know you could do that. If only there was a built-in base 2 conversion. From zyzhu2000 at gmail.com Wed Jul 25 10:50:18 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 25 Jul 2007 14:50:18 -0000 Subject: Flatten a list/tuple and Call a function with tuples Message-ID: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> Hi, I am wondering how do I 'flatten' a list or a tuple? For example, I'd like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4]. Another question is how do I pass a tuple or list of all the aurgements of a function to the function. For example, I have all the arguments of a function in a tuple a=(1,2,3). Then I want to pass each item in the tuple to a function f so that I make a function call f(1,2,3). In perl it is a given, but in python, I haven't figured out a way to do it. (Maybe apply? but it is deprecated?) Thanks, cg From NuclearOnslaught at gmail.com Tue Jul 24 13:32:27 2007 From: NuclearOnslaught at gmail.com (NuclearOnslaught at gmail.com) Date: Tue, 24 Jul 2007 17:32:27 -0000 Subject: Memory Logging Message-ID: <1185298347.081987.126360@m3g2000hsh.googlegroups.com> Hey all, I'm running some data analysis scripts that, due to the input file size, tend to be quite memory intensive. I've been reading up on Python's memory allocation (I'm using 2.4 and am locked into it, so I don't have the new fixes in 2.5) but because of the nature of its looping I don't think its losing much memory because of some of the deallocation issues - it will reuse the ints and lists that Python is retaining references to. Because of this I suspect there are other memory leaks, and I'm trying to find out where; some method through which I could monitor memory usage as the script runs would be extremely helpful, even if it just prints the amount of memory python is using every time I call a particular command. I've tried using the profile module; the output didn't seem particularly helpful in terms of memory usage. In case OS-specific commands are required, all the machines it will run on are using Windows XP. Thanks, -- Aneesh Goel From ahlongxp at gmail.com Sun Jul 8 00:53:59 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Sat, 07 Jul 2007 21:53:59 -0700 Subject: socket: connection reset by server before client gets response In-Reply-To: <46902a45$0$331$e4fe514c@news.xs4all.nl> References: <1183819907.249945.239700@o11g2000prd.googlegroups.com> <1183827514.109496.252870@d30g2000prg.googlegroups.com> <46902a45$0$331$e4fe514c@news.xs4all.nl> Message-ID: <1183870439.595652.305590@z28g2000prd.googlegroups.com> > Post the code. ok. here is the code: # Echo server program import socket HOST = '' # Symbolic name meaning the local host PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) s.listen(1) conn, addr = s.accept() print 'Connected by', addr conn.settimeout(1) toread = 99 retrytime = 0 reads = 0 while reads < toread and retrytime < 10: try: data = conn.recv(min(32,toread-reads)) if not data: continue print data reads += len(data) except: retrytime += 1 print "timeout %d" % retrytime continue if reads == toread: conn.send("OK") else: conn.send("NOT OK") conn.close() ****************I'm the separate line********************************************* # Echo client program import socket HOST = 'localhost' # The remote host PORT = 50007 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) for i in range(12): print "time %d" % i s.send('0123456789') #data = s.recv(1024) #print "data %d" %i, data #s.shutdown(socket.SHUT_WR)#no more write data=s.recv(1024) s.close() print 'Received', repr(data) client is supposed to get the response, either "OK" or "NOT OK". but the fact is, client gets "Connection reset by peer" (as shown below) about one in fifth. ---------------------------------- Traceback (most recent call last): File "c.py", line 10, in s.send('0123456789') socket.error: (104, 'Connection reset by peer') ---------------------------------- anyway, server is doing well all the time. any comments on the design or implementation will be greatly appreciated. -- ahlongxp Software College,Northeastern University,China ahlongxp at gmail.com http://www.herofit.cn From duncan.booth at invalid.invalid Wed Jul 18 03:39:39 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Jul 2007 07:39:39 GMT Subject: In a dynamic language, why % operator asks user for type info? References: <1184631007.920803.147790@j4g2000prf.googlegroups.com> <1184631512.329438.90050@i13g2000prf.googlegroups.com> <1184632433.980754.189240@d30g2000prg.googlegroups.com> <1184634387.15828.47.camel@blackwidow.nbk> <1184725539.689107.314450@g12g2000prg.googlegroups.com> Message-ID: Asun Friere wrote: > On Jul 17, 5:38 pm, Duncan Booth wrote: > >> indeed anything which has an __int__ method may be >> passed to the %d formatter: > > Anything?! Sorry to be persnickety here, but what about this: > > class C : > def __int__ (self) : pass > > '%d' % C() > __int__ is a reserved method name so it is reasonable to assume that any such method will act as documented: "Should return a value of the appropriate type." If you choose to ignore the documentation then expect exceptions to be thrown. > or this: > > def foo (val) : return val > foo.__int__ = lambda x=42 : int(x) > > '%d' % foo('spam') > I don't see any methods named '__int__' there, just a function assigned to an attribute. (Yes, I know that isn't the problem, assigning a function to an __int__ attribute works for other types, but if you can be silly so can I.) From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jul 10 17:42:01 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 10 Jul 2007 23:42:01 +0200 Subject: bool behavior in Python 3000? References: Message-ID: <5ficp9F3cram2U2@mid.individual.net> Alan G Isaac wrote: > My preference would be for the arithmetic operations *,+,- > to be given the standard interpretation for a two element > boolean algebra: > http://en.wikipedia.org/wiki/Two-element_Boolean_algebra >>> [bool(True+True), bool(True+False)] [True, True] Works for me, or did I misunderstand you? If you don't want explicitly to write bool, you could define your own True and False classes. Regards, Bj?rn -- BOFH excuse #184: loop found in loop in redundant loopback From ahlongxp at gmail.com Mon Jul 9 04:42:11 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Mon, 09 Jul 2007 08:42:11 -0000 Subject: socket.makefile() buggy? In-Reply-To: References: <1183892789.434028.15370@x35g2000prf.googlegroups.com> Message-ID: <1183970531.241008.295940@z28g2000prd.googlegroups.com> On Jul 8, 9:54 pm, Steve Holden wrote: > That's a pretty pejorative subject line for someone who's been > programming Python [guessing by the date of your first post] for about a > month. > I have to admit it that I'm quite a newbie programmer. > Perhaps "Incomprehensible behavior from socket.makefile()", or "I have > written a buggy network application"? That would at least show that you > are considering the possibility you yourself are the cause of the > problem ;-) > Thanks. I'll be more careful about my words. but I did show some possibility myself is the cause of the problem. Is there any chance you missed the "?" and "guess" at the same time. > Python has been around for a long time, so you should ask yourself how > likely it is that you would be the first to discover such a fundamental > flaw? very low but not zero. Miracle happens. >I'd be very surprised if someone doesn't point you at an article > on "how to ask smart questions", but I will content myself with that > oblique reference. > > The big problem is that, I didn't know such a person like you before. It's my misfortune. > The big problem here seems to be that your server is closing the socket > after reading 99 bytes, but the client is actually sending 120. If you > change the "99" in the server to "120" you will see that the client > works when it uses the makefile().read(). I can't be bothered to debug > the exact reason why the 21 bytes of buffered data doesn't cause a > problem with the recv() version, but I wouldn't regard the error you are > getting as a bug in Python, rather as a bug in your application. > I don't know the underlying details of networking. But with recv() version I can get things done as expected while makefile() version can't. I guess it's not that unreasonable to make a guess like I did. > The underlying cause of all this appears to be your failure to > understand that network protocols should ideally allow the endpoints to > determine when a complete message has been transmitted, and to consume > all transmitted data. > > You can't just ignore some or all of a client request and expect it not > to cause problems. Back to the problem, I make it working by adding a sleep(0.5) just before the server closes the connection. Actually this is Hendrik van Rooyen's idea. And luckily I got a another lesson http://groups.google.com/group/comp.lang.python/browse_thread/thread/9c5ad2608f4c80d5/4302772dfe27d8f1#4302772dfe27d8f1 >If you look at some of the better-known TCP-based > application protocols you will see they take pains to ensure that > clients and servers can deterministically parse each others' messages. > I found something useful in RFC2616--Hypertext Transfer Protocol -- HTTP/1.1. [PAGE49] - If an origin server receives a request that does not include an Expect request-header field with the "100-continue" expectation, the request includes a request body, and the server responds with a final status code before reading the entire request body from the transport connection, then the server SHOULD NOT close the transport connection until it has read the entire request, or until the client closes the connection. Otherwise, the client might not reliably receive the response message. However, this requirement is not be construed as preventing a server from defending itself against denial-of-service attacks, or from badly broken client implementations. "Otherwise, the client might not reliably receive the response message". My problem seems fixed. But it's not "relialbe" though it's working pretty good under windows 2k, windowsxp, and linux. I may reconsider my design and willprobably try dividing request with body into two steps like HTTP does. > In summary, a better protocol design will cause you rather less grief > and a little more humility will result in less acidity from crabby old > geeks like me. > I do appreciate your response. I mean 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 ------------- And last but not least, I' here to be helped and help as long as I can. But as you noticed I'm not very good at expressing myself in English. I didn't mean to offense anyone but I might seem to be rude or offensive. I hope you can understand. -- ahlongxp Software College,Northeastern University,China ahlongxp at gmail.com http://www.herofit.cn From robinsiebler at gmail.com Fri Jul 20 15:43:33 2007 From: robinsiebler at gmail.com (robinsiebler at gmail.com) Date: Fri, 20 Jul 2007 12:43:33 -0700 Subject: Weird errors when trying to access a dictionary key In-Reply-To: <1184959634.927653.158530@i13g2000prf.googlegroups.com> References: <1184956573.702959.96400@d30g2000prg.googlegroups.com> <1184959634.927653.158530@i13g2000prf.googlegroups.com> Message-ID: <1184960613.930193.143150@i38g2000prf.googlegroups.com> > You are converting the dictionary to a list on this line, and lists do > not have keys> rpt_file.writelines('\t' + [song].keys() \ > How am I converting it to a list? > Note the first line has braces, not brackets so it is a > dictionary. Braces? What 1st line are you talking about? From carsten at uniqsys.com Sat Jul 7 15:34:09 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 07 Jul 2007 15:34:09 -0400 Subject: Creating logged functions using decorators In-Reply-To: <1183834783.235867.146840@n2g2000hse.googlegroups.com> References: <1183834783.235867.146840@n2g2000hse.googlegroups.com> Message-ID: <1183836849.3122.3.camel@localhost.localdomain> On Sat, 2007-07-07 at 11:59 -0700, Paul McGuire wrote: > On Jul 7, 1:47 pm, "Nathan Harmston" > wrote: > > Hi, > > > > I m thinking about writing some code which logs the input and output > > of a function/script and stores it in a database using sqlalchemy > > (although I havent started on this yet). I want to do this via a > > decorator ( I think this is the best way ). > > [...] > > I can access the arguments passed to the "logged" function, but is > > there anyway I can capture the output of the function i.e. 10. > > > > Many Thanks in advance, > > > > Nathan > > Yes. Capture the output of the function to a variable and log it > before you return it. > > def log(fn): > def newfn(*args): > print datetime.date.today() > print __file__ > print fn.__name__ > print args > returnValue = fn(*args) > print returnValue > return What Paul means here is, of course, "return returnValue", not a bare return. -- Carsten Haese http://informixdb.sourceforge.net From ndbecker2 at gmail.com Fri Jul 27 18:49:17 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 27 Jul 2007 18:49:17 -0400 Subject: problem with change to exceptions Message-ID: import exceptions class nothing (exceptions.Exception): def __init__ (self, args=None): self.args = args if __name__ == "__main__": raise nothing Traceback (most recent call last): File "", line 1, in File "/usr/tmp/python-3143hDH", line 5, in __init__ self.args = args TypeError: 'NoneType' object is not iterable I'll have to say, I don't understand this error. From star.public at gmail.com Thu Jul 12 21:06:14 2007 From: star.public at gmail.com (star.public at gmail.com) Date: Thu, 12 Jul 2007 18:06:14 -0700 Subject: New guy help with setup In-Reply-To: <1184277359.397821.265290@m3g2000hsh.googlegroups.com> References: <1184275051.504507.116080@57g2000hsv.googlegroups.com> <1184275783.250640.327630@g4g2000hsf.googlegroups.com> <1184277359.397821.265290@m3g2000hsh.googlegroups.com> Message-ID: <1184288774.758733.122570@q75g2000hsh.googlegroups.com> On Jul 12, 5:55 pm, meg99 wrote: > got the >>> prompt Type fun things at the >>> prompt, such as: >>> print 'Some Obligatroy Greeting Like "Hello World."' or >>> [x*5 for x in [1,2,3,4,5]] or >>> import os >>> os.listdir('.') >>> [os.isdir(x) for x in os.listdir('.')] Also, you should now be able to make .py files in a text editor and run them by double-clicking them. (Hint: If you're just doing print statements and such, stick a raw_input() at the end of the file so that the window stays around when you double-click it ...) But all in all, the .configrue[1] stuff is only for unix-like systems and stuff like cygwin, windows dosn't usally need to worry about it. [1] I saw this typo, then decided to leave it as some kind of scary obscure bad zork pun thing. -- Weaver From mensanator at aol.com Mon Jul 16 19:08:13 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 16 Jul 2007 16:08:13 -0700 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> <1184351416.166930.290710@k79g2000hse.googlegroups.com> <1184362323.476796.22570@w3g2000hsg.googlegroups.com> Message-ID: <1184627293.763822.255220@g4g2000hsf.googlegroups.com> On Jul 15, 4:37 pm, Steve Holden wrote: > Wayne Brehaut wrote: > > On Fri, 13 Jul 2007 14:32:03 -0700, "mensana... at aol.com" > [...] > > But I digress (but only because provoked!)... > > >>> [for purposes of this argument, at least] > > > This statement is the informal equivalent to saying "Define a base-1 > > number system as...", as I noted above. If you'd noted this, and > > understood it, or were willing to accept it whether or not you > > understood it, you'd have saved us both some bother--but me more than > > you I guess, so maybe you were just trolling? > > wwway to beat a response to a pulp. Crackpot math is the way to beat a response to a pulp? And why does the response need to be beaten to a pulp? Isn't the purpose of comp.lang.python to promote knowledge, not ignorance? When someone posts x = [] for i in range(255): x.append(i) are you being a troll when you point out this could be done better using list comprehension? > Sometimes it's easier and better for > your blood pressure just to let someone else have the last word, however > ill-informed What was ill-informed? That there's no base 1? >>> x = int('1111',1) Traceback (most recent call last): File "", line 1, in x = int('1111',1) ValueError: int() base must be >= 2 and <= 36 Or that Roman numerals aren't equivalent to tallying? > or hostile. What hostility? > > regards > Steve From deets at nospam.web.de Fri Jul 20 03:18:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 20 Jul 2007 09:18:16 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7x1wf8kc6l.fsf@ruckus.brouhaha.com> References: <468565a0$0$3686$426a74cc@news.free.fr> <7xvecumrte.fsf@ruckus.brouhaha.com> <1i13w96.kyyobph71qxrN%aleax@mac.com> <7xwsx63we6.fsf@ruckus.brouhaha.com> <878x9llv5x.fsf@benfinney.id.au> <5fovr8F3eglkfU1@mid.uni-berlin.de> <7x1wf8kc6l.fsf@ruckus.brouhaha.com> Message-ID: <5gb5u1F3fip9cU1@mid.uni-berlin.de> Paul Rubin schrieb: > "Diez B. Roggisch" writes: >> For example, SPARK does not support dynamic allocation of memory so >> things such as pointers and heap variables are not supported. > > Right, Spark uses a profile intended for embedded systems, so > no unpredictable gc delays etc. > >> Which is not to say that trivial code couldn't have errors, and if >> it's extremely cruical code, it's important that it hasn't errors. But >> all I can see is that you can create trustable, simple sub-systems in >> such a language. And by building upon them, you can ensure that at >> least these won't fail. > > Yes, that's the usual approach. > >> But to stick with the example: if the path-planning of the UAV that >> involves tracking a not before-known number of enemy aircrafts steers >> the UAV into the ground, no proven-not-to-fail radius calculation will >> help you. > > Whether the program uses dynamic memory allocation or not, there > either has to be some maximum number of targets that it can be > required to track, or else it's subject to out-of-memory errors. > If a maximum number is specified, then memory requirements can > be computed from that. In other words: you pre-allocate everything and can then proove what - that the program is going to be stop working? What does that buy you - where is "I'm crashed becaus I ran out of memory trying to evade the seventh mig" better than "sorry, you will be shot down because I'm not capable of processing more enemie fighters - but hey, at least I'm still here to tell you!" Sorry, but if that's supposed to make a point for static typechecking, I don't buy it. Crippling the execution model so that it fits a proving-scheme which essentially says "don't do anything complex with me" is no good. Diez From kyosohma at gmail.com Fri Jul 20 13:57:09 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 20 Jul 2007 10:57:09 -0700 Subject: Python MAPI Message-ID: <1184954229.222401.213380@k79g2000hse.googlegroups.com> Hi, I've been googling all over and can't find any good answers about this problem. I would like to create some kind of MAPI interface with Python such that when I open Microsoft Word (or another Office program) and click File, Send To, Mail Recipient it opens a program I wrote in Python and uses it to send the email rather than Outlook. The closest I've come is finding the registry key HKLM\Software\Clients \Mail which seems to control the default email client. I did figure out how to redirect mailto directives on websites to my program successfully, but this is a whole 'nother ballgame. Any suggestions are welcome. I am considering writing some VBA hooks in Office Apps in question, but would prefer to avoid that. Thanks! Mike P.S. Currently using Python 2.4, wxPython 2.8.3 (for GUI) on Windows XP Pro. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jul 30 12:02:32 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 30 Jul 2007 18:02:32 +0200 Subject: making a variable available in a function from decorator In-Reply-To: References: <5h5e3lF3hmufcU1@mid.uni-berlin.de> Message-ID: <46ae0b96$0$26111$426a74cc@news.free.fr> rkmr.em at gmail.com a ?crit : (top-post corrected) > > On 30 Jul 2007 06:17:25 GMT, Marc 'BlackJack' Rintsch wrote: >> On Sun, 29 Jul 2007 15:22:47 -0700, rkmr.em at gmail.com wrote: >> >>> I create a variable in a decorator. i want to be able to access that >>> variable in the function to be decorated. How to do this? > >> Pass it as argument to the function: >> >> def deco(func): >> eggs = 42 >> def decorated(*args, **kwargs): >> kwargs['spam'] = eggs >> func(*args, **kwargs) >> return decorated >> >> @deco >> def test(parrot, spam): >> print parrot, spam > is it possible to do this without passing it as a function argument? What's your use case, exactly ? Having a function depending on a name being set by a decorator is not exactly pythonic, and arguments are meant to pass variables to functions... From bbxx789_05ss at yahoo.com Sun Jul 1 23:51:56 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 01 Jul 2007 20:51:56 -0700 Subject: unicode In-Reply-To: <46880b1a$0$22417$9b622d9e@news.freenet.de> References: <1183267580.178435.265640@o61g2000hsh.googlegroups.com> <1183318859.305908.218960@w5g2000hsg.googlegroups.com> <46880b1a$0$22417$9b622d9e@news.freenet.de> Message-ID: <1183348316.943369.230970@q75g2000hsh.googlegroups.com> Hi, Thanks for the detailed response. On Jul 1, 2:14 pm, "Martin v. L?wis" wrote: > > 1) If you print a unicode string: > > > > a) str() calls encode(), and encode() tries to convert the unicode > > string to a regular string. encode() uses the default encoding, which > > is ascii. If encode() can't convert a character, then encode() raises > > an exception. > > Yes and no. This is what str() does, but str() isn't called. Instead, > print inspects sys.stdout.encoding, and uses that encoding to encode > the string. That, in turn, may raise an exception (in particular if > sys.stdout.encoding is "ascii" or not set). > Is that the same as print calling encode(u_str, sys.stdout.encoding) From tjreedy at udel.edu Tue Jul 24 11:34:03 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 24 Jul 2007 11:34:03 -0400 Subject: Code objects References: Message-ID: "Evan Klitzke" wrote in message news:cfb58d850707232355p5a1c7214l1486c2276389b25b at mail.gmail.com... |I was playing around with the inspect module tonight, and I have a | question about "code components". Can an object have more than one | code component? As produced by CPython, a function object has one code attribute, .func_code I think. On the other hand, you should be able to attach other code objects under different names, such as .func_code2. Such would, however, be ignored in function calls. | For example, will the following code ever create a | list whose length is greater than one? | | import inspect | | # Some code here defining an object/function foo | | components = [cc[1] for cc in inspect.getmembers(foo,\ | inspect.iscode)] Try it on such an augmented function object. tjr From stargaming at gmail.com Thu Jul 26 01:50:00 2007 From: stargaming at gmail.com (Stargaming) Date: 26 Jul 2007 05:50:00 GMT Subject: Keyword argument 'from'; invalid syntax References: Message-ID: <46a83608$0$24910$9b622d9e@news.freenet.de> On Thu, 26 Jul 2007 12:08:40 +1000, Steven D'Aprano wrote: > On Thu, 26 Jul 2007 03:33:20 +0200, Kai Kuehne wrote: > >> I have tried to prepare a dict and then passing it to the method >> afterwards: >>>>> d = {'person': 'user', 'from': vorgestern} >>>>> magnolia.bookmarks_find(d) >> : bookmarks_find() takes exactly 1 >> argument (2 given) >> >> I'm out of ideas so help is greatly appreciated! > > Try this: > > magnolia.bookmarks_find(**d) > > although I suspect that will probably raise an exception as well. > Judging by the error message, it looks like bookmarks_find() takes only > a single argument, which I imagine would be the "self" instance > automatically provided at runtime. Could be bookmarks_find(person, **other), unpacking other manually. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jul 19 12:03:26 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 19 Jul 2007 18:03:26 +0200 Subject: Itertools question: how to call a function n times? In-Reply-To: References: Message-ID: <469f8b4e$0$8399$426a74cc@news.free.fr> Matthew Wilson a ?crit : > I want to write a function that each time it gets called, it returns a > random choice of 1 to 5 words from a list of words. > > I can write this easily using for loops and random.choice(wordlist) and > random.randint(1, 5). > > But I want to know how to do this using itertools, since I don't like > manually doing stuff like: > > phrase = list() > for i in random.randint(1, 5): > > phrase.append(random.choice(wordlist)) what's wrong with: phrases = [random.choice(wordList) for i in random.randint(1, 5)] From robert.rawlins at thinkbluemedia.co.uk Tue Jul 17 05:57:29 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Tue, 17 Jul 2007 10:57:29 +0100 Subject: Dict Help In-Reply-To: <015101c7c718$e207e820$a617b860$@rawlins@thinkbluemedia.co.uk> References: <015101c7c718$e207e820$a617b860$@rawlins@thinkbluemedia.co.uk> Message-ID: <023401c7c858$e36c6ec0$aa454c40$@rawlins@thinkbluemedia.co.uk> Morning Gabriel, I'm looking for a little more advice on this dictionary/list to defaultdict/set conversion that we were talking about, there were a few things I was looking to clarify. Firstly, what is the difference between a standard dict and a default dict? Is it purely a performance issue? This dict is likely to grow pretty large and is read/written on a very regular basis so the better performing one is going to work best for me. Also, am I still able to iterate over a set in the same way I can a list? Here is an example of my add function at the moment, how can that be converted to a defaultdict/set instead of the dict/list approach? self.History = {} def addHistory(self, address, media): if address not in self.History: self.History[address] = [] self.History[address].append(media) Thanks Gabriel, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Robert Rawlins - Think Blue Sent: 15 July 2007 20:47 To: 'Gabriel Genellina'; python-list at python.org Subject: RE: Dict Help Thanks Gabriel, That all works a charm, Iteration on this isn?t important for me so the SET will work much better I think, I had read about them before but have never used them, I'm glad to see it works so simply. Thanks, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Gabriel Genellina Sent: 15 July 2007 20:33 To: python-list at python.org Subject: Re: Dict Help En Sun, 15 Jul 2007 11:39:24 -0300, Robert Rawlins escribi?: > I'm looking for some help expanding on a dictionary I've got and storing > multiple values per key and the best way to do it. I'm guessing that I > need to store a list inside the value of the dictionary, but I'm not > quite sure how that can be achieved, and also how to check for values in > that list. > Here is a brief example of what I want to be able to build: > Key Value > 00:0F:DE:A8:AB:6F > 6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg,01DBB592-F7EB-B000-7F250FD8A2CE158F. gif,533EAE0F-B211-B2D8-4C2DB662CCECFBD7.3gp > 00:17:B0:A0:E7:09 > 6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg,01DBB592-F7EB-B000-7F250FD8A2CE158F. gif > 00:1B:98:16:21:E4 > 6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg There are a few ways to do it. Just translating your own words into Python, use a dictionary with a list of values. > Now I really need to have two functions, one of which appends a value to > the list for a specified key, so I have the key and the new value as > strings, I then want to locate that key and append the list with the new > value. The simplest way: d = {} # add a pair key, value if key not in d: d[key] = [value] else: d[key].append(value) > The second function I need, is to check for the existence of a value in > the list of a particular key, again I have the key and the value and I > want to do something like: > if value in list of values for key: > do something here... # check for a key, value exists = key in d and value in d[key] > The final function that would be helpful to me would to be able to > remove a value from the list for a specific key. # remove value from key's values if key in d and value in d[key]: d[key].remove(value) > I'm not sure if a list as the value in a dict is possible, or if its the > best way to achieve this, It just made logic sense to me so thought I'd > come and get your thoughts on this. If anyone has any better suggestions It's perfectly possible as you can see. Now, depending on how many values you have, or how often do you test, you might replace the list with a set. Sets are unordered collections (you will loose the insertion order) but are better suited for a "contains" test (O(1) instead of O(n) for a list) And you might replace the dictionary with a defaultdict. The insertion would become: from collections import defaultdict d = defaultdict(set) # add a pair key, value d[key].add(value) The existence check and remove method do not change. Dicts, lists and sets are documented here: and defaultdict -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list From graemeglass at gmail.com Tue Jul 3 05:06:07 2007 From: graemeglass at gmail.com (Graeme Glass) Date: Tue, 03 Jul 2007 09:06:07 -0000 Subject: need help with win32com In-Reply-To: References: Message-ID: <1183453567.042362.140490@n2g2000hse.googlegroups.com> On Jul 2, 6:38 pm, Thomas wrote: > I want to be able to access an excel file and extract the code from > the macro that is in the file. How can I do this? > > -- > ~Thomas~ http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483742 From see at signature.invalid Thu Jul 12 13:42:07 2007 From: see at signature.invalid (Douglas Wells) Date: Thu, 12 Jul 2007 13:42:07 -0400 (EDT) Subject: asyncore and OOB data References: <1184172867.420979.215300@q75g2000hsh.googlegroups.com> Message-ID: In article , Steve Holden writes: > Douglas Wells wrote: > > > > Third, the TCP protocol, which you have selected via the SOCK_STREAM > > option doesn't support OOB at all, so there's no way that you can > > even send OOB data in the manner that you are expecting. > > > Wrong. The URGENT pointer indicates that the data begins with > out-of-band data. You are correct, however, in stating that the FTP > protocol doesn't support or implement out-of-band data transmissions. Well, first I have to admit that I just looked at the wiki article on out-of-band () and it also makes a statement that TCP urgent data is OOB. But I disagree with that interpretation. So, let me acknowledge that there are dissenting opinions, and explain my assertion in terms of the OP's problem of wanting a separate data stream (or at least that was my interpretation). First, I fully acknowledge that the concept of TCP's URGENT pointer itself is out-of-band, but I don't know of any way to associate data, in the form of an identifiable set of octets, with that concept. As supporting evidence I offer the following: - There is no way for the sender and the receiver to agree on the *start* of an urgent data set. The end point is clearly identified by the urgent pointer, but the start is time dependent and is not identified in the TCP communication stream. Thus, the sender could not express the concept of sending a particular data value, e.g. "This string", to the receiver reliably. - If receivers are highly responsive (meaning that the receiver is always able to process incoming data without having to discard any of it), there will be no difference in the behavior of two receivers, one of which properly implements the concept of the urgent pointer, and the other of which totally ignores the concept of urgency. - There appears to be no way to actually read any OOB data from a Berkeley socket API. (As I noted my system, at least, returns an error in this case.) > > Let's switch to the positive, however. What TCP does have is the > > concept of "urgent" data. Urgent data is data that the sender > > believes is so important that the receiver should discard intermediate > > data, if necessary, in order to process the urgent data -- but the > > urgent data is sent *in-band*. > > > No, technically the urgent data is out-of-band, isn't it? There is no > requirement to ditch the other data in the packet, so urgent data can be > interspersed without loss of regular in-band data if required. This is the same point that I argued above. I now acknowledge that some people think of the TCP urgent concept as OOB. I don't; but this is a matter of definition and almost certainly not an issue for coherent argument. > > In the case of FTP, the concept of urgent data is used to allow > > the user side to interrupt the data transfer, which it does by > > sending an ABOR command. The underlying problem is that the server > > might be blocked on a receive on the data connection and not > > listening for commands on the control connection. So the user > > side is required to perform some "special action" that includes > > sending urgent data, which the server can then process specially. > > This problem arises primarily in systems without either threading > > or asynchronous I/O APIs. Your use of asyncore should alleviate > > this problem. > > The thing that may be confusing you is that for whatever reason > > the designers of the Berkeley socket API (which is what you are > > using when running under POSIX/Linux/MS Windows), chose to use the > > OOB flags (e.g., MSG_OOB) to indicate the *transmission* of OOB > > data -- but it's not really OOB data. In fact, when I attempt to > > receive using the MSG_OOB flag using the OS interfaces on my system, > > I get back an error (EINVAL - Invalid argument). I would expect > > that asyncore would report this error somehow or other. > > > You can, of course, expect what you like, but experience is the best > guide to what will actually happen. Agreed, but having acknowledged that I had never used asyncore, I was trying to express the hope that the designers would not purposely discard a error condition without notifying the user, particularly for a "reliable" transfer method such as TCP. > Steve - dmw -- . Douglas Wells . Connection Technologies . . Internet: -sp9804- -at - contek.com- . From carsten at uniqsys.com Fri Jul 13 08:15:38 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 13 Jul 2007 08:15:38 -0400 Subject: Fast powerset function In-Reply-To: <7xodigr6xk.fsf@ruckus.brouhaha.com> References: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> <7xodigr6xk.fsf@ruckus.brouhaha.com> Message-ID: <20070713120150.M89148@uniqsys.com> On 13 Jul 2007 02:25:59 -0700, Paul Rubin wrote > Antoon Pardon writes: > > On 7/12/07, Arash Arfaee wrote: > > > I need a powerset generator function. It's really slow with recursion. Does > > > anybody have any idea or code(!!) to do it in an acceptable time? > > My idea would be the following. ... > > 3) let n range from 0 to 2 ** lng > > That may help a little but my guess is the slowness comes from > the size (2**n) of the power set. That's true if by "a little bit" you mean "a lot." Observe: """ def recursive_powerset(s): if not s: yield set() for x in s: s2 = s - set([x]) for subset in recursive_powerset(s2): yield subset for subset in recursive_powerset(s2): yield subset.union(set([x])) def nonrecursive_powerset(s): # Four lines of code hidden. # I want the OP to figure this out for himself. import time print " N Recursive Non-Recursive" print " - ------------- -------------" for n in range(8): t1 = time.time() x = list(recursive_powerset(set(range(n)))) t2 = time.time() x = list(nonrecursive_powerset(set(range(n)))) t3 = time.time() print "%4d %12.6fs %12.6fs" % (n,t2-t1,t3-t2) """ Results: N Recursive Non-Recursive - ------------- ------------- 0 0.000029s 0.000026s 1 0.000027s 0.000028s 2 0.000063s 0.000036s 3 0.000379s 0.000067s 4 0.004795s 0.000191s 5 0.045020s 0.001054s 6 0.633989s 0.013931s 7 14.881078s 0.212958s It is correct that a power set algorithm can never be truly fast because the run time is exponential by definition, but the non-recursive (iterative) method is still a lot faster than the recursive method. -Carsten From http Fri Jul 20 05:58:12 2007 From: http (Paul Rubin) Date: 20 Jul 2007 02:58:12 -0700 Subject: How to organize control access to source code ? References: <1184618776.798929.98960@57g2000hsv.googlegroups.com> <469c6fc6$0$27173$426a34cc@news.free.fr> Message-ID: <7xk5svpfbf.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > > How can we organize development team with code source control policy, > > that limit access to some portion of code ? > > The question may be of interest, but I'm afraid I don't understand how > it relates to Python ??? It sounds like a reasonable application of multiple Mercurial repositories. Mercurial is a distributed source control system written in Python. Does that count? From mccredie at gmail.com Tue Jul 10 19:53:51 2007 From: mccredie at gmail.com (Matimus) Date: Tue, 10 Jul 2007 23:53:51 -0000 Subject: SafeConfigParser can set unsafe values In-Reply-To: <46940a3e$0$18464$afc38c87@news.optusnet.com.au> References: <46940a3e$0$18464$afc38c87@news.optusnet.com.au> Message-ID: <1184111631.293350.106340@o11g2000prd.googlegroups.com> > Should SafeConfigParser.set() be escaping automatically? It seems like that would be a nice feature. However, may I offer up that if you are setting an option and then later on getting that value back in the same program, you probably should have used some other storage mechanism in the first place. That is, you shouldn't store values needed during the runtime of your program in a ConfigParser instance. As far as I can tell, these are the valid use cases for ConfigParser: 1. Use ConfigParser to read values from an config file - This implies .read() followed by .get()s 2. Use ConfigParser to create and write a config file - This implies .set()s followed by .write() 3. Use ConfigParser to read, modify and write a config file. - This implies .read() followed by .get()s followed by .set()s followed by .write() None of the above use cases involve calling .get() after a .set(). Perhaps I am missing a use case though. While I think you have technically pointed out a potential bug, I'm not sure why it matters. Such a bug only comes about for (IMHO) flawed use cases. Matt From nospam.themindstorm at gmail.com Fri Jul 27 20:39:18 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Sat, 28 Jul 2007 00:39:18 +0000 (UTC) Subject: problem with change to exceptions References: Message-ID: Neal Becker wrote in news:f8e0g4$o1u$1 at sea.gmane.org: > Alex Popescu wrote: > >> Neal Becker wrote in >> news:f8dspe$fm2$1 at sea.gmane.org: >> > > [snip...] > >>> >> >> You can pass to the exception: >> a) a string (it will become the message) >> b) a tuple of values (can it be a list also?) >> >> In your case there is no message, no values so args is NoneType. >> > Yes, args is None. So the assignment: > self.args = args > > should set self.args to None. Nothing wrong there, and what has this > got to do with NoneType being iterable? > args are used to generate the traceback when a message was not provided. ./alex -- .w( the_mindstorm )p. From sjmachin at lexicon.net Tue Jul 3 06:00:50 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 03 Jul 2007 03:00:50 -0700 Subject: need help with win32com In-Reply-To: <1183453567.042362.140490@n2g2000hse.googlegroups.com> References: <1183453567.042362.140490@n2g2000hse.googlegroups.com> Message-ID: <1183456850.187980.29930@x35g2000prf.googlegroups.com> On Jul 3, 7:06 pm, Graeme Glass wrote: > On Jul 2, 6:38 pm, Thomas wrote: > > > I want to be able to access an excel file and extract the code from > > the macro that is in the file. How can I do this? > > > -- > > ~Thomas~ > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483742 The OP wants to extract the code of a macro. The above URL points to an interesting recipe for an extra layer on top of xlrd's data- extraction API. xlrd, as documented, avoids macros. The OP needs, as his subject suggests, help with win32com, which is AFAIK the only possible Python-related candidate for a solution to his problem. From bob at mellowood.ca Fri Jul 13 22:36:38 2007 From: bob at mellowood.ca (bvdp) Date: Fri, 13 Jul 2007 19:36:38 -0700 Subject: Circular import problem In-Reply-To: <1184343897.111992.107880@g4g2000hsf.googlegroups.com> References: <1184294176.550267.119980@n60g2000hse.googlegroups.com> <1184343897.111992.107880@g4g2000hsf.googlegroups.com> Message-ID: <1184380598.535032.251520@q75g2000hsh.googlegroups.com> Just as a bit of a followup, I have fixed the problem in my code. I changed the order of some of the imports in some other modules. What I was doing was more guesswork and good luck ... but it works. I really wonder if there is a better way to figure these problems out. Reading a few of the other discussions on the 'net about this it seems that I'm not the 1st to get hit with the problem ... and the solutions I find aren't any prettier than mine :) From willmaier at ml1.net Wed Jul 11 13:45:18 2007 From: willmaier at ml1.net (Will Maier) Date: Wed, 11 Jul 2007 12:45:18 -0500 Subject: condor_compiled python interpreter In-Reply-To: <1184174932.530506.13300@r34g2000hsd.googlegroups.com> References: <1184174932.530506.13300@r34g2000hsd.googlegroups.com> Message-ID: <20070711174518.GG20746@lass.lfod.us> On Wed, Jul 11, 2007 at 10:28:52AM -0700, Thomas Nelson wrote: > Does anyone know where I could find help on condor_compiling a > python interpreter? My own attempts have failed, and I can't find > anything on google. This is probably more condor-related than Python-related, but are you building for the standard universe? It shouldn't be too hard. See this thread[0] for some more bits, including a step-by-step. [0] https://lists.cs.wisc.edu/archive/condor-users/2007-March/msg00216.shtml https://lists.cs.wisc.edu/archive/condor-users/2007-March/msg00217.shtml -- [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] From kay.schluehr at gmx.net Thu Jul 5 16:40:29 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 05 Jul 2007 13:40:29 -0700 Subject: Re-raising exceptions with modified message In-Reply-To: References: Message-ID: <1183668029.470160.218230@q69g2000hsb.googlegroups.com> On Jul 5, 3:53 pm, Christoph Zwerschke wrote: > What is the best way to re-raise any exception with a message > supplemented with additional information (e.g. line number in a > template)? Let's say for simplicity I just want to add "sorry" to every > exception message. My naive solution was this: > > try: > ... > except Exception, e: > raise e.__class__, str(e) + ", sorry!" > > This works pretty well for most exceptions, e.g. > > >>> try: > ... 1/0 > ... except Exception, e: > ... raise e.__class__, str(e) + ", sorry!" > ... > Traceback (most recent call last): > File "", line 4, in > ZeroDivisionError: integer division or modulo by zero, sorry! > > But it fails for some exceptions that cannot be instantiated with a > single string argument, like UnicodeDecodeError which gets "converted" > to a TypeError: > > >>> try: > ... unicode('\xe4') > ... except Exception, e: > ... raise e.__class__, str(e) + ", sorry!" > ... > Traceback (most recent call last): > File "", line 4, in > TypeError: function takes exactly 5 arguments (1 given) > > Another approach is using a wrapper Extension class: > > class SorryEx(Exception): > def __init__(self, e): > self._e = e > def __getattr__(self, name): > return getattr(self._e, name) > def __str__(self): > return str(self._e) + ", sorry!" > > try: > unicode('\xe4') > except Exception, e: > raise SorryEx(e) > > But then I get the name of the wrapper class in the message: > > __main__.SorryEx: 'ascii' codec can't decode byte 0xe4 in position 0: > ordinal not in range(128), sorry! > > Yet another approach would be to replace the __str__ method of e, but > this does not work for new style Exceptions (Python 2.5). > > Any suggestions? > > -- Chris If you are sure that the exception isn't caught on another level just use the following showtraceback() function, manipulate it's output slightly and terminate your program with sys.exit() def showtraceback(): ''' (Copied from code.py) ''' try: type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb tblist = traceback.extract_tb(tb) del tblist[:1] lst = traceback.format_list(tblist) if lst: lst.insert(0, "Traceback (most recent call last):\n") lst[len(lst):] = traceback.format_exception_only(type, value) finally: tblist = tb = None sys.stderr.write("".join(lst)) From tunuyan-house at hotmail.com Fri Jul 13 15:26:52 2007 From: tunuyan-house at hotmail.com (Natalia) Date: Fri, 13 Jul 2007 12:26:52 -0700 Subject: www.cerocom.com Message-ID: <1184354812.029036.210880@n2g2000hse.googlegroups.com> ...................................... www.cerocom.com ...................................... You will be able to ask yourself: Is Internet a good investment for my company? So that an investment would have to do I of this type? Really is going to serve to me to have a Web site? So that to be in Internet? See some of the main advantages have a Web site: ? Increase the productivity and to generate more businesses with the implementation of collaboration rofe and integration maximizing the value of Internet and networks IP. ? Offer solutions of Internet, integration and collaboration in accordance with our clients, anyone is their size or trains, to rofesional r to integrate their applications, to fortify their present position in the market or to impel their growth, assuring trustworthiness, discharge rofesional qualification, and customized service. I invite it to cross the Web site and interiorice of the services available. www.cerocom.com Contact: Commercial direction: Viamonte 783 Piso 3? Capital Federal (C1053ABO) Bs. As. Argentina Tel/Fax: (54.11) 4322.1201 Celular: (54-9-11) (15) 5006.4384 Mail: cerocom at cerocom.com Web Site: www.cerocom.com From ehsan.khoddam at gmail.com Mon Jul 30 17:13:54 2007 From: ehsan.khoddam at gmail.com (Ehsan) Date: Mon, 30 Jul 2007 14:13:54 -0700 Subject: yield keyword usage Message-ID: <1185830034.713489.174640@r34g2000hsd.googlegroups.com> hi coulde any one show me the usage of "yield" keyword specially in this example: """Fibonacci sequences using generators This program is part of "Dive Into Python", a free Python book for experienced programmers. Visit http://diveintopython.org/ for the latest version. """ __author__ = "Mark Pilgrim (mark at diveintopython.org)" __version__ = "$Revision: 1.2 $" __date__ = "$Date: 2004/05/05 21:57:19 $" __copyright__ = "Copyright (c) 2004 Mark Pilgrim" __license__ = "Python" def fibonacci(max): a, b = 0, 1 while a < max: yield a a, b = b, a+b for n in fibonacci(1000): print n, From george.sakkis at gmail.com Wed Jul 25 13:25:06 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 25 Jul 2007 17:25:06 -0000 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <1185379218.286977.124040@19g2000hsx.googlegroups.com> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <1185379218.286977.124040@19g2000hsx.googlegroups.com> Message-ID: <1185384306.104549.287510@19g2000hsx.googlegroups.com> On Jul 25, 12:00 pm, kyoso... at gmail.com wrote: > On Jul 25, 10:46 am, beginner wrote: > > > > > On Jul 25, 10:19 am, Stargaming wrote: > > > > On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote: > > > > Hi, > > > > > I am wondering how do I 'flatten' a list or a tuple? For example, I'd > > > > like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4]. > > > > A recursive function, always yielding the first element of the list, > > > could do the job. See the ASPN Python Cookbook for a few implementations.http://aspn.activestate.com/ASPN/search? > > > query=flatten§ion=PYTHONCKBK&type=Subsection > > > > > Another question is how do I pass a tuple or list of all the aurgements > > > > of a function to the function. For example, I have all the arguments of > > > > a function in a tuple a=(1,2,3). Then I want to pass each item in the > > > > tuple to a function f so that I make a function call f(1,2,3). In perl > > > > it is a given, but in python, I haven't figured out a way to do it. > > > > (Maybe apply? but it is deprecated?) > > > >>> def foo(a, b, c): print a, b, c > > > ... > > > >>> t = (1, 2, 3) > > > >>> foo(*t) > > > > 1 2 3 > > > > Have a look at the official tutorial, 4.7.4http://www.python.org/doc/ > > > current/tut/node6.html#SECTION006740000000000000000 > > > > > Thanks, > > > > cg > > > > HTH, > > > Stargaming > > > Hi Stargaming, > > > I know the * operator. However, a 'partial unpack' does not seem to > > work. > > > def g(): > > return (1,2) > > > def f(a,b,c): > > return a+b+c > > > f(*g(),10) will return an error. > > > Do you know how to get that to work? > > > Thanks, > > cg > > As I mentioned, you can access the elements individually using square > brackets. The following works: > > f(g()[0], g()[1], 10) > > But it's not clear. Unfortunately, I'm not seeing much else for tuple > unpacking except the obvious: > > a,b=g() > f(a,b,10) > > Mike Or if you'd rather write it in one line: f(*(g() + (10,))) George From stefan.behnel-n05pAM at web.de Fri Jul 13 03:51:15 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 13 Jul 2007 09:51:15 +0200 Subject: Question about PyDict_SetItemString In-Reply-To: <1184311267.876950.150040@e16g2000pri.googlegroups.com> References: <1184311267.876950.150040@e16g2000pri.googlegroups.com> Message-ID: <46972EF3.4000807@web.de> lgx schrieb: > Does PyDict_SetItemString(pDict,"key",PyString_FromString("value")) > cause memory leak? You shouldn't use that at all. If you look at the sources, what SetItemString does is: create a Python string from the char* and call PyDict_SetItem() to put the new string in. So it is actually much more efficient to use PyDict_SetItem() directly in your case. If you want to temporarily create a char* from a string and you know that the char content won't be modified, use the PyString_FROM_STRING macro, which just returns the internal pointer. Stefan From wildemar at freakmail.de Fri Jul 13 21:18:43 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Sat, 14 Jul 2007 03:18:43 +0200 Subject: Understanding python functions - Instant Python tutorial In-Reply-To: References: <4697AB4F.80708@freakmail.de> Message-ID: <46982473.1050308@freakmail.de> Wayne Brehaut wrote: >> (had to be a semicolon there) >> > > Not "had to be" since a discerning reader will note that the two > values in the list: > > >>> id(x), id(y) > (19105872, 19091664) Weeeell, as long as we are nitpicking: That's a tuple, not a list. ;) /W From jstroud at mbi.ucla.edu Thu Jul 26 17:05:36 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 26 Jul 2007 14:05:36 -0700 Subject: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> Message-ID: Steve Holden wrote: > Sadly there are too few female members of > either c.l.py or c.l.p.m for it to make much difference. Midway through a semester in college, after a few days (or was it a few weeks?) of...well...lets just say I was studying real hard...I got lost on my way to o-chem and wandered into the interior design department by accident and found what I like to call "the motherload". No, the girls definitely weren't doing the sciency stuff back then. But that has been a few years already, so maybe things have changed. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From bjourne at gmail.com Wed Jul 4 19:05:29 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Thu, 5 Jul 2007 01:05:29 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182448413.966430.299590@m36g2000hse.googlegroups.com> <7xhcp0fom4.fsf@ruckus.brouhaha.com> <87tzt0tgol.fsf@benfinney.id.au> <1182533987.715191.159850@m36g2000hse.googlegroups.com> Message-ID: <740c3aec0707041605w3ef468c8g38cec3ae7feee984@mail.gmail.com> On 6/22/07, Eduardo EdCrypt O. Padoan wrote: > Remember that pure CPython has no different "compile time" and > runtiime. But Psyco and ShedSkin could use the annotations the way > they want. ..... > def compile(source: "something compilable", > filename: "where the compilable thing comes from", > mode: "is this a single statement or a suite?"): I think the above would make an annotation-enhanced Psyco or ShedSkin very confused. -- mvh Bj?rn From the.mindstorm.mailinglist at gmail.com Fri Jul 20 05:33:28 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Fri, 20 Jul 2007 09:33:28 +0000 (UTC) Subject: Converting between objects References: <676224240707191317i41e76ab7lceb39fcb981b0188@mail.gmail.com> Message-ID: "Nathan Harmston" wrote in news:676224240707191317i41e76ab7lceb39fcb981b0188 at mail.gmail.com: > Hi, > > I have being thinking about this and was wondering with built in types > you can do things like > > float(1) or str(200) > > is there way I can define conversion functions like this: > > say i have a class A and a class B > > bobj = B() > aobj = a(bobj) > > in a neater way than just defining a set of methods > > def a(object_to_convert) > # if object_to_convert of type...... > # do some stuff > return A() > > def b(object_to_convert) > # if object_to_convert of type...... > # do some stuff > return B() > > Cause this seems a little verbose and not very OO. > > Please correct me if I m wrong or offer me hints as to a better way to > do it ? > > Many Thanks > > nathan I think your question is somehow misleading and here is why I'm thinking this: 1/ on one side: creating objects from other objects (and this part is related to float(1), str(200) and have been covered by the others in this thread) 2/ on the otherside: making an object to behave differently or implement a new protocol described by the second object (I think this is the Pythonic way of calling it). bests, ./alex -- .w( the_mindstorm )p. From kyosohma at gmail.com Tue Jul 31 15:57:05 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 31 Jul 2007 19:57:05 -0000 Subject: Creating a shared object in python In-Reply-To: References: Message-ID: <1185911825.967103.279730@x35g2000prf.googlegroups.com> On Jul 31, 2:37 pm, "Delgado, Edgardo CIV NAVAIR 4.1.4.3" wrote: > Is there a way to create a shared object in python? > > Thx, > > Edgar You can save variables in a separate module. Something like this structure works quite well: # shared.py # shared variables / object someNum = 0 # first module import shared x = shared.someNum # do something x = 5 # second module import shared y = shared.someNum Basically as the code is called, be it a dialog from a main gui or whatever, it updates this variable that is kind of held "out there" in memory. Thus, it is available for and other running modules that import it. It's kind of hard to get your mind around at first, but I've used it before for some cool programming magic. Mike From carsten at uniqsys.com Fri Jul 20 15:31:18 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 20 Jul 2007 15:31:18 -0400 Subject: Pythonic way for missing dict keys In-Reply-To: References: Message-ID: <1184959878.3586.18.camel@dot.uniqsys.com> On Fri, 2007-07-20 at 19:08 +0000, Alex Popescu wrote: > Hi all! > > I am pretty sure this has been asked a couple of times, but I don't seem > to find it on the archives (Google seems to have a couple of problems > lately). > > I am wondering what is the most pythonic way of dealing with missing > keys and default values. > > According to my readings one can take the following approaches: > > 1/ check before (this has a specific name and acronym that I haven't > learnt yet by heart) > > if not my_dict.has_key(key): > my_obj = myobject() > my_dict[key] = my_obj > else: > my_obj = my_dict[key] This is called "Look before you leap." Note that "if key in my_dict" is preferred over has_key(). > 2/ try and react on error (this has also a specific name, but...) > > try: > my_obj = my_dict[key] > except AttributeError: > my_obj = myobject() > my_dict[key] = my_obj > This is called "It's easier to ask for forgiveness than permission." > 3/ dict.get usage: > > my_obj = my_dict.get(key, myobject()) > > I am wondering which one is the most recommended way? get usage seems > the clearest, but the only problem I see is that I think myobject() is > evaluated at call time, and so if the initialization is expensive you > will probably see surprises. All ways are equally acceptable. The main difference is in the amount of optimism the code conveys about the existence of the key. Number 1 and 3 convey the notion that you expect the key to be missing, that it's normal for the key to be missing. Number 2 conveys the notion that the key is only missing under exceptional circumstances. As you noted, number 3 is not good if it's expensive to initialize a myobject() instance, because the object will be created regardless of whether it'll be needed. In that case, you should go with number 1, or the following variant of number 3: my_obj = my_dict.get(key, None) if my_obj is None: my_obj = myobject() This only works if the dictionary doesn't contain Nones already. If it does, you would create a cheap sentinel object instead: sentinel = object() my_obj = my_dict.get(key, sentinel) if my_obj is sentinel: my_obj = myobject() HTH, -- Carsten Haese http://informixdb.sourceforge.net From noreply at python.org Thu Jul 26 05:20:26 2007 From: noreply at python.org (Post Office) Date: Thu, 26 Jul 2007 11:20:26 +0200 Subject: No subject Message-ID: <200707260813.l6Q8DAbd032612@mbox.infotel.bg> ----Virus Warning Message (from InterScanVirusWall mbox.infotel.bg) Found virus WORM_MYDOOM.GEN in file MESSAGE.BAT (in message.zip) The uncleanable file is deleted. If you have questions, contact administrator. --------------------------------------------------------- -------------- next part -------------- The original message was received at Thu, 26 Jul 2007 11:20:26 +0200 from python.org [158.207.10.37] ----- The following addresses had permanent fatal errors ----- ----- Transcript of session follows ----- while talking to python.org.: >>> MAIL From:"Post Office" <<< 501 "Post Office" ... Refused -------------- next part -------------- ----Virus Warning Message (from InterScanVirusWall mbox.infotel.bg) message.zip is removed from here because it contains a virus. --------------------------------------------------------- From steve at holdenweb.com Mon Jul 16 15:39:31 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 16 Jul 2007 15:39:31 -0400 Subject: zipfile 2GB problems? In-Reply-To: <1184612398.359979.28900@d55g2000hsg.googlegroups.com> References: <1184474112.081258.111490@n60g2000hse.googlegroups.com> <1184525970.082235.238200@q75g2000hsh.googlegroups.com> <1184528949.751377.5620@g4g2000hsf.googlegroups.com> <1184612398.359979.28900@d55g2000hsg.googlegroups.com> Message-ID: xamdam wrote: > On Jul 15, 5:39 pm, Steve Holden wrote: >> xamdam wrote: >>>>> Additional info: my file is from a data provider, do not know what >>>>> they used to compress it. Previous files worked ok, this one is the >>>>> 1st over 2GB. Winzip has no problem with it. >>>> It could be you are using a Python with an in-built limit of 2GB on file >>>> size. What happens if you open the file, seek past the 2GB point and >>>> then try and read data? >>> Steve, >>> I used is_zipfile function, which from does exactly that from a quick >>> read - goes to the end, reads expected string. It worked fine. Tried >>> regular Windows 2.4.4 and 2.5.1, same result. >> Fine, if it isn't file size limitations I suspect you need to post some >> code and a traceback so we can get better insight into exactly what the >> problem is. >> > > It's failing in the ZipFile constructor, which ends up throwing > > zipfile(2.4.3).py:291> raise BadZipfile, "Bad magic number for file > header" > > > Well, that one bald line by itself certainly doesn't give *me* any traction an what the problem might be. Getting information about this problem is like (i.e. as difficult as) pulling teeth! 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 dave at boost-consulting.com Wed Jul 4 23:47:18 2007 From: dave at boost-consulting.com (David Abrahams) Date: Wed, 04 Jul 2007 23:47:18 -0400 Subject: import mysteries References: Message-ID: <87zm2bjyux.fsf@grogan.peloton> on Wed Jul 04 2007, Peter Otten <__peter__-AT-web.de> wrote: >>> Explicitly passed, see >>> >>> > http://genshi.edgewall.org/browser/trunk/genshi/filters/tests/transform.py >> >> IIRC I ran doctest on the file I cited, not the one you're pointing >> at. Is there some new magic doctest feature I should know about? > > Had you looked at it Gimme a little credit, please! Of course I looked at it. > you'd seen that the file I pointed to is the driver > script for running the doctests in the file you pointed to Yes, I saw that, but I don't know of any magic feature that causes the driver script to get loaded when I invoke doctest directly on the file I pointed to. > -- unfortunately they have the same name. [...]/tests/transform.py > does indeed inject a HTML object into the globals of > [...]/filters/transform.py before it runs the tests. Yes, I saw that, but as I said... Anyway, maybe I just got confused and doctest-ed the driver script. That certainly would explain everything. >>>> Another example: I was recently working on some code that did an >>>> import from inside a class method. That import was failing. I moved >>>> the import to the top of the file (at module scope) and it succeeded. >>>> I'm fairly sure that nobody was monkeying around with sys.path in that >>>> case. Can anyone think of a likely explanation? >>> >>> Too vague, sorry. >> >> # this will succeed if I do it here >> # import foo.bar >> >> class X: >> def y(): >> import foo.bar # but this fails > > Are threads involved? I vaguely remember a problem with Queue.Queue that > came up on this list some time ago. I don't know, honestly. This was probably in Trac somewhere. I don't know if it's threaded. -- Dave Abrahams Boost Consulting http://www.boost-consulting.com The Astoria Seminar ==> http://www.astoriaseminar.com From kar1107 at gmail.com Tue Jul 3 18:22:56 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 03 Jul 2007 15:22:56 -0700 Subject: object references/memory access In-Reply-To: <468ac0b1$0$9090$9b622d9e@news.freenet.de> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1183407411.397142.304790@e16g2000pri.googlegroups.com> <1183417108.245203.158830@x35g2000prf.googlegroups.com> <4689e535$0$23896$9b622d9e@news.freenet.de> <1183488824.131448.62720@x35g2000prf.googlegroups.com> <468ac0b1$0$9090$9b622d9e@news.freenet.de> Message-ID: <1183501376.537918.154340@i38g2000prf.googlegroups.com> On Jul 3, 2:33 pm, "Martin v. L?wis" wrote: > > If the problem does not require two way communication, which is > > typical of a producer-consumer, it is a lot faster to allow P to fully > > run before C is started. > > Why do you say it's *a lot* faster. I find that it is a little faster. > The only additional overhead from switching forth and back between > consumer and producer is the overhead for context switching, which > is typically negligible, compared to everything else that is going > on. True it needn't be *a lot*. I did observe 25% gain or more when there were a chain of processes involved as in a shell pipeline. Again this could be very problem specific. What I had, included something like 4 or 5 processes connected as in p1 | p2 | p3 | p4 ... here I found the back-n-forth context switching was slowing down quite a bit (some thing like 2 mins task completed in under 40 seconds without the piping) If all you had is just two processes, P and C and the amount of data flowing is less (say on the order of 10's of buffer-size ... e.g. 20 times 4k), *a lot* may not be right quantifier. But if the data is large and several processes are involved, I am fairly sure the overhead of context-switching is very significant (not negligible) in the final throughput. Thanks, Karthik > > Regards, > Martin From emin.shopper at gmail.com Mon Jul 9 10:43:24 2007 From: emin.shopper at gmail.com (Emin.shopper Martinian.shopper) Date: Mon, 9 Jul 2007 10:43:24 -0400 Subject: What is the preferred doc extraction tool? Message-ID: <32e43bb70707090743r6df891eeo3500e0893d05aa54@mail.gmail.com> Dear Experts, What is the preferred doc extraction tool for python? It seems that there are many very nice options (e.g., pydoc, epydoc, HappyDoc, and lots of others), but what is the "standard" tool or at least what is the tool used to generate the documentation for the python standard library? Thanks, -Emin -------------- next part -------------- An HTML attachment was scrubbed... URL: From kelybrown at gmail.com Wed Jul 25 07:56:20 2007 From: kelybrown at gmail.com (K. Brown) Date: Wed, 25 Jul 2007 04:56:20 -0700 Subject: =?utf-8?B?4paE4pa6IEZSRUUgU2F0ZWxsaXRlIFRWIG9uIHlvdXIgUEMgLSBEb3dubG9hZCBOb3chIOKXhOKWhA==?= Message-ID: <1185364580.436908.150960@e16g2000pri.googlegroups.com> SATELLITE TV for PC - Amazing Software which Instantly Turns your Computer into a Super TV! Get over 3000 Stations. Watch all your favorite shows on your Computer! Save 1000's of $$$ over many years on cable and satellite bills. INSTANT DOWNLOAD Know More About It: http://tv-pc.xt.cx/ From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Jul 19 16:33:23 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 19 Jul 2007 22:33:23 +0200 Subject: Converting between objects References: Message-ID: <5ga04jF3f1pvjU1@mid.individual.net> Nathan Harmston wrote: > is there way I can define conversion functions like this: > > say i have a class A and a class B > > bobj = B() > aobj = a(bobj) > > in a neater way than just defining a set of methods > > def a(object_to_convert) > # if object_to_convert of type...... > # do some stuff > return A() > > def b(object_to_convert) > # if object_to_convert of type...... > # do some stuff > return B() > > Cause this seems a little verbose and not very OO. Yes, simply write something like class a(object): def __init__(self, parameter): if isinstance(parameter, B): # conversion from B to a else: # something else Something like that is called "conversion constructor". At least in C++. Regards, Bj?rn -- BOFH excuse #55: Plumber mistook routing panel for decorative wall fixture From tinaweb at bestemselv.com Wed Jul 11 09:22:17 2007 From: tinaweb at bestemselv.com (Tina I) Date: Wed, 11 Jul 2007 15:22:17 +0200 Subject: python extra In-Reply-To: <1183919191.840576.204450@n60g2000hse.googlegroups.com> References: <1183919191.840576.204450@n60g2000hse.googlegroups.com> Message-ID: mensanator at aol.com wrote: > On Jul 8, 12:59?pm, Neal Becker wrote: >> Just a little python humor: >> >> http://www.amazon.com/Vitamin-Shoppe-Python-Extra-tablets/dp/B00012NJ... > > Aren't there any female Python programmers? > No, of course not. Oh, and guys: If you take those pills please observe the warning; "Safety information: Do not use if you are pregnant or nursing!" :P From mcfletch at vrplumber.com Mon Jul 23 17:03:46 2007 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Mon, 23 Jul 2007 17:03:46 -0400 Subject: Where do they tech Python officialy ? In-Reply-To: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> Message-ID: <46A517B2.7090302@vrplumber.com> NicolasG wrote: ... > I'm planning to save some money and attend a course in any of the > universities that teach hard core Python. > > Does some one have any suggestions on which University to attend ? > In Canada, the University of Toronto is planning to switch all first-year Comp-Sci courses to Python this September. Last I heard the University of Waterloo allowed Python submissions for most assignments in most courses. But those are "learn hard-core computer science using Python" solutions, not "learn hard-core Python" solutions. If you really want to learn hard-core Python, probably your best bet is: * read everything Tim Peters has ever written in comp.lang.python (this will take a few months), start with "import this" * read everything the PyPy guys have ever written (particularly Christian and Armin) * read and try to beat the more exotic recipes in the Python cookbook * read the papers from the various PyCons on metaclasses and the like, build a couple of dozen metaclasses and descriptors But jumping into "hardcore" first might not be the best approach. Many would suggest just learning "normal" Python first, *then* moving onto the hardcore stuff. HTH, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From the.mindstorm.mailinglist at gmail.com Thu Jul 12 11:52:27 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Thu, 12 Jul 2007 08:52:27 -0700 Subject: web page text extractor In-Reply-To: References: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> <6faf39c90707120723t8f8188chb131779e66eaf971@mail.gmail.com> Message-ID: <1184255547.373790.204790@w3g2000hsg.googlegroups.com> On Jul 12, 5:24 pm, "Andre Engels" wrote: > 2007/7/12, Andre Engels : > > I forgot to include > > import urllib2, re > > here > > > def textonly(url): > > # Get the HTML source on url and give only the main text > > f = urllib2.urlopen(url) > > text = f.read() > > r = re.compile('\<[^\<\>]*\>') > > newtext = r.sub('',text) > > while newtext != text: > > text = newtext > > newtext = r.sub('',text) > > return text > > -- > Andre Engels, andreeng... at gmail.com > ICQ: 6260644 -- Skype: a_engels Andre I think that unfortunately your solution will not ignore inlined scripting, inlined styling, etc. On the otherside, I don't think there are many solutions available, other than the Lynx approach somebody has already suggested. bests, ./alex -- .w( the_mindstorm )p. From damienlmoore at gmail.com Tue Jul 17 12:24:49 2007 From: damienlmoore at gmail.com (dmoore) Date: Tue, 17 Jul 2007 16:24:49 -0000 Subject: Embedding/Extending Python in/with C++: non-static members? In-Reply-To: <1184593533.995878.123010@k79g2000hse.googlegroups.com> References: <1184593533.995878.123010@k79g2000hse.googlegroups.com> Message-ID: <1184689489.343144.178550@g37g2000prf.googlegroups.com> (I thought I'd follow up on this post so as not to send unsuspecting readers down a hopeless path) duh! I've obviously spent too much time with dynamic languages. The problem with what I'm trying to do is obvious: In C++ you simply can't pass pointers to call a particular instance of a C++ class method so there is no way to initialize the PyMethodDef with class methods instances. In other words, there is no callback mechanism built into the language and you are stuck with template based approaches, which obviously don't mesh very well with the Python/C API (without SWIG, Boost::Python etc). So to get a python interpreter instance to communicate with pre- existing dynamically allocated C++ objects, it looks like I need to implement some kind of lookup table approach. The static nature of the Python/C API is just too cumbersome for use with multiple interpreters and making me thing it might be better to embed just a sinlge interpreter inside my app and use multi-process communication with either pipes or sockets for the extra interpreters... From brotherjenos at gmail.com Fri Jul 20 11:27:13 2007 From: brotherjenos at gmail.com (Walker Lindley) Date: Fri, 20 Jul 2007 08:27:13 -0700 Subject: Pickled objects over the network In-Reply-To: References: Message-ID: <9c8d48280707200827h66d32ffcxe68978590efd3e97@mail.gmail.com> It doesn't interface well because the string you end up with often doesn't fit into a single packet. Therefore you have to add a layer of protocol on top of it that allows you to check to make sure you have the whole string received before trying to unpickle it. This the case even if you use socket's makefile() method to make a file descriptor. -Walker On 20 Jul 2007 14:00:06 +0100 (BST), Sion Arrowsmith < siona at chiark.greenend.org.uk> wrote: > > >Since pickle has problems > >-- does not interface well with networking > > In what way does pickle not interface well with networking? Other > than, possibly, security issues which you list as a separate problem > with it. I've taken a working XML-RPC system and replaced the XML with > pickle, and had no issues. Other than an order of magnitude > performance gain. (OK, a cow-orker allegedly and unreproducibly found > that cPickle was leaking memory, and as the performance gains weren't > so great with the pure Python implementation, it got shelved and we > stuck with XML-RPC.) > > -- > \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 > > -- > http://mail.python.org/mailman/listinfo/python-list > -- 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: From jstroud at mbi.ucla.edu Fri Jul 13 19:06:05 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 13 Jul 2007 23:06:05 GMT Subject: interactive graphical script builder In-Reply-To: <1184196856.996182.25040@k79g2000hse.googlegroups.com> References: <1184196856.996182.25040@k79g2000hse.googlegroups.com> Message-ID: nik wrote: > Hi, > > I am looking for an interactive graphical script builder for python. > Basically, something like the os X automator. I have made a group of > methods that some non-programmers need to combine into a script. I > don't need a python IDE necessarially, but more of a sequence builder. > I am imagining a tool that could show graphical representations of my > different commands and then string them together in a single "script." > I've done a lot of googling, and the closest things that I can find > are apple automator or labview, but before I go through the process of > making one of those interact with python I would like to know if > anybody already knows of something like them that is more tuned to > python. > > Thanks, > Nik > Check out Viper at Scripps (Sanner, lab). He has a prototype of this type of thing for working with molecular models. I'm not sure how the code is liscensed. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From roy at panix.com Tue Jul 3 07:53:54 2007 From: roy at panix.com (Roy Smith) Date: Tue, 03 Jul 2007 07:53:54 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> Message-ID: aleax at mac.com (Alex Martelli) wrote: > Eckel's and Martin's well-known essays on why good testing can replace > strict static type checking: > > I've read the first before. I just re-read it. There seem to be three different concepts all being talked about at the same time. 1) Static vs. dynamic checking. 2) Type (is-a) checking vs. behavior (has-a) checking. 3) Automatic (i.e. compiler generated) vs. manually written tests. They all allow you to write manual tests. No sane programmer will rely exclusively on the automatic checks, no matter what flavor they are. The interesting thing is that most people seem to conflate items 1 and 2 above into two composite camps: static type checking vs. dynamic behavior checking. There's really no reason you can't have dynamic type checking (things that raise TypeError in Python, for example, or C++'s dynamic_cast). There's also no reason you can't have static behavior checking (Java's interfaces). From the.mindstorm.mailinglist at gmail.com Wed Jul 11 07:30:16 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Wed, 11 Jul 2007 04:30:16 -0700 Subject: stripping the first byte from a binary file In-Reply-To: <4694B01A.30107@web.de> References: <1184063032.195000.25880@i13g2000prf.googlegroups.com> <1184115964.912526.273780@e16g2000pri.googlegroups.com> <1184148168.639675.85900@a26g2000pre.googlegroups.com> <4694B01A.30107@web.de> Message-ID: <1184153416.798767.163740@d55g2000hsg.googlegroups.com> On Jul 11, 1:25 pm, Stefan Behnel wrote: > rvr wrote: > > On Jul 11, 1:28 pm, Steven D'Aprano > > wrote: > >> On Wed, 11 Jul 2007 01:06:04 +0000, rvr wrote: > >>> Is there a way to edit the file in place? The best I seem to be able to > >>> do is to use your second solution to read the file into the string, then > >>> re-open the file for writing and put the whole thing back (minus the > >>> first byte). Thanks. > >> I don't believe that any of the popular operating systems in common use > >> (Windows, Linux, Mac, *BSD) have any such functionality. > > >> For safety, you are best off copying the file (minus the first byte) to a > >> temporary file, then renaming the copy over the original. That way if > >> your process dies midway through copying the file, you don't lose data. > > >> Renaming the file is atomic under Linux and (probably) Mac, so it is as > >> safe as possible. Even under Windows, which isn't atomic, it has a > >> smaller margin for disaster than over-writing the file in place. > > > Thanks for your response. While searching for solution, I found this: > > > http://mail.python.org/pipermail/python-list/2001-December/116519.html > > > Quoting from it: > > > """ > > Replace 2 bytes in place beginning at offset 100 (101st byte): > > > f = open('text_input', 'r+b') > > f.seek(100) > > f.write(chr(123) + chr(0x80)) > > f.seek(0,2) > > f.close() > > """ > > > Can I use the seek() and write() methods in a similar way to remove > > the first byte? For whatever reason I can't seem to make it work > > myself. Thanks again. > > Funny. I just happened to read ESR's "how to ask questions the smart way" and > your posts match quite a few of the examples. :) > > No, you can't. Steven's solution is what I'd go for. > > Stefan Forgive my newbie ignorance, but I am wondering why the other method would not work? I mean it may not be very safe, but I guess it may perform a lot better, than having to read the whole file just to cut out the first byte. TIA, ./alex -- .w( the_mindstorm )p. From zyzhu2000 at gmail.com Wed Jul 25 11:46:58 2007 From: zyzhu2000 at gmail.com (beginner) Date: Wed, 25 Jul 2007 15:46:58 -0000 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <46a76a0c$0$1471$9b622d9e@news.freenet.de> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> Message-ID: <1185378418.100041.38560@w3g2000hsg.googlegroups.com> On Jul 25, 10:19 am, Stargaming wrote: > On Wed, 25 Jul 2007 14:50:18 +0000, beginner wrote: > > Hi, > > > I am wondering how do I 'flatten' a list or a tuple? For example, I'd > > like to transform[1, 2, (3,4)] or [1,2,[3,4]] to [1,2,3,4]. > > A recursive function, always yielding the first element of the list, > could do the job. See the ASPN Python Cookbook for a few implementations.http://aspn.activestate.com/ASPN/search? > query=flatten§ion=PYTHONCKBK&type=Subsection > > > Another question is how do I pass a tuple or list of all the aurgements > > of a function to the function. For example, I have all the arguments of > > a function in a tuple a=(1,2,3). Then I want to pass each item in the > > tuple to a function f so that I make a function call f(1,2,3). In perl > > it is a given, but in python, I haven't figured out a way to do it. > > (Maybe apply? but it is deprecated?) > >>> def foo(a, b, c): print a, b, c > ... > >>> t = (1, 2, 3) > >>> foo(*t) > > 1 2 3 > > Have a look at the official tutorial, 4.7.4http://www.python.org/doc/ > current/tut/node6.html#SECTION006740000000000000000 > > > Thanks, > > cg > > HTH, > Stargaming Hi Stargaming, I know the * operator. However, a 'partial unpack' does not seem to work. def g(): return (1,2) def f(a,b,c): return a+b+c f(*g(),10) will return an error. Do you know how to get that to work? Thanks, cg From mizrandir at gmail.com Tue Jul 24 05:14:38 2007 From: mizrandir at gmail.com (mizrandir at gmail.com) Date: Tue, 24 Jul 2007 02:14:38 -0700 Subject: Recursive lists Message-ID: <1185268478.433070.291370@q75g2000hsh.googlegroups.com> Can someone tell me why python doesn't crash when I do the following: >>> a=[] >>> a.append(a) >>> print a [[...]] >>> print a[0][0][0][0][0][0][0] [[...]] How does python handle this internally? Will it crash or use up lot's of memory in similar but more complicated cases? From greg.kujawa at gmail.com Tue Jul 24 07:50:50 2007 From: greg.kujawa at gmail.com (gregarican) Date: Tue, 24 Jul 2007 11:50:50 -0000 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: <1185277850.068986.212160@d30g2000prg.googlegroups.com> On Jul 24, 6:57 am, NicolasG wrote: > > Why would you want to become a programmer? Programmers smell bad, > > they have no social life, they get treated like crap by everyone. > > They can get paid pretty well but then they spend all the money on > > useless electronic junk so they still live like bums. > > I wouldn't call this person programmer , I would call him a geek ;) > > > one reason to be a programmer, which is that the drive to program > > burns in you like a fire. But in that case don't ask how to become a > > programmer, because you are already one, so welcome to the ranks ;-). > > Yes true , I'm already a programmer.. doing technical support for my > company products in a call center. I hate my job, I hate the moment I > have to wake up to go work ! I hate that moment I have to go sleep > when I think of the next working day morning. > 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 .. You sound like Peter from "Office Space." Each day is the worst day of his life. Hypnotherapy...Python. What's the difference :-) From http Sun Jul 1 14:57:30 2007 From: http (Paul Rubin) Date: 01 Jul 2007 11:57:30 -0700 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> Message-ID: <7xsl88eyud.fsf@ruckus.brouhaha.com> Martin Gregorie writes: > GPS time is UTC time According to Wikipedia, While most clocks are synchronized to Coordinated Universal Time (UTC), the Atomic clocks on the satellites are set to GPS time. The difference is that GPS time is not corrected to match the rotation of the Earth, so it does not contain leap seconds or other corrections which are periodically added to UTC. GPS time was set to match Coordinated Universal Time (UTC) in 1980, but has since diverged. The lack of corrections means that GPS time remains at a constant offset (19 seconds) with International Atomic Time (TAI). http://en.wikipedia.org/wiki/GPS#Ephemeris_and_clock_errors From gert.cuykens at gmail.com Thu Jul 5 13:02:03 2007 From: gert.cuykens at gmail.com (gert) Date: Thu, 05 Jul 2007 17:02:03 -0000 Subject: login http://cheeseshop.python.org/pypi broken ? In-Reply-To: <468C8FED.3000801@v.loewis.de> References: <1183606025.475352.230270@k79g2000hse.googlegroups.com> <468C8FED.3000801@v.loewis.de> Message-ID: <1183654923.527936.80020@57g2000hsv.googlegroups.com> On Jul 5, 8:30 am, "Martin v. L?wis" wrote: > gert schrieb: > > > tried reseting password but i can not login anymore to upload my new > > source code ? > > Please try again. It was a misconfiguration which should be fixed now. > > Regards, > Martin thank you, it works. From NikitaTheSpider at gmail.com Fri Jul 13 12:42:01 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Fri, 13 Jul 2007 12:42:01 -0400 Subject: Problem with Python's "robots.txt" file parser in module robotparser References: <0T7li.5316$rL1.2716@newssvr19.news.prodigy.net> Message-ID: In article , John Nagle wrote: > I asked over at Webmaster World, and over there, they recommend against > using redirects on robots.txt files, because they questioned whether all of > the major search engines understand that. Does a redirect for > "foo.com/robots.txt" mean that the robots.txt file applies to the domain > being redirected from, or the domain being redirected to? Good question. I'd guess the latter, but it's a little ambiguous. I agree that redirecting a request for robots.txt is probably not a good idea. Given that the robots.txt standard isn't as standard as it could be, I think it's a good idea in general to apply the KISS principle when dealing with things robots.txt-y. -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From grflanagan at yahoo.co.uk Mon Jul 16 12:23:31 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: Mon, 16 Jul 2007 09:23:31 -0700 Subject: Compiling python2.5 on IBM AIX In-Reply-To: <1184581796.377610.98230@o61g2000hsh.googlegroups.com> References: <1184581796.377610.98230@o61g2000hsh.googlegroups.com> Message-ID: <1184603011.013990.150960@k79g2000hse.googlegroups.com> On Jul 16, 12:29 pm, bravo.l... at gmail.com wrote: > hi, > > I'm trying to make a local install of python 2.5 on AIX and I'm > getting some trouble with _curses. > > Here is how I tried to compile it : > > export BASE=/usr/local/python251 > > cd Python.2.5.1 > ./configure --prefix=${BASE}/\ > LDFLAGS="-L\${BASE}/lib/"\ > PPFLAGS="-I\${BASE}/include/"\ > > make > make test > make altinstall > I haven't compiled it myself, but I'm told that the installation I work with was compiled with: export PATH=$PATH:/usr/vacpp/bin:/usr/vacpp/lib ./configure --with-gcc="xlc_r -q64" --with-cxx="xlC_r -q64" --disable- ipv6 AR="ar -X64" make make install if that helps. Gerard From doug at alum.mit.edu Fri Jul 6 16:25:56 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Fri, 06 Jul 2007 16:25:56 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <9uRhi.17027$xk5.14289@edtnps82> Message-ID: "Chris Mellon" writes: > Sure, but thats part of the general refcounting vs GC argument - > refcounting gives (a certain level of) timeliness in resource > collection, GC often only runs under memory pressure. If you're > saying that we should keep refcounting because it provides better > handling of non-memory limited resources like file handles, I > probably wouldn't argue. But saying we should keep refcounting > because people like to and should write code that relies on implicit > scope level object destruction I very strongly argue against. And why would you do that? People rely very heavily in C++ on when destructors will be called, and they are in fact encouraged to do so. They are, in fact, encouraged to do so *so* much that constructs like "finally" and "with" have been rejected by the C++ BDFL. Instead, you are told to use smart pointers, or what have you, to clean up your allocated resources. I so no reason not to make Python at least as expressive a programming language as C++. >> > Relying on the specific semantics of refcounting to give >> > certain lifetimes is a logic error. >> > >> > For example: >> > >> > f = some_file() #maybe it's the file store for a database implementation >> > f.write('a bunch of stuff') >> > del f >> > #insert code that assumes f is closed. >> That's not a logic error if you are coding in CPython, though I agree >> that in this particular case the explicit use of "with" would be >> preferable due to its clarity. > I stand by my statement. I feel that writing code in this manner is > like writing C code that assumes uninitialized pointers are 0 - > regardless of whether it works, it's erroneous and bad practice at > best, and actively harmful at worst. That's a poor analogy. C doesn't guarantee that pointers will be initialized to 0, and in fact, they typically are not. CPython, on other other hand, guarantees that the refcounter behaves a certain way. There are languages other than C that guarantee that values are initialized in certain ways. Are you going to also assert that in those languages you should not rely on the initialization rules? |>oug From byte8bits at gmail.com Mon Jul 9 10:53:13 2007 From: byte8bits at gmail.com (brad) Date: Mon, 09 Jul 2007 10:53:13 -0400 Subject: catching empty strings (I guess that's what they are) In-Reply-To: <5fev6bF3bcgoiU2@mid.uni-berlin.de> References: <5fev6bF3bcgoiU2@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > They are still there because you perform the stripping and lowercasing in > the append-call. Not beforehand. Thank you. I made the changes. It works. From jjl at pobox.com Tue Jul 10 19:36:18 2007 From: jjl at pobox.com (John J. Lee) Date: Tue, 10 Jul 2007 23:36:18 GMT Subject: What is the most efficient way to test for False in a list? References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <7x7ipajvst.fsf@ruckus.brouhaha.com> <5fejp2F3cp3igU1@mid.individual.net> <5feju0F3c7pd1U1@mid.uni-berlin.de> <7xsl7xmxcl.fsf@ruckus.brouhaha.com> Message-ID: <87tzsbesr1.fsf@pobox.com> Duncan Booth writes: > Paul Rubin wrote: > >> "Diez B. Roggisch" writes: >>> >> status = all(list) >>> > >>> > Am I mistaken, or is this no identity test for False at all? >>> >>> You are mistaken. all take an iterable and returns if each value of >>> it is true. >> >> all(list) does what the OP's code did, tests for the presence of a >> false value in the list. If you want an identity test, use >> >> status = not (False in list) > > That is an equality test, not an identity test: > >>>> False in [0] > True It's also not a very idiomatic equality test -- "x not in y" is better than "not (x in y)". John From bj_666 at gmx.net Mon Jul 30 14:56:16 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Jul 2007 18:56:16 GMT Subject: How to write GUI and event separately in wxPython?? References: <1185777254.925902.204500@z28g2000prd.googlegroups.com> <5h5kmiF3hmufcU3@mid.uni-berlin.de> <5h5upbF3hmufcU5@mid.uni-berlin.de> Message-ID: <5h6qigF3hmufcU6@mid.uni-berlin.de> On Mon, 30 Jul 2007 11:16:01 -0400, Steve Holden wrote: > Marc 'BlackJack' Rintsch wrote: >> First I thought: Why the unnecessary list comprehension but to my surprise: >> >> In [33]: xrange(42) == xrange(42) >> Out[33]: False >> >> That's strange. >> > Not so strange really. The two xrange objects are different (though I > confess I haven't looked to see how they implement comparisons), but > iterating over them produces the same result. They are different objects, so are range(23) and another range(23) but those compare equal. Somehow I expected two seemingly equal `xrange` objects compare equal too. Ciao, Marc 'BlackJack' Rintsch From rcdailey at gmail.com Tue Jul 31 20:24:26 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 31 Jul 2007 19:24:26 -0500 Subject: Wing IDE for Python v. 3.0 beta1 released In-Reply-To: <46AF8ED7.2070206@wingware.com> References: <46AF8ED7.2070206@wingware.com> Message-ID: <496954360707311724p23fb2f06nde8ea12239dd7fd3@mail.gmail.com> Too bad it's not free. I'll stick with PSPad & IPython On 7/31/07, 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 > > Wing IDE is a commercial IDE designed specifically for Python programmers. > More information about the product and free trials are available at > http://wingware.com/ > > 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 > > (*)'d items are available in Wing IDE Professional only. > > The CHANGELOG.txt file in the installation provides additional details. > > 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). > > 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 normal price to upgrade. > > Thanks! > > The Wingware Team > Wingware | Python IDE > Advancing Software Development > > www.wingware.com > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From whamil1 at entergy.com Mon Jul 30 10:24:04 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Mon, 30 Jul 2007 09:24:04 -0500 Subject: Making Gridded Widgets Expandable In-Reply-To: <1185803688.860152.54210@x40g2000prg.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CAEE@LITEXETSP001.etrsouth.corp.entergy.com> > From: Jim > Hi, > I'm looking at page 548 of Programming Python (3rd Edition) by Mark > Lutz. > The following GUI script works with no problem, i.e., the rows and > columns expand: > ================================================================= > # Gridded Widgets Expandable page 548 > > from Tkinter import * > colors = ["red", "white", "blue"] > > def gridbox(root): > Label(root, text = 'Grid').grid(columnspan = 2) > r = 1 > for c in colors: > l = Label(root, text=c, relief=RIDGE, width=25) > e = Entry(root, bg=c, relief=SUNKEN, width=50) > l.grid(row=r, column=0, sticky=NSEW) > e.grid(row=r, column=1, sticky=NSEW) > root.rowconfigure(r, weight=1) > r += 1 > root.columnconfigure(0, weight=1) > root.columnconfigure(1, weight=1) > > root = Tk() > gridbox(Toplevel(root)) > Button(root, text="Quit", command=root.quit).grid() > mainloop() > ================================================================= > However, the following GUI script using class does not expand rows and > columns: > ================================================================= > # Gridded Widgets Expandable 2 > > from Tkinter import * > colors = ["red", "white", "blue"] > > class GUI(Frame): > def __init__(self,master): > Frame.__init__(self,master) > self.grid() > self.gridbox() > > def gridbox(self): > Label(self, text = 'Grid').grid(columnspan = 2) > r = 1 > for c in colors: > l = Label(self, text=c, relief=RIDGE, width=25) > e = Entry(self, bg=c, relief=SUNKEN, width=50) > l.grid(row=r, column=0, sticky=NSEW) > e.grid(row=r, column=1, sticky=NSEW) > self.rowconfigure(r, weight=1) > r += 1 > self.columnconfigure(0, weight=1) > self.columnconfigure(1, weight=1) > > root = Tk() > root.title("Gridded Widgets Expandable") > app = GUI(root) > Button(root, text="Quit", command=root.quit).grid() > root.mainloop() > ================================================================= > What am I missing? In the first, your gridbox has Toplevel(root) as its master, causing it to be created in a new window. In the second, it has Frame(root) as its master, which does not create a new window. Changing Frame to Toplevel in the class statement and the call to __init__ causes them to act identically. -- -Bill Hamilton From orsenthil at users.sourceforge.net Sun Jul 1 23:22:19 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Mon, 2 Jul 2007 08:52:19 +0530 Subject: what is the PythonWin In-Reply-To: <1183330410.164963.151790@c77g2000hse.googlegroups.com> References: <1183330410.164963.151790@c77g2000hse.googlegroups.com> Message-ID: <20070702032219.GC3553@gmail.com> * steveandleyla at gmail.com [2007-07-01 15:53:30]: > In PythonWin, select Tools | COM MakePy utility | Microsoft Speech > Object Library 5.1). > > I can't find PythonWin .. Does anybody know what this is. I have the > Python shell gui but no "PythonWin". > PythonWin is a separate project by Mark Hammond providing win32 extensions for python. http://sourceforge.net/projects/pywin32/ -- O.R.Senthil Kumaran http://uthcode.sarovar.org From steve at holdenweb.com Mon Jul 23 13:33:10 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Jul 2007 13:33:10 -0400 Subject: Pickled objects over the network In-Reply-To: <00bd01c7ccf6$8fa62540$03000080@hendrik> References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com><011401c7caa0$3e3e5900$03000080@hendrik> <012901c7cb60$5ba530c0$03000080@hendrik> <00c601c7cc38$d826ba00$03000080@hendrik> <00bd01c7ccf6$8fa62540$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "Steve Holden" wrote: > >> Yes. > > Why? > It's difficult to establish, and then correctly implement, almost any security protocol without leaving cracks that attackers can lever open and use to inject code into your process's memory space. By all means go ahead and hack on pickle to do what you want to. Just don't claim your solution is secure without a thorough review. 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 Wed Jul 4 22:32:49 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 05 Jul 2007 14:32:49 +1200 Subject: MethodType/FunctionType and decorators In-Reply-To: <1183591053.434640.119550@o61g2000hsh.googlegroups.com> References: <1183589529.198694.109440@m36g2000hse.googlegroups.com> <1183591053.434640.119550@o61g2000hsh.googlegroups.com> Message-ID: <5f33ovF3apchvU1@mid.individual.net> Alex Popescu wrote: > - for decorators, my test is executed before the class is defined and > so at that moment the function is still a function; it will become a > methodinstance only after the class definition is closed Closer, but still not quite right. Even after the class is defined, the function sitting inside it is still just an ordinary function. You can see this by looking at A.__dict__['method'] An instancemethod is only created when you look the method up in an instance, i.e. a = A() a.method The instancemethod encapsulates a value for 'self' and a reference to the underlying function. This is known as a "bound method". (You also get an instancemethod if you look the method up in the class, i.e. A.method but in that case the instancemethod doesn't contain a value for 'self', and is known as an "unbound method".) -- Greg From BjornSteinarFjeldPettersen at gmail.com Sun Jul 29 10:57:42 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Sun, 29 Jul 2007 14:57:42 -0000 Subject: Compiling python2.5.1 results in 3.5MB python lib? In-Reply-To: <1185705971.100270.120010@57g2000hsv.googlegroups.com> References: <1185556268.287077.258080@d55g2000hsg.googlegroups.com> <46AB0739.9040107@v.loewis.de> <1185705971.100270.120010@57g2000hsv.googlegroups.com> Message-ID: <1185721062.258481.301640@d55g2000hsg.googlegroups.com> On Jul 29, 12:46 pm, simonbun wrote: ... > How would I go about doing this? I'm not sure what to strip nor how to > do it. man strip -- bjorn From mcbooczech at gmail.com Tue Jul 24 17:28:52 2007 From: mcbooczech at gmail.com (Petr Jakes) Date: Tue, 24 Jul 2007 21:28:52 -0000 Subject: datetime.time() class - How to pass it a time string? In-Reply-To: <1185297087.998644.53940@r34g2000hsd.googlegroups.com> References: <1185297087.998644.53940@r34g2000hsd.googlegroups.com> Message-ID: <1185312532.746598.150310@19g2000hsx.googlegroups.com> On 24 ec, 19:11, Robert Dailey wrote: > Hi, > > I have a string in the following format: > > "00:00:25.886411" > > I would like to pass this string into the datetime.time() class and > have it parse the string and use the values. However, the __init__() > method only takes integers (which means I'd be forced to parse the > string myself). Does anyone know of a way I can make it use the > string? Thanks. http://pleac.sourceforge.net/pleac_python/datesandtimes.html the part "http://pleac.sourceforge.net/pleac_python/ datesandtimes.html" HTH Petr Jakes From ars at iki.fi Mon Jul 30 08:55:30 2007 From: ars at iki.fi (Antti Rasinen) Date: Mon, 30 Jul 2007 15:55:30 +0300 Subject: Detecting __future__ features In-Reply-To: References: Message-ID: On 2007-07-30, at 15:29, Steven D'Aprano wrote: > How would one tell at runtime if a particular feature has been > enabled by > the "from __future__ import thing" statement? > > (I don't especially care whether the feature in question has been > enabled > via an explicit call to import, or because it has become the default.) > > Is there any general mechanism? You probably have to care about imports vs. language defaults. But it's not very difficult. For imports you can use __future__ to help you. If your namespace contains a feature you want to check for and it is identical to the same feature in __future__, then the code has used from __future__ import feature. You could probably try something like this: import __feature__ feature = "division" if globals().get(feature, None) == __future__.__dict__[feature]: print "Bingo!" You can probably figure out how to use sys.version_info to check whether the current Python version is higher than the one specified in a feature line: import __future__ import sys if sys.version_info >= __future__.division.mandatory: print "Bingo! Two in a row!" Check the __future__ docstrings for more information. -- [ ars at iki.fi <*> Antti Rasinen ] This drone-vessel speaks with the voice and authority of the Ur-Quan. From hniksic at xemacs.org Fri Jul 13 12:57:14 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 13 Jul 2007 18:57:14 +0200 Subject: os.wait() losing child? References: <4694903B.8000105@cosc.canterbury.ac.nz> <87bqehg5v1.fsf@mulj.homelinux.net> <873azsn6ca.fsf@mulj.homelinux.net> Message-ID: <87vecokzrp.fsf@mulj.homelinux.net> Jason Zheng writes: >>> Nope it still doesn't work. I'm running python 2.4.4, tho. >> That explains it, then, and also why greg's code didn't work. You >> still have the option to try to run 2.5's subprocess.py under 2.4. > Is it more convenient to just inherit the Popen class? You'd still need to change its behavior to not call _cleanup. For example, by removing "your" instances from subprocess._active before chaining up to Popen.__init__. > I'm concerned about portability of my code. It will be run on > multiple machines with mixed Python 2.4 and 2.5 environments. I don't think there is a really clean way to handle this. From kar1107 at gmail.com Tue Jul 3 14:53:44 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 03 Jul 2007 11:53:44 -0700 Subject: object references/memory access In-Reply-To: <4689e535$0$23896$9b622d9e@news.freenet.de> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1183407411.397142.304790@e16g2000pri.googlegroups.com> <1183417108.245203.158830@x35g2000prf.googlegroups.com> <4689e535$0$23896$9b622d9e@news.freenet.de> Message-ID: <1183488824.131448.62720@x35g2000prf.googlegroups.com> On Jul 2, 10:57 pm, "Martin v. L?wis" wrote: > >>> I have found the stop-and-go between two processes on the same machine > >>> leads to very poor throughput. By stop-and-go, I mean the producer and > >>> consumer are constantly getting on and off of the CPU since the pipe > >>> gets full (or empty for consumer). Note that a producer can't run at > >>> its top speed as the scheduler will pull it out since it's output pipe > >>> got filled up. > > > On a single core CPU when only one process can be running, the > > producer must get off the CPU so that the consumer may start the > > draining process. > > It's still not clear why you say that the producer can run "at its top > speed". You seem to be suggesting that in such a setup, the CPU would > be idle, i.e. not 100% loaded. Assuming that the consumer won't block > for something else, then both processes will run at their "top speed". > Of course, for two processes running at a single CPU, the top speed > won't be the MIPs of a single processor, as they have to share the CPU. > > So when you say it leads to very poor throughput, I ask: compared > to what alternative? Let's assume two processes P and C. P is the producer of data; C, the consumer. To answer your specific question, compared to running P to completion and then running C to completion. The less optimal way is p1-->c1-- >p2-->c2-->..... p_n---c_n where p1 is a time-slice when P is on CPU, c1 is a time-slice when c1 is on CPU. If the problem does not require two way communication, which is typical of a producer-consumer, it is a lot faster to allow P to fully run before C is started. If P and C are tied using a pipe, in most linux like OS (QNX may be doing something really smart as noted by John Nagle), there is a big cost of scheduler swapping P and C constantly to use the CPU. You may ask why? because the data flowing between P and C, has a small finite space (the buffer). Once P fills it; it will block -- the scheduler sees C is runnable and puts C on the CPU. Thus even if CPU is 100% busy, useful work is not 100%; the process swap overhead can kill the performance. When we use an intermediate file to capture the data, we allow P to run a lot bigger time-slice. Assuming huge file-system buffering, it's very much possible P gets one-go on the CPU and finishes it's job of data generation. Note that all these become invalid, if you have a more than one core and the scheduler can keep both P and C using two cores simulateanously. If that is the case, we don't incur this process-swap overhead and we may not see the stop-n-go performance drop. Thanks, Karthik > > Regards, > Martin From iferca at gmail.com Sun Jul 22 16:43:03 2007 From: iferca at gmail.com (=?ISO-8859-1?Q?Israel_Fern=E1ndez_Cabrera?=) Date: Sun, 22 Jul 2007 16:43:03 -0400 Subject: Re-running unittest Message-ID: Hi I'm writing some code that automatically execute some registered unit test in a way to automate the process. A sample code follows to illustrate what I'm doing: class PruebasDePrueba(unittest.TestCase): def testUnTest(self): a = 2 b = 1 self.assertEquals(a, b) def runTests(): loader = unittest.TestLoader() result = unittest.TestResult() suite = loader.loadTestsFromName("import_tests.PruebasDePrueba") suite.run(result) print "Errores: ", len(result.errors) print "Fallos: ", len(result.failures) if __name__ == "__main__": runTests() raw_input("Modify [fix] the test and press ENTER to continue") The code executes the tests from the class PruebasDePrueba, as the user to "fix" the failing test and then executes the tests again after ENTER is pressed. The test's initial state is "fail" so, equaling the values of a or b in the second execution I wait the test does not fails again, but it does. I've changed the original code in very different ways trying to figure out what is wrong with it but no success The problem is not reproduced if instead of loading the test from the TestCase (import_tests.PruebasDePrueba) they are loaded referring the container module and this behaves like this because I wrote a class that inherits from unittest.TestLoader abd re-defines the loadTestsFromModule(module) then every time this method is called, the module is reloaded via "reload" python's function. I would like to do the same with TestCases. I have written this problem to several other python lists but I have not received any answer, hope this time is different, I'd like to thaks in advance, regards -- ____________________ Israel Fdez. Cabrera iferca at gmail.com . 0 . . . 0 0 0 0 From zentraders at gmail.com Mon Jul 30 19:31:04 2007 From: zentraders at gmail.com (Zentrader) Date: Mon, 30 Jul 2007 23:31:04 -0000 Subject: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why? In-Reply-To: <1185814119.604341.204100@z28g2000prd.googlegroups.com> References: <1185791793.141118.44080@x35g2000prf.googlegroups.com> <5h5ufoF3hmufcU4@mid.uni-berlin.de> <1185814119.604341.204100@z28g2000prd.googlegroups.com> Message-ID: <1185838264.101543.246150@g12g2000prg.googlegroups.com> > from decimal import Decimal > > In [21]: a = Decimal() > > In [22]: class Decimal(object): > ....: pass > ....: > > In [23]: b = Decimal() > > In [24]: a - b Perhaps I don't understand what you are doing here, but on line 22 you overload Decimal. If you just have a = Decimal() b = Decimal() print a-b yields 0. decimal.Decimal() can be subtracted from decimal.Decimal(). decimal.Decimal() can not be subtracted from class Decimal(object). I would assume that they are different types. Using the original code, print type(a), type(b). From noah at noah.org Sun Jul 15 13:14:31 2007 From: noah at noah.org (Noah) Date: Sun, 15 Jul 2007 10:14:31 -0700 Subject: Python Subprocess module In-Reply-To: References: Message-ID: <1184519671.315474.132910@m37g2000prh.googlegroups.com> On Jul 13, 2:15 pm, Dave Sampson wrote: > hey folks, > > A simple question hopefully. despite all my searching I have not found a > satisfactory response. > > The goal. Interact with a command line program. Simple enough, but the > key is INTERACT. You need Pexpect. > So then I went with Popen and such... which then led to the subprocess > module. I can create the object and read a few lines of output. but if I go too > far then the program hangs. the number of lines will differ depandening > on many function including the format of an input file so I can;t > hardcode how many lines to read. There is nothing you can do about this when using a pipe. This is because stdio will change the type of buffering when sending stdout and stderr to a pipe. From the client side there is no way you can change the buffer mode (you CAN change the mode, but it only changes it on YOUR side of the pipe -- not your child application's side). > and nothing seems to get the program going again for I still cant; read > past the same point in the standard output. then I have to kill and > start over. Your child application is waiting for you, but you can't see what it wrote becuase it has not filled or flushed the output buffer. When a program write to stdout and it is connected to a TTY it will automatically flush the output buffer when it writes a newline (or, rather, the clib will do this). But when writing to a pipe it will automatically use block buffering and will only flush the buffer when it is full. It's not very complicated, but it can be very confusing at first. It is also surprising that this behavior cannot be changed by the parent application. > So the next approach included looking atPexpect, which got realy > confusing realy fast and despite running fedora core and python 2.4.4 I > would like my application to be cross platform and there is noPexpect > for Windows That I can see. You are going to need something like Pexpect that uses pseudo-ttys (pty). Pexpect works under Cygwin on Windows, but not under the native Windows Python. Email me if you have questions about Pexpect and I'll try to help you. Yours, Noah From pydecker at gmail.com Sat Jul 7 19:37:56 2007 From: pydecker at gmail.com (Peter Decker) Date: Sat, 7 Jul 2007 19:37:56 -0400 Subject: Restarting a Python Application In-Reply-To: <94ccbe710707071511o3beee718wc12f15082b3c6e18@mail.gmail.com> References: <1183498045.092504.229250@m36g2000hse.googlegroups.com> <94ccbe710707071511o3beee718wc12f15082b3c6e18@mail.gmail.com> Message-ID: On 7/7/07, Kelvie Wong wrote: > Ugh.. this would be a repost for the OP, but I forgot to hit "reply to > all" again. Imagine if you wrote applications where the default behavior did not do what was needed 99% of the time: how long do you think you'd be in business? The default behavior of replying to the original sender instead of the list makes no sense. I've read the purist arguments against replying to the list, but I subscribed to a *list*, not an individual sender. I know that this post is pointless, since the people who run this list seem to care more about abstract and misdirected notions of purity than making things as useful and intelligent as possible, but after seeing dozens of "please keep your reply on list" responses recently, I had to vent. -- # p.d. From nogradi at gmail.com Tue Jul 3 07:40:41 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 3 Jul 2007 13:40:41 +0200 Subject: 15 Exercises to Know A Programming Language In-Reply-To: <1183459662.072934.215470@k79g2000hse.googlegroups.com> References: <1183456696.168214.114900@o61g2000hsh.googlegroups.com> <5eumhhF39v66mU2@mid.uni-berlin.de> <1183459662.072934.215470@k79g2000hse.googlegroups.com> Message-ID: <5f56302b0707030440g3a8a4cecrb8ba7fec45eb82c6@mail.gmail.com> > > > "Write a program that takes as its first argument one of the words > > > 'sum,' 'product,' 'mean,' or 'sqrt' and for further arguments a > > > series of numbers. The program applies the appropriate function to > > > the series." > > > > > My solution so far is this: > > > > >http://dpaste.com/13469/ > > > > > I would really like some feedback. Is this a good solution? is it > > > efficient? robust? what could be improved? any not looking for a > > > revised solution, hints on what to improve are also very welcome. > > > > Don't use `eval()` if it is not absolutely necessary. Especially if the > > input comes from a user it's a security hole. `float()` is the function > > to use here. > > > > `mean()` does not work as you try to divide a list by a number. > > > > Thanks for the feedback. I have posted a revised version here (http:// > dpaste.com/13474/) where mean works. The reason I use eval is I want > it to work for complex numbers too, but I guess i could check for the > presence of a "j" in the arguments instead. Hi, if I invoke your program without arguments an uncaught exception is raised. Wouldn't it be better to inform the user that an argument is expected? See http://docs.python.org/tut/node10.html From aleax at mac.com Thu Jul 5 23:19:23 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 5 Jul 2007 20:19:23 -0700 Subject: Where is the syntax for the dict() constructor ?! References: <468D1D9D.6060002@gmail.com> <468D3445.2060408@gmail.com> Message-ID: <1i0snor.ir5kakobtfkrN%aleax@mac.com> Neil Cerutti wrote: > Besides, a string is an excellent epresentation for a zip code, > since arithmetic upon them is unthinkable. Absolutely! Excel, unless you remedied that later with a column operation, would turn some East Coast zipcodes into 3- and 4-digit numbers (dropping the leading 0s), exactly because it's so obtuse as to try to "treat as numbers" entries that are all-digits. Funny enough, that very issue took at least 5 minutes of lecture time at a recent lecture in a course on "statistical approaches to data mining" that I'm following (hopefully it will turn to slightly more advanced issues soon:-): Excel (!) and R are the two "recommended" programs for the course, and substantial parts of the lecture times so far have been spent illustrating various foibles of each. Still, another guy who's taking the class had a funny and relevant war story: at one point a company he was working for did a mass mailing (paper mail)... and big bag of the mails was returned as undeliverable by a pretty peeved US Post Office... the "mail merge" they had done apparently involved Excel (or some other spreadsheet program) at some point, and many East Coast zipcodes had indeed been truncated (which messes with USPO's automatic system and thus is NOT tolerated, at least in bulk mail)...!-) Alex From steven.bethard at gmail.com Thu Jul 12 18:26:08 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 12 Jul 2007 16:26:08 -0600 Subject: Function parameter type safety? In-Reply-To: <1184277163.803229.318660@g4g2000hsf.googlegroups.com> References: <1184277163.803229.318660@g4g2000hsf.googlegroups.com> Message-ID: Robert Dailey wrote: > Is there a way to force a specific parameter in a function to be a > specific type? For example, say the first parameter in a function of > mine is required to be a string. If the user passes in an integer, I > want to notify them that they should pass in a string, not an integer. In Python, you generally don't want to do this. If I have code like:: def foo(x): if not isinstance(x, basestring): raise ValueError('x must be a string') return x.split() then if someone creates a string-like object that doesn't subclass from basestring, my code raises an exception even though the string-like object had a .split() method and would have worked perfectly. If you really feel like you need to give a specific error message, you could write it instead like:: def foo(x): try: split = x.split except AttributeError: raise ValueError('x needs to have a split() method') return split() But generally there's no reason to do that because the AttributeError itself would have said almost exactly the same thing. Long story short: checking parameter types is un-Pythonic. Don't do it. STeVe From steve at REMOVE.THIS.cybersource.com.au Mon Jul 23 19:28:51 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 24 Jul 2007 09:28:51 +1000 Subject: Maintaining leading zeros with the lstrip string function? References: Message-ID: On Mon, 23 Jul 2007 15:21:20 -0400, Miles wrote: > Also, use raw strings ( r'\path\to\file' ) to avoid problems > with backslashes being interpreted in strings. Not quite. Raw strings are designed for building regular expressions, not file names. Consequently, there are still a few cases where they won't help you, e.g.: >>> fname = 'mydoc.txt' >>> fname = r'C:\My Documents\Something\' + fname File "", line 1 fname = r'C:\My Documents\Something\' + fname ^ SyntaxError: EOL while scanning single-quoted string A better solution is to remember that Windows will accept a forward slash anywhere it expects a backslash: >>> fname = 'C:/My Documents/Something/' + fname (But again... the better, platform independent way to do this is with os.path.) -- Steven. From irmen.NOSPAM at xs4all.nl Mon Jul 2 20:26:43 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 03 Jul 2007 02:26:43 +0200 Subject: Tiny/small/minimalist Python? In-Reply-To: <7xmyyeizf8.fsf@ruckus.brouhaha.com> References: <1183332951.122782.212720@o11g2000prd.googlegroups.com> <7xved3satm.fsf@ruckus.brouhaha.com> <1183389420.175712.59460@z28g2000prd.googlegroups.com> <7xmyyeizf8.fsf@ruckus.brouhaha.com> Message-ID: <468997c7$0$327$e4fe514c@news.xs4all.nl> Paul Rubin wrote: > rtk writes: >> FYI.. I wanted a simple version of Python to run on an ancient DEC >> Alpha box. I got VMS Python 2.5 up and running but it is too slow to >> use. It takes *minutes* to get the interpreter prompt after typing >> 'python'! > > Something is wrong. Maybe it's trying to DNS itself and timing out, > or something like that. Something is definately wrong. Back in the days my port of Python to the Commodore Amiga machine ran quite comfortably on a 50 mhz CPU with 4 Mb of RAM. (ok ok it was Python 1.5.2, that has to be said). Python started in about 5 seconds on that Amiga if I remember correctly. I'm quite sure your 'ancient' DEC Alpha box is way more powerful than my Amiga back then. --Irmen From steve at holdenweb.com Fri Jul 27 07:52:09 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 27 Jul 2007 07:52:09 -0400 Subject: Compile python with Mingw In-Reply-To: <1185533861.522783.268580@o61g2000hsh.googlegroups.com> References: <1185533861.522783.268580@o61g2000hsh.googlegroups.com> Message-ID: Ninereeds wrote: > fdu.xiaojf at gmail.com wrote: > >> I don't have VS2003, so I think I may compile both pymol >> and python with mingw. > > Sorry I can't help with mingw, but Microsoft has released a free > version of VC2005, which should be binary compatible with VC2003, I'd > have thought. Of course that means going through the Windows > validation, and the downloads pretty big, plus you may need the > platform SDK too. > You are wrong about the compatibility. You can't compile a library with VC 2005 and run it with a Python compiled with VC 2003. http://www.z3lab.org/sections/blogs/philipp-weitershausen/2007_07_26_cheap-binary-windows gives some information about compiling Zope packages with C extensions in them using Mingw, this may help the OP. 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 http Sun Jul 8 19:54:42 2007 From: http (Paul Rubin) Date: 08 Jul 2007 16:54:42 -0700 Subject: What is the most efficient way to test for False in a list? References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> Message-ID: <7x7ipajvst.fsf@ruckus.brouhaha.com> lex writes: > list = [1, True, True, False, False, True] > status = True > for each in list: > status = status and each > > but what is your best way to test for for False in a list? status = all(list) From martin at v.loewis.de Tue Jul 10 03:47:19 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 10 Jul 2007 09:47:19 +0200 Subject: Error when trying to write unicode xml to zipfile In-Reply-To: <4693346A.4030707@web.de> References: <1184022684.557693.111890@n60g2000hse.googlegroups.com> <4693346A.4030707@web.de> Message-ID: <46933987.6010703@v.loewis.de> > Unless, obviously, you were serialising to a non-utf8 encoding. But since the > "toxml()" method seems to return unicode here (which sounds surprising), I > expect it a) to provide no XML declaration at all or b) to be broken anyway. Or c) the user forgot to specify the encoding= parameter in toxml(). Regards, Martin From spamtrap at dot-app.org Thu Jul 26 11:43:48 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Thu, 26 Jul 2007 11:43:48 -0400 Subject: I am giving up perl because of assholes on clpm -- switching to Python References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> <878x93ivqx.fsf@benfinney.id.au> Message-ID: Ben Finney writes: > Martha_Jones at tx.net writes: > >> Python is a better language, with php support, anyway, but I am fed >> up with attitudes of comp.lang.perl.misc. > > Please, if you must fred the troll, drop comp.lang.python from the > discussion (i.e. post trplies only to the newsgroup this message > relates to). Grow up. This troll doesn't relate to *either* group. Redirecting responses towards a group you don't read is just as trollish as the original. Ignoring it is best, but if you *must* feed it, respond to all the listed groups. Encouraging the troll while at the same time foisting it off upon someone else is just as rude as the original. sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From Larry.Martell at gmail.com Thu Jul 19 08:32:02 2007 From: Larry.Martell at gmail.com (Larry.Martell at gmail.com) Date: Thu, 19 Jul 2007 12:32:02 -0000 Subject: UDP broadcast over a specific interface Message-ID: <1184848322.796960.121950@q75g2000hsh.googlegroups.com> I am trying to send UDP broadcast packets over a specific interface and I am having trouble specifying the interface: host='192.168.28.255' sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('',0)) sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(host)) socket.error: (49, "Can't assign requested address") What am I doing wrong? How can I force my broadcast packets to go out a specific interface? TIA! -larry From cyberco at gmail.com Sun Jul 1 15:49:44 2007 From: cyberco at gmail.com (cyberco) Date: Sun, 01 Jul 2007 19:49:44 -0000 Subject: The best platform and editor for Python In-Reply-To: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> Message-ID: <1183319384.952570.195830@q69g2000hsb.googlegroups.com> There is one tool you won't be able to live without: iPython (no, it's not an Apple product, but it would be worth waiting in line for 3 days for) http://ipython.scipy.org/moin/ From jan.m.danielsson at gmail.com Sun Jul 8 16:23:20 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Sun, 08 Jul 2007 22:23:20 +0200 Subject: "Empty" text Message-ID: <469147b8$1@griseus.its.uu.se> Hello all, I'm using mod_python+ElementTree to build XHTML pages. But I stumbled across this problem: -------------------- def foo(req, desc = None): ... tr = ET.SubElement(tbl, "tr") th = ET.SubElement(tr, "th") th.text = "Description" td = ET.SubElement(tr, "td") ta = ET.SubElement(td, "textarea", name="desc", rows="8", cols="64") if desc is None: desc = '' ta.text = desc -------------------- The problem is that this generates the following code: Description I understand the opitmization ElementTree is performing; but it seems there are cases when it is not the proper thing to do. Is it possible to force ElementTree to output the XHTML code I need it to? -- Kind regards, Jan Danielsson From vishak.1981 at gmail.com Tue Jul 31 16:28:59 2007 From: vishak.1981 at gmail.com (Maximus Decimus) Date: Tue, 31 Jul 2007 20:28:59 -0000 Subject: Extending Python by Adding Keywords & Data types Message-ID: <1185913739.879602.212950@w3g2000hsg.googlegroups.com> HI all, 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. It would be really great if anybody could guide me as which files and modules I need to look to make these additions and enhancements to the existing python version. Thanks a lot in advance and your help is really appreciated. Vishak From nick at craig-wood.com Wed Jul 11 16:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 11 Jul 2007 15:30:03 -0500 Subject: bool behavior in Python 3000? References: <5ficp9F3cram2U2@mid.individual.net> <469472f4$0$1293$9b622d9e@news.freenet.de> <1184140795.974059.302830@22g2000hsm.googlegroups.com> <9v4li.8359$MV6.308@trnddc01> Message-ID: Alan Isaac wrote: > Miles wrote: > > What boolean operation does '-' represent? > > Complementation. > And as usual, a-b is to be interpreted as a+(-b). > In which case the desired behavior is > False-True = False+(-True)=False+False = False If you want to do algebra with bools in python then use the logical operators (and or not) and not the arithmetical operators. Eg >>> False or not True False -- Nick Craig-Wood -- http://www.craig-wood.com/nick From donn at u.washington.edu Thu Jul 5 15:24:37 2007 From: donn at u.washington.edu (Donn Cave) Date: Thu, 05 Jul 2007 12:24:37 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> Message-ID: In article <1183575597.272150.152200 at w5g2000hsg.googlegroups.com>, Paul Boddie wrote: > However, it's interesting to consider the work that sometimes needs to > go in to specify data structures in some languages - thinking of ML > and friends, as opposed to Java and friends. The campaign for optional > static typing in Python rapidly became bogged down in this matter, > fearing that any resulting specification for type information might > not be the right combination of flexible and powerful to fit in with > the rest of the language, and that's how we really ended up with PEP > 3107: make the semantics vague and pretend it has nothing to do with > types, thus avoiding the issue completely. I missed the campaign for optional static typing, must have been waged in the developer list. Unless it was not much more than some on-line musings from GvR a year or two ago. I don't see how it could ever get anywhere without offending a lot of the Python crowd, however well designed, so I can see why someone might try to sneak it past by pretending it has nothing to do with types. But he didn't -- look at the examples, I think he rather overstates the potential for static typing applications. Donn Cave, donn at u.washington.edu From hong2221 at gmail.com Wed Jul 25 03:10:39 2007 From: hong2221 at gmail.com (hong2221) Date: Wed, 25 Jul 2007 07:10:39 -0000 Subject: How to create a single executable of a Python program In-Reply-To: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> References: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> Message-ID: <1185347439.951960.126120@o61g2000hsh.googlegroups.com> On Jul 25, 2:34 am, NicolasG wrote: > Dear fellows, > > I'm trying to create a executable file using py2exe . Unfortunately > along with the python executable file it also creates some other files > that are needed in order to the executable be able to run in a system > that doesn't have Python installed. Can some one guide me on how can I > merge all this files created by py2exe in a single exe file ? If I > have a python program that uses an image file I don't want this image > file to be exposed in the folder but only to be accessible through the > program flow.. > > Regards, > Nicolas. I would like to konw as well. Thanks. From steve at holdenweb.com Tue Jul 31 12:42:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 31 Jul 2007 12:42:24 -0400 Subject: standalone process to interact with the web In-Reply-To: <1185899130.331170.151980@e16g2000pri.googlegroups.com> References: <1185899130.331170.151980@e16g2000pri.googlegroups.com> Message-ID: 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 - http://wwwsearch.sourceforge.net/mechanize/ With mechanize and its partner ClientForm you can rule the web world ;-) 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 http Wed Jul 25 21:44:37 2007 From: http (Paul Rubin) Date: 25 Jul 2007 18:44:37 -0700 Subject: Keyword argument 'from'; invalid syntax References: Message-ID: <7xabtkndkq.fsf@ruckus.brouhaha.com> "Kai Kuehne" writes: > >>> d = {'person': 'user', 'from': vorgestern} > >>> magnolia.bookmarks_find(d) > : bookmarks_find() takes exactly 1 > argument (2 given) > > I'm out of ideas so help is greatly appreciated! Try magnolia.bookmarks_find(**d) From snezhana.manoah at stilog.com Mon Jul 9 09:12:42 2007 From: snezhana.manoah at stilog.com (Snezhana) Date: Mon, 09 Jul 2007 15:12:42 +0200 Subject: TypeError: can't multiply sequence to non-int References: 20031103151451.BC13.PYTHON@essene.com Message-ID: <4692344A.80700@stilog.com> From skip at pobox.com Wed Jul 18 12:34:25 2007 From: skip at pobox.com (Skip Montanaro) Date: Wed, 18 Jul 2007 16:34:25 +0000 (UTC) Subject: Mouse/keyboard watcher? References: <18078.10372.792537.288757@montanaro.dyndns.org> Message-ID: > Someone, I thought from this list or maybe python-dev, told me about > a newer open source application in the same space which is more > portable and actively maintained/developed. Alas, I can't recall > the name... Found it: workrave (http://www.workrave.org/). Sorry for the noise. Skip From cito at online.de Sun Jul 15 04:52:54 2007 From: cito at online.de (Christoph Zwerschke) Date: Sun, 15 Jul 2007 10:52:54 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: <1184345588.791872.79010@d55g2000hsg.googlegroups.com> References: <1183863713.876365.111820@57g2000hsv.googlegroups.com> <1184239885.828717.271410@r34g2000hsd.googlegroups.com> <1184258925.321462.50270@k79g2000hse.googlegroups.com> <1184345588.791872.79010@d55g2000hsg.googlegroups.com> Message-ID: samwyse wrote: > NewStyle.__name__ = old.__class__.__name__ Simple, but that does the trick! > new.__dict__ = old.__dict__.copy() Unfortunately, that does not work, since the attributes are not writeable and thus do not appear in __dict__. But my __getattr__ solution does not work either, since the attributes are set to None when initialized, so __getattr__ is never called. Need to think about this point some more... Anyway, the beer is on me ;-) -- Chris From steve at holdenweb.com Wed Jul 25 18:16:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Jul 2007 18:16:11 -0400 Subject: TypeError: 'int' object is not callable for max(2,3) In-Reply-To: <266557d0707251457t5a9237abv2118ffebf58290cc@mail.gmail.com> References: <266557d0707251457t5a9237abv2118ffebf58290cc@mail.gmail.com> Message-ID: Arash Arfaee wrote: > Hi all, > I have a problem. if I enter max(2,3) before I run my program in command > line it returns 3. However if I start to debug my program, I have this > error: > > [Dbg]>>> max(2,3) > Traceback (most recent call last): > File "", line 1, in > TypeError: 'int' object is not callable > > Any idea what should be the reason? > You have assigned an integer value to the name max, thereby shadowing the builtin 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 steve at holdenweb.com Thu Jul 5 08:32:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Jul 2007 08:32:33 -0400 Subject: MethodType/FunctionType and decorators In-Reply-To: <1183626989.983470.94950@o61g2000hsh.googlegroups.com> References: <1183589529.198694.109440@m36g2000hse.googlegroups.com> <1183591053.434640.119550@o61g2000hsh.googlegroups.com> <1i0qoq9.u1fu2g63fkmxN%aleax@mac.com> <1183623479.913816.301230@g4g2000hsf.googlegroups.com> <1183626989.983470.94950@o61g2000hsh.googlegroups.com> Message-ID: Alex Popescu wrote: > On Jul 5, 11:17 am, Michele Simionato > wrote: >> On Jul 5, 3:41 am, a... at mac.com (Alex Martelli) wrote: >> >>> >> Alex already explained everything beautifully. I will just add a link >> to >> the definite guide to descriptors:http://users.rcn.com/python/download/Descriptor.htm >> >> Michele Simionato >> >> (who spent lot of brain cycles studying descriptors *before* that >> guide was written :-() > > Guys, I appreciate a lot your help and explanations. It looks like I > have to read/play a bit more as some of the terms/ideas are pretty new > to me (coming to Python with a 10 years Java bag, and only with a > small dynlang bag - Ruby, Perl). > > Once again thanks, > Please also realise that for someone new to the language you have dived right into the nitty gritty. This isn't necessarily a bad way to learn, but it does mean that there's a lot of background to assimilate as you go along. Good luck with your studies. 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 Jul 24 09:25:00 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 24 Jul 2007 06:25:00 -0700 Subject: some parts of wxPython broken on Mac In-Reply-To: References: <1185268611.681037.298490@m37g2000prh.googlegroups.com> Message-ID: <1185283500.988203.173430@22g2000hsm.googlegroups.com> On Jul 24, 6:14 am, Steve Holden wrote: > ahlongxp wrote: > > Sorry, I know this is not the most appropriate place to talk about > > wxPython. > > But I can't have access to wxPython mail list page(because I don't pay > > enough). > > > I downloaded python2.5 and wxPython 2.8.4.0 from pythonmac.org and > > installed them into one of my friends' Mac 10.4.8(intel) > > and I found wx.lib.flatnotebook and wx.xrc were broken(which are quite > > OK under both Linux and Windows). > > > because I don't have the machine, I can't give more details. > > > I hope someone will be good enough to check out these problems. > > I'm not a Mac user, so I can't answer the technical issues. But I *do* > know that the wxPython users list is just as open as python-list, so I > see no reason why you shouldn't point these issues out there. Cost > shouldn't be a factor. > > If you do so, however, you should give a little more information than > that the components "are broken". That won't help anyone isolate an 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 ------------- Yeah, you need to post to the wxPython group here: http://www.wxpython.org/maillist.php There's an entire slew of wxPython gurus on there that use Macs, Windows, and Linux on there and will be better able to help you if you're more descriptive. Mike From news2 at mystrobl.de Tue Jul 17 03:34:22 2007 From: news2 at mystrobl.de (Wolfgang Strobl) Date: Tue, 17 Jul 2007 09:34:22 +0200 Subject: Can a low-level programmer learn OOP? References: Message-ID: <7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com> Steve Holden : >I'm happy you are proceeding with so little trouble. Without wishing to >confuse you, however, I should point out that this aspect of Python has >very little to do with its object-orientation. There was a language >called Icon, for example, 20 years ago, that used similar semantics but >wasn't at all object-oriented. Actually, there was a language called SNOBOL, 40 years ago, that used similar semantics, developed by Griswold et al. Its object model was remarkably similar to that of Python without classes. And it even had dictionaries (called "tables") :-). For an explaination of the concept "variable" in SNOBOL see SNOBOLs powerfull patterns still shine, compared to Pythons clumsy regular expressions. I've used the language a lot in the past, first on the mainframe (SPITBOL on System/360), later on the PC (Catspaws SNOBOL4 &SPITBOL). When I switched to Python, it wasn't because of the expressiveness of the language, but of the rich library ("batteries included") and the IMO elegant syntax, i.e. blocks by identation. Icon came later. Griswold developed Icon as a successor to SNOBOL, constructing it around the concept of generators and co-expressions. I didn't like it. -- Thank you for observing all safety precautions From xellzhang at gmail.com Sun Jul 8 14:18:36 2007 From: xellzhang at gmail.com (Xell Zhang) Date: Mon, 9 Jul 2007 02:18:36 +0800 Subject: Is there anyone familiar with pybloom (bloom filter in python)? Message-ID: Hello, I found pybloom module from http://www.imperialviolet.org/pybloom.html and tried to use it for my crawler:) I want to use it to store the URLs which have been crawled. But when I insert a URL string I always get a warning and wrong result... My testing code is quite simple: from pybloom import CountedBloom cb = CountedBloom(800000, 4) cb.insert("AAA") print cb.__contains__("BBB") Warning: E:\EclipseWorkspace\demo\src\pybloom.py:74: DeprecationWarning: 'I' format requires 0 <= number <= 4294967295 b = [ord(x) for x in struct.pack ('I', val)] I will get warning when running the code above. The output is "1" which means "BBB" is in the set. But actually it is not... When I use integer for testing it seems right. I am not familiar with arithmetic and I don't know if I wrote something wrong. Can anyone help me? Thanks! -- Zhang Xiao Junior engineer, Web development Ethos Tech. http://www.ethos.com.cn -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Mon Jul 2 15:37:13 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 02 Jul 2007 14:37:13 -0500 Subject: Rappresenting infinite In-Reply-To: <1183403549.523918.262500@m36g2000hse.googlegroups.com> References: <1182940919.351011.267020@n2g2000hse.googlegroups.com> <1183403549.523918.262500@m36g2000hse.googlegroups.com> Message-ID: avassalotti at gmail.com wrote: > float('inf') works well, no? > > >>> inf = float('inf') > >>> inf / inf > nan > >>> -inf > -inf > >>> inf / 0 > ZeroDivisionError: float division > >>> 1 / inf > 0.0 > >>> 0 * float('inf') > nan It is not cross-platform. The parsing of strings into floats and the string representation of floats is dependent on your system's C library. For these special values, this differs across platforms. Your code won't work on Windows, for example. Fortunately, it doesn't matter all that much (at least for those who just need to create such values; parsing them from files is another matter) since infs and nans can be constructed in a cross-platform way (at least for IEEE-754 platforms where these values make sense). inf = 1e200 * 1e200 nan = inf / inf -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From thenault at gmail.com Fri Jul 13 05:37:56 2007 From: thenault at gmail.com (syt) Date: Fri, 13 Jul 2007 09:37:56 -0000 Subject: Tool for finding external dependencies In-Reply-To: <1183945183.147231.120180@z28g2000prd.googlegroups.com> References: <1183945183.147231.120180@z28g2000prd.googlegroups.com> Message-ID: <1184319476.230168.310350@q75g2000hsh.googlegroups.com> On Jul 9, 3:39 am, Rob Cakebread wrote: > Hi, > > I need to find external dependencies for modules (not Python standard > library imports). > > Currently I usepylintand manually scan the output, which is very > nice, or usepylint's--ext-import-graph option to create a .dot file > and extract the info from it, but either way can take a very long > time. > > I'm aware of Python's modulefinder.py, but it doesn't find external > dependencies (or at least I don't know how to make it do them). notice that you can launch pylint in the following way to disabling everything but dependencies analysis : :: pylint --enable-checker=imports yourproject this will disable all others checkers and you may gain a signifiant speedup. -- Sylvain From vedrandekovic at v-programs.com Sun Jul 1 12:20:50 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Sun, 01 Jul 2007 09:20:50 -0700 Subject: how to send files via bluetooth with python to a mobile In-Reply-To: <1183305873.736724.116680@c77g2000hse.googlegroups.com> References: <1183294323.556314.293860@m36g2000hse.googlegroups.com> <1183305873.736724.116680@c77g2000hse.googlegroups.com> Message-ID: <1183306850.712226.313800@m36g2000hse.googlegroups.com> vedrandeko... at v-programs.com je napisao/la: > Drex je napisao/la: > > Hi, > > > > I have been looking on the internet for some info about sending files > > from PC to a mobile phone (I have a nokia 6288) but I was not able to > > find anything. > > > > there is a lot of info how to transfer files from a symbian phone to a > > pc, but nothing about sending them in the oposite direction. > > > > would anybody point me to some resources on the topic? > > > > thanks, regards > > dz > > Hi, > > I'm not sure but try this: ( py_s60 ) > > http://sourceforge.net/projects/pyed/ > > regards, > > vedran Hi again, and also try this: http://sourceforge.net/projects/pys60 regards, vedran From robert.rawlins at thinkbluemedia.co.uk Wed Jul 4 05:55:04 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 4 Jul 2007 10:55:04 +0100 Subject: Which Python Version Message-ID: <009e01c7be21$6c83be80$458b3b80$@rawlins@thinkbluemedia.co.uk> Hello Chaps, Is there a command I can run to confirm which version of python I'm running? Another thing I've always wondered, should i be running my applications using './MyFile.py' or 'Python MyFile.Py' what are the benefits of each method? One thing I have noticed is that when I used 'Python MyFile.Py' my processor usage was a lot higher, is that normal? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From straton at lampsacos.demon.co.uk Sun Jul 29 13:06:18 2007 From: straton at lampsacos.demon.co.uk (Ken Starks) Date: Sun, 29 Jul 2007 18:06:18 +0100 Subject: UK Ordnance survey coordinates and Geocoding anyone ? Message-ID: Has anyone written a python wrapper around the (Windows) dll for converting between OSGB36 and ETRS89 coordinates ? The dll and an application are available from http://www.qgsl.co.uk as long as you register. Information, if you don't know what I'm taking about: ----------------------------------------------------- OSGB36 is the system system used on Ordnance survey maps, 'Eastings, Northings, and 'Height above sea level' (normally Newlyn). ETRS89 is the European variation of the standard Sat-Nav coordinates (GRS 1980) adjusted slightly to account for the continental drift of the European Plate away from the International average. You get 'Longitude' 'Latitude' and 'Height above the Ellipsoid. The Ordnance survey now __define__ OSGB36 in terms of ETRS89 and the algorithm implemented by the 'Grid Inquest' dll. Goodbye (most) Trig stations and Benchmarks! For an example of an OS map centered at a 1 metre accuracy gridpoint, (Buckingham Palace) go to: http://www.magic.gov.uk/website/magic/opener.htm?startTopic=maggb&xygridref=529115,179711&startScale=2500 From mensanator at aol.com Mon Jul 16 20:23:37 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 16 Jul 2007 17:23:37 -0700 Subject: In a dynamic language, why % operator asks user for type info? In-Reply-To: <1184631007.920803.147790@j4g2000prf.googlegroups.com> References: <1184631007.920803.147790@j4g2000prf.googlegroups.com> Message-ID: <1184631817.739077.273580@o61g2000hsh.googlegroups.com> On Jul 16, 7:10 pm, Karthik Gurusamy wrote: > Hi, > > The string format operator, %, provides a functionality similar to the > snprintf function in C. In C, the function does not know the type of > each of the argument and hence relies on the embedded % > specifier to guide itself while retrieving args. > > In python, the language already provides ways to know the type of an > object. > > So in > > output = '%d foo %d bar" % (foo_count, bar_count), > why we need to use %d? I'm thinking some general common placeholder, > say %x (currently it's hex..) could be used. > > output = '%x foo %x bar" % (foo_count, bar_count). > Since % by definition is string formatting, the operator should be > able to infer how to convert each of the argument into strings. You want all your numbers to print in hexadecimal? > > If the above is the case, we could've avoided all those exceptions > that happen when a %d is specified but say a string is passed. Who does that? > > Thanks, > Karthik From istvan.albert at gmail.com Thu Jul 26 19:25:36 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Thu, 26 Jul 2007 23:25:36 -0000 Subject: zip() function troubles Message-ID: <1185492336.850090.279190@b79g2000hse.googlegroups.com> Hello all, I've been debugging the reason for a major slowdown in a piece of code ... and it turns out that it was the zip function. In the past the lists that were zipped were reasonably short, but once the size exceeded 10 million the zip function slowed to a crawl. Note that there was memory available to store over 100 million items. Now I know that zip () wastes lots of memory because it copies the content of the lists, I had used zip to try to trade memory for speed (heh!) , and now that everything was replaced with izip it works just fine. What was really surprising is that it works with no issues up until 1 million items, but for say 10 million it pretty much goes nuts. Does anyone know why? is there some limit that it reaches, or is there something about the operating system (Vista in the case) that makes it behave like so? I've noticed the same kinds of behavior when trying to create very long lists that should easily fit into memory, yet above a given threshold I get inexplicable slowdowns. Now that I think about is this something about the way lists grow when expanding them? and here is the code: from itertools import izip BIGNUM = int(1E7) # let's make a large list data = range(BIGNUM) # this works fine (uses about 200 MB and 4 seconds) s = 0 for x in data: s += x print s # this works fine, 4 seconds as well s = 0 for x1, x2 in izip(data, data): s += x1 print s # this takes over 2 minutes! and uses 600 MB of memory # the memory usage slowly ticks upwards s = 0 for x1, x2 in zip(data, data): s += x1 print s From grahn+nntp at snipabacken.dyndns.org Wed Jul 4 11:11:24 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 4 Jul 2007 15:11:24 GMT Subject: Python's "only one way to do it" philosophy isn't good? References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <1183098228.517915.12140@q75g2000hsh.googlegroups.com> Message-ID: On Fri, 29 Jun 2007 12:53:49 -0400, Douglas Alan wrote: > Steve Holden writes: > >> "Python" doesn't *have* any refcounting semantics. > > I'm not convinced that Python has *any* semantics at all outside of > specific implementations. It has never been standardized to the rigor > of your typical barely-readable language standards document. > >> If you rely on the behavior of CPython's memory allocation and >> garbage collection you run the risk of producing programs that won't >> port tp Jython, or IronPython, or PyPy, or ... > >> This is a trade-off that many users *are* willing to make. > > Yes, I have no interest at the moment in trying to make my code > portable between every possible implementation of Python, since I have > no idea what features such implementations may or may not support. > When I code in Python, I'm coding for CPython. In the future, I may > do some stuff in Jython, but I wouldn't call it "Python" -- it'd call > it "Jython". Yeah, especially since Jython is currently (according to the Wikipedia article) an implementation of Python 2.2 ... not even *I* use versions that are that old these days! [I have, for a long time, been meaning to post here about refcounting and relying on CPython's __del__ semantics, but I've never had the energy to write clearly or handle the inevitable flame war. So I'll just note that my view on this seems similar to Doug's.] /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From danaraicute20 at gmail.com Fri Jul 20 22:10:16 2007 From: danaraicute20 at gmail.com (Dan C) Date: Fri, 20 Jul 2007 19:10:16 -0700 Subject: =?utf-8?B?4peZ4pa6RlJFRSBTYXRlbGxpdGUgVFYgb24geW91ciBQQ+KXhOKXmQ==?= Message-ID: <1184983816.407026.280320@m37g2000prh.googlegroups.com> Watch Free Satellite TV on your PC or Laptop Instantly Turn your Computer into a Super TV ? Watch all your favorite shows on your Computer & TV! ? Channels you can?t get any other place in the U.S.A! ? Watch from anywhere in the world! ? Save 1000's of $$$ over many years on cable and satellite bills ? INSTANT DOWNLOAD ? And much, much more! For More Details: http://tv-pc.xt.cx From nospam.themindstorm at gmail.com Sun Jul 22 07:20:41 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Sun, 22 Jul 2007 11:20:41 +0000 (UTC) Subject: code packaging References: <7xfy3jpem8.fsf_-_@ruckus.brouhaha.com> Message-ID: On 7/22/07, Ryan Ginstrom <> wrote: > Hi Alex: > > Do you develop for Windows? Are you looking to automate a build > process? > > The standard library's build module is distutils: > http://docs.python.org/lib/module-distutils.html > > As I mentioned in my post, I use a variety of third-party modules > (epydoc, py2exe, Inno Setup, AutoIt), which I glue together with my > own brew of python scripts. Since I develop mostly for Windows (except > for Web stuff, which I use Linux for), my build process is tailored to > that platform. > > Regards, > Ryan Ginstrom Thanks for following up on this. I am mostly used with a world where platform dependent builds are not very used (Java). My current attempt to learn Python is by creating a Python equivalent of the advanced Java testing framework TestNG (http://testng.org) -- but I will give more details about this when I'll be starting to have something more solid :-). However, due to my background where builds are required and there are some de facto build standards (Ant, Maven, etc.) I am starting to think I will be needing something similar while working on the tool I've mentioned. At this point I think that what I am interested in are how distros are build in Python world (no platform specific distros, but rather generic ones) and ways to automate the process of creating the distros (and probably running the framework internal tests etc.) My research lead me to distutils and/or setuptools, respectively SCon and/or buildutils. So I am wondering if I am looking in the right direction or do I need to do some more research :-). tia, ./alex -- .w( the_mindstorm )p. From cito at online.de Sun Jul 15 05:16:24 2007 From: cito at online.de (Christoph Zwerschke) Date: Sun, 15 Jul 2007 11:16:24 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: References: <1183863713.876365.111820@57g2000hsv.googlegroups.com> <1184239885.828717.271410@r34g2000hsd.googlegroups.com> <1184258925.321462.50270@k79g2000hse.googlegroups.com> <1184345588.791872.79010@d55g2000hsg.googlegroups.com> Message-ID: Christoph Zwerschke wrote: > Here is a simple solution, but it depends on the existence of the args > attribute that "will eventually be deprecated" according to the docs: Ok, here is another solution that does not depend on args: def PoliteException(e): E = e.__class__ class PoliteException(E): def __init__(self): for arg in dir(e): if not arg.startswith('_'): setattr(self, arg, getattr(e, arg)) def __str__(self): return str(e) + ", sorry!" PoliteException.__name__ = E.__name__ return PoliteException() try: unicode('\xe4') except Exception, e: p = PoliteException(e) assert p.reason == e.reason raise p From mike.klaas at gmail.com Mon Jul 23 14:48:19 2007 From: mike.klaas at gmail.com (Klaas) Date: Mon, 23 Jul 2007 11:48:19 -0700 Subject: class C: vs class C(object): In-Reply-To: <87hcnzqm13.fsf@mulj.homelinux.net> References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> <1184923127.990359.288920@d55g2000hsg.googlegroups.com> <87hcnzqm13.fsf@mulj.homelinux.net> Message-ID: <1185216499.870770.195060@i13g2000prf.googlegroups.com> On Jul 20, 5:47 am, Hrvoje Niksic wrote: > "sjdevn... at yahoo.com" writes: > > In particular, old-style classes are noticeably faster than > > new-style classes for some things (I think it was attribute lookup > > that surprised me recently, possibly related to the property > > stuff...) > > Can you post an example that we can benchmark? I ask because the > opposite is usually claimed, that (as of Python 2.4 or 2.5) new-style > classes are measurably faster. Why do people ask for trivial examples? $ cat classes.py class Classic: def __init__(self): self.attr = 1 class NewStyle(object): def __init__(self): self.attr = 1 $ python -m timeit -s 'from classes import *; c = Classic()' 'c.attr' :2: SyntaxWarning: import * only allowed at module level 1000000 loops, best of 3: 0.182 usec per loop $ python -m timeit -s 'from classes import *; c = NewStyle()' 'c.attr' :2: SyntaxWarning: import * only allowed at module level 1000000 loops, best of 3: 0.269 usec per loop New style classes have more machinery to process for attribute/method lookup, and are slower. There are very few algorithms for which attribute access is the bottleneck however (seeing as how easier they can be extracted out of inner loops into locals, which are much faster than attribute access on either type of class). Using old-style classes for performance is a useful hack for python perf wizards, but is a dangerous meme to perpetuate. -Mike From bj_666 at gmx.net Fri Jul 6 13:39:43 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Jul 2007 17:39:43 GMT Subject: How would I write this C code in Python? References: <1183743110.399675.180570@n60g2000hse.googlegroups.com> Message-ID: <5f7d2vF3b25tsU3@mid.uni-berlin.de> On Fri, 06 Jul 2007 17:31:50 +0000, DeveloperX wrote: > I am trying to figure out how to rewrite the following chunk of code > in Python: > > C source > [code] > typedef struct PF > { > int flags; > long user; > char*filename; > unsigned char buffer[MAXBUFFERSIZE]; > } PF; > > typedef BLOCK > { > PF * packdata; > } BLOCK; > > BLOCK* blocks; > [/code] > > My first idea was to create a class for PF and a class for BLOCK, but > I got lost somewhere along the lines. :\ > > Python Attempt: Please note that since I can't type TABs online > easily, I am using the @ character to represent TABs in the following > Python code. > [code] > class PF: > @def __init__(self): > @@self.flags, self.user = 0, 0 > @@self.filename = '' > @@self.buffer = [] > > class BLOCK: > @def __init__(self): > @@self.packdata = [] > > blocks = [] > [/code] > > Any Python Gurus out there that can help me? At a first glance it looks okay but unless we know what you are going to do with these data structures it's hard to tell if it is really the best "translation". `PF.buffer` might be better a string or an `array.array`. And is `BLOCK` really just a structure with *one* member? Looks a bit odd IMHO. Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Thu Jul 26 02:51:33 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 26 Jul 2007 06:51:33 GMT Subject: Flatten a list/tuple and Call a function with tuples References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <7xzm1kqw89.fsf@ruckus.brouhaha.com> <1185411490.250673.165570@z28g2000prd.googlegroups.com> Message-ID: <5gqujkF3gv1kkU1@mid.uni-berlin.de> On Thu, 26 Jul 2007 00:58:10 +0000, beginner wrote: > I need nested lists to represent nested records in a script. Since the > structure of the underlying data is nested, I think it is probably > reasonable to represent them as nested lists. For example, if I have > the below structure: > > Big Record > Small Record Type A > Many Small Record Type B > Small Record Type C > > It is pretty natural to use lists, although after a while it is > difficult to figure out the meaning of the fields in the lists. If > only there were a way to 'attach' names to members of the list. That's where you may start looking into classes. The simplest one is for just holding attributes seems to be the "bunch": In [15]: class Bunch(object): ....: def __init__(self, **kwargs): ....: self.__dict__ = kwargs ....: In [16]: small_a = Bunch(foo=42, bar=23) In [17]: many_b = [1, 2, 3] In [18]: small_c = Bunch(name='eric', profession='viking') In [19]: big_record = Bunch(small_a=small_a, many_b=many_b, small_c=small_c) In [20]: big_record.small_a.bar Out[20]: 23 In [21]: big_record.many_b[1] Out[21]: 2 > For the unpacking question, I encountered it when working with list > comprehensions. For example: > > [ f(*x,1,2) for x in list] is difficult to do if I don't want to > expand *x to x[0]..x[n]. There are usually 7-10 items in the list and > it is very tedious and error prone. If you are the designer of `f` then just receive the whole `x` as *one* argument. Ciao, Marc 'BlackJack' Rintsch From paddy3118 at googlemail.com Tue Jul 17 02:19:41 2007 From: paddy3118 at googlemail.com (Paddy) Date: Mon, 16 Jul 2007 23:19:41 -0700 Subject: In a dynamic language, why % operator asks user for type info? In-Reply-To: <1184631007.920803.147790@j4g2000prf.googlegroups.com> References: <1184631007.920803.147790@j4g2000prf.googlegroups.com> Message-ID: <1184653181.658840.237510@n2g2000hse.googlegroups.com> On Jul 17, 1:10 am, Karthik Gurusamy wrote: > Hi, > > The string format operator, %, provides a functionality similar to the > snprintf function in C. In C, the function does not know the type of > each of the argument and hence relies on the embedded % > specifier to guide itself while retrieving args. > > In python, the language already provides ways to know the type of an > object. > > So in > > output = '%d foo %d bar" % (foo_count, bar_count), > why we need to use %d? I'm thinking some general common placeholder, > say %x (currently it's hex..) could be used. > > output = '%x foo %x bar" % (foo_count, bar_count). > Since % by definition is string formatting, the operator should be > able to infer how to convert each of the argument into strings. > > If the above is the case, we could've avoided all those exceptions > that happen when a %d is specified but say a string is passed. > > Thanks, > Karthik '%s' might be what your after as a more 'general purpose' moifier. - Paddy. From greg at cosc.canterbury.ac.nz Wed Jul 4 22:15:21 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 05 Jul 2007 14:15:21 +1200 Subject: object references/memory access In-Reply-To: References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1183407411.397142.304790@e16g2000pri.googlegroups.com> <1183417108.245203.158830@x35g2000prf.googlegroups.com> <4689e535$0$23896$9b622d9e@news.freenet.de> <1183488824.131448.62720@x35g2000prf.googlegroups.com> Message-ID: <5f32o8F3aeadqU1@mid.individual.net> John Nagle wrote: > C gets to > run briefly, drains out the pipe, and blocks. P gets to run, > fills the pipe, and blocks. The compute-bound thread gets to run, > runs for a full time quantum, and loses the CPU to C. Wash, > rinse, repeat. I thought that unix schedulers were usually a bit more intelligent than that, and would dynamically lower the priority of processes using CPU heavily. If it worked purely as you describe, then a CPU-bound process would make any interactive application running at the same time very unresponsive. That doesn't seem to happen on any of today's desktop unix systems. -- Greg From LarinAM at gmail.com Thu Jul 5 06:52:45 2007 From: LarinAM at gmail.com (LarinAM at gmail.com) Date: Thu, 05 Jul 2007 10:52:45 -0000 Subject: Python daemon in Linux In-Reply-To: <1183627404.157350.105560@o61g2000hsh.googlegroups.com> References: <1183627404.157350.105560@o61g2000hsh.googlegroups.com> Message-ID: <1183632765.423932.249970@g4g2000hsf.googlegroups.com> As far as I understand the issue, any Python process has a sort of "main" thread. When the main thread exits, the Python process will exit if there are only daemon threads around. If there are any non-daemon threads, the Python process will only exit after those threads are finished. Or, as the documentation says: "The entire Python program exits when no active non-daemon threads are left." Kind regards, Benjamin From bdesth.quelquechose at free.quelquepart.fr Sun Jul 22 02:20:52 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 22 Jul 2007 08:20:52 +0200 Subject: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> Message-ID: <46a7b9e7$0$31113$426a74cc@news.free.fr> Martha_Jones at tx.net a ?crit : > Python is a better language, with php support, Python has php support ? My, I'm a professional web developper using both, and I didn't knew this. (snip troll) From greg at cosc.canterbury.ac.nz Wed Jul 4 00:34:56 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Wed, 04 Jul 2007 16:34:56 +1200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xd4za1086.fsf@ruckus.brouhaha.com> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> Message-ID: <5f0mhuF3b0stbU1@mid.individual.net> Paul Rubin wrote: > E.g. your program might pass its test and run properly for years > before some weird piece of input data causes some regexp to not quite > work. Then you get a bug report, you fix it, and you add a test for it so that particular bug can't happen again. > Once I got the > function to work, I deployed it without writing permanent tests for > it. That suggests you had a temporary test at some point. So, keep it and make it a permanent test. Even if it's just a small manually-created directory, it's still better than nothing, and you can add to it over time to cover any bugs that turn up. -- Greg From kelvie at ieee.org Thu Jul 5 03:15:15 2007 From: kelvie at ieee.org (Kelvie Wong) Date: Thu, 5 Jul 2007 00:15:15 -0700 Subject: ['a', 'b'][True] results 'b' But how? In-Reply-To: <1183618481.636297.96080@e9g2000prf.googlegroups.com> References: <1183618481.636297.96080@e9g2000prf.googlegroups.com> Message-ID: <94ccbe710707050015s62322741h844cf1d05c59f055@mail.gmail.com> In this case, [True] and [False] are not lists, rather you're accessing the items of the list with the index True or False, as per the following example: >>> a_list = ['a', 'b'] >>> a_list[True] 'b' >>> a_list[False] 'a' This happens because the __getitem__ method takes its argument (which in this case is True or False) and casts it into an integer: >>> int(True) 1 >>> int(False) 0 So thus it follows logically that since: >>> a_list[1] 'b' >>> a_list[0] 'a' a_list[True] and a_list[False] must be its first and zeroth indexed members, respectively. On 7/4/07, kath wrote: > Hi, > > Can any one please tell me how is the following code is working? > ['a','b'] is a list of string, and [True] is list of boolean value. > How is it making effect....? > > > >>> ['a','b] [True] > 'b' > >>> ['a','b'] [False] > 'a' > >>> ['a','b']['some_string' == r'some_string'] > 'b' > >>> ['a','b']['some_string' == r'somestring'] > 'a' > > > > > Thanks in advance, > regards, > kath. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Kelvie From pyscottishguy at hotmail.com Fri Jul 27 12:48:23 2007 From: pyscottishguy at hotmail.com (pyscottishguy at hotmail.com) Date: Fri, 27 Jul 2007 16:48:23 -0000 Subject: pyparser and recursion problem In-Reply-To: <1185543544.227131.158640@r34g2000hsd.googlegroups.com> References: <1185479408.520124.40670@k79g2000hse.googlegroups.com> <1185504855.745706.241590@d55g2000hsg.googlegroups.com> <1185507613.143993.175840@19g2000hsx.googlegroups.com> <1185543544.227131.158640@r34g2000hsd.googlegroups.com> Message-ID: <1185554903.885829.211910@d55g2000hsg.googlegroups.com> Hey, Thanks for the further explanations. I'm going to play around more with the 'recursive grammar' and 'parse-time dynamic grammar element' stuff so that I understand it a bit better. I liked the changes you suggested. The alternative grammar definitely makes the code easier to understand, plus the 'delimitedList' function is very handy. I can see the usefulness of 'Combine' but it's not needed here. This didn't work though: print res["Start"][0].asList() But that's ok, because I was more than happy to do: myArray = [res["Start"]][0] and have the whole thing as a list. Very nice indeed :) Thanks again for your help! For anyone thats interested, here is the updated code (my original code with Paul's enhancements) #!/usr/bin/python from pyparsing import Word, OneOrMore, Group, alphas, \ alphanums, Suppress, Dict, delimitedList, ParseResults import string def allIn( as, members ): "Tests that all elements of as are in members""" for a in as: if a not in members: return False return True def allUpper( as ): """Tests that all strings in as are uppercase""" return allIn( as, string.uppercase ) # recursive reference fixer-upper def fixupRefsRecursive(tokens, lookup): if isinstance(tokens, ParseResults): subs = [ fixupRefsRecursive(t, lookup) for t in tokens ] tokens = ParseResults( subs ) else: if tokens.isupper(): tokens = fixupRefsRecursive(lookup[tokens], lookup) return tokens def fixupRefs(tokens): tokens["Start"] = fixupRefsRecursive( tokens["Start"], tokens ) testData = """ :Start: first SECOND THIRD fourth FIFTH :SECOND: second1_1 second1_2 | second2 | second3 :THIRD: third1 third2 | SIXTH :FIFTH: fifth1 | SEVENTH :SIXTH: sixth1_1 sixth1_2 | sixth2 :SEVENTH: EIGHTH | seventh1 :EIGHTH: eighth1 | eighth2 """ COLON = Suppress(":") label = COLON + Word(alphas + "_") + COLON entry = Word(alphanums + "_") data = delimitedList( Group(OneOrMore(entry)), delim="|" ) line = Group(label + data) doc = Dict(OneOrMore(line)) doc.setParseAction( fixupRefs ) res = doc.parseString(testData) myArray = [res["Start"]][0] print myArray From deets at nospam.web.de Wed Jul 18 11:37:50 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 18 Jul 2007 17:37:50 +0200 Subject: Property Descriptor - Public Getter, Private Setter References: <1184771137.140502.187210@e16g2000pri.googlegroups.com> Message-ID: <5g6qeeF3ecbugU1@mid.uni-berlin.de> gamehack wrote: > Hi all, > > I was looking around the net to figure out how I can use the > property() descriptor to make a property readable by everyone and only > settable by the class or any derived classes. Thanks. Forget it. You can try and come up with an implementation that will check the stack-frames and try and see if the callers belong to the current class, or some subclass. But then if somebody wants to accomplish the setting by all means, he/she just adds a new setter method to your class, and that's it. What's your usecase? If you give us that, there might be better suggestions. Diez From rcdailey at gmail.com Fri Jul 6 15:28:14 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 06 Jul 2007 19:28:14 -0000 Subject: C++ Modules for python: How to? Message-ID: <1183750094.154566.248170@m36g2000hse.googlegroups.com> Hi, I'm interested in making a C++ library of mine usable through python. Python does a similar thing with Expat (the non-validating XML parser). I notice that with Expat, python is importing a C++ header file into a PY file and the interface is available to python. I've read through the python documentation as well as done a little bit of google research and I've not been able to find a tutorial of some sort on how to do this. Perhaps I just don't know the right words to search for. If anyone could lead me in the right direction (possibly an article, tutorial, etc) I would greatly appreciate it. From antoPUNTOcuni at gmail.com Wed Jul 11 09:03:25 2007 From: antoPUNTOcuni at gmail.com (Antonio Cuni) Date: Wed, 11 Jul 2007 15:03:25 +0200 Subject: How to Machine A python script execute Machine B python script? In-Reply-To: <1183945503.875939.292420@57g2000hsv.googlegroups.com> References: <1183945503.875939.292420@57g2000hsv.googlegroups.com> Message-ID: johnny wrote: > Anyone know how I can make Machine A python script execute a python > script on Machine B ? have a look to py.execnet; in the simplest case, it does not need any special setup on machine B, just a working ssh server and a python interpreter installed: http://codespeak.net/py/dist/execnet.html ciao Anto From rvtol+news at isolution.nl Tue Jul 3 20:14:14 2007 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Wed, 4 Jul 2007 02:14:14 +0200 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <138jml0ldeucf32@corp.supernews.com> Message-ID: Peter J. Holzer schreef: > Since a day with a leap second has 86401 seconds (or 86399, but that > hasn't happened yet) Many systems allow a seconds value of 0..61, so minutes (actually months) with two leap seconds are foreseen. A leap second may be introduced at the end of any month, the preferred dates are at the end of June and the end of December. At the estimated rate of decrease, the earth would lose about 1/2 day after 4,000 years, and about two leap seconds a month would be needed to keep UTC in step with Earth time, UT1. (source: ) -- Affijn, Ruud "Gewoon is een tijger." From will at willNOmcguganSPAM.com Tue Jul 3 15:20:58 2007 From: will at willNOmcguganSPAM.com (Will McGugan) Date: Tue, 03 Jul 2007 20:20:58 +0100 Subject: error return without exception set In-Reply-To: References: <468a6d19$0$27861$db0fefd9@news.zen.co.uk> Message-ID: <468aa19c$0$27853$db0fefd9@news.zen.co.uk> Peter Otten wrote: > > The "error return without exception set" part looks like a failed > consistency check in ceval.c -- perhaps caused by a broken extension > written in C. > > But you'd have to give some more context. Thanks for the explanation. It happens when I'm debugging a wxWidgets application with Komodo, but I can't trap it. I'm guessing it must be a Komodo issue, because I dont get it if I run it without the debugger. Will From kar1107 at gmail.com Mon Jul 2 18:58:28 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Mon, 02 Jul 2007 15:58:28 -0700 Subject: object references/memory access In-Reply-To: References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1183407411.397142.304790@e16g2000pri.googlegroups.com> Message-ID: <1183417108.245203.158830@x35g2000prf.googlegroups.com> On Jul 2, 3:01 pm, Steve Holden wrote: > Karthik Gurusamy wrote: > > On Jul 1, 12:38 pm, dlomsak wrote: > [...] > > > I have found the stop-and-go between two processes on the same machine > > leads to very poor throughput. By stop-and-go, I mean the producer and > > consumer are constantly getting on and off of the CPU since the pipe > > gets full (or empty for consumer). Note that a producer can't run at > > its top speed as the scheduler will pull it out since it's output pipe > > got filled up. > > But when both processes are in the memory of the same machine and they > communicate through an in-memory buffer, what's to stop them from > keeping the CPU fully-loaded (assuming they are themselves compute-bound)? If you are a producer and if your output goes thru' a pipe, when the pipe gets full, you can no longer run. Someone must start draining the pipe. On a single core CPU when only one process can be running, the producer must get off the CPU so that the consumer may start the draining process. > > > When you increased the underlying buffer, you mitigated a bit this > > shuffling. And hence saw a slight increase in performance. > > > My guess that you can transfer across machines at real high speed, is > > because there are no process swapping as producer and consumer run on > > different CPUs (machines, actually). > > As a concept that's attractive, but it's easy to demonstrate that (for > example) two machines will get much better throughput using the > TCP-based FTP to transfer a large file than they do with the UDP-based > TFTP. This is because the latter protocol requires the sending unit to > stop and wait for an acknowledgment for each block transferred. With > FTP, if you use a large enough TCP sliding window and have enough > content, you can saturate a link as ling as its bandwidth isn't greater > than your output rate. > > This isn't a guess ... What you say about a stop-n-wait protocol versus TCP's sliding window is correct. But I think it's totally orthogonal to the discussion here. The issue I'm talking about is how to keep the end nodes chugging along, if they are able to run simultaneously. They can't if they aren't on a multi- core CPU or one different machines. > > > Since the two processes are on the same machine, try using a temporary > > file for IPC. This is not as efficient as real shared memory -- but it > > does avoid the IPC stop-n-go. The producer can generate the multi-mega > > byte file at one go and inform the consumer. The file-systems have > > gone thru' decades of performance tuning that this job is done really > > efficiently. > > I'm afraid this comes across a bit like superstition. Do you have any > evidence this would give superior performance? > I did some testing before when I worked on boosting a shell pipeline performance and found using file-based IPC was very good. (some details at http://kar1107.blogspot.com/2006/09/unix-shell-pipeline-part-2-using.html ) Thanks, Karthik > >> Thanks for the replies so far, I really appreciate you guys > >> considering my situation and helping out. > > 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.rawlins at thinkbluemedia.co.uk Sun Jul 15 15:46:48 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Sun, 15 Jul 2007 20:46:48 +0100 Subject: Dict Help In-Reply-To: References: Message-ID: <015101c7c718$e207e820$a617b860$@rawlins@thinkbluemedia.co.uk> Thanks Gabriel, That all works a charm, Iteration on this isn?t important for me so the SET will work much better I think, I had read about them before but have never used them, I'm glad to see it works so simply. Thanks, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Gabriel Genellina Sent: 15 July 2007 20:33 To: python-list at python.org Subject: Re: Dict Help En Sun, 15 Jul 2007 11:39:24 -0300, Robert Rawlins escribi?: > I'm looking for some help expanding on a dictionary I've got and storing > multiple values per key and the best way to do it. I'm guessing that I > need to store a list inside the value of the dictionary, but I'm not > quite sure how that can be achieved, and also how to check for values in > that list. > Here is a brief example of what I want to be able to build: > Key Value > 00:0F:DE:A8:AB:6F > 6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg,01DBB592-F7EB-B000-7F250FD8A2CE158F. gif,533EAE0F-B211-B2D8-4C2DB662CCECFBD7.3gp > 00:17:B0:A0:E7:09 > 6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg,01DBB592-F7EB-B000-7F250FD8A2CE158F. gif > 00:1B:98:16:21:E4 > 6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg There are a few ways to do it. Just translating your own words into Python, use a dictionary with a list of values. > Now I really need to have two functions, one of which appends a value to > the list for a specified key, so I have the key and the new value as > strings, I then want to locate that key and append the list with the new > value. The simplest way: d = {} # add a pair key, value if key not in d: d[key] = [value] else: d[key].append(value) > The second function I need, is to check for the existence of a value in > the list of a particular key, again I have the key and the value and I > want to do something like: > if value in list of values for key: > do something here... # check for a key, value exists = key in d and value in d[key] > The final function that would be helpful to me would to be able to > remove a value from the list for a specific key. # remove value from key's values if key in d and value in d[key]: d[key].remove(value) > I'm not sure if a list as the value in a dict is possible, or if its the > best way to achieve this, It just made logic sense to me so thought I'd > come and get your thoughts on this. If anyone has any better suggestions It's perfectly possible as you can see. Now, depending on how many values you have, or how often do you test, you might replace the list with a set. Sets are unordered collections (you will loose the insertion order) but are better suited for a "contains" test (O(1) instead of O(n) for a list) And you might replace the dictionary with a defaultdict. The insertion would become: from collections import defaultdict d = defaultdict(set) # add a pair key, value d[key].add(value) The existence check and remove method do not change. Dicts, lists and sets are documented here: and defaultdict -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list From stefan.sonnenberg at pythonmeister.com Thu Jul 5 06:18:54 2007 From: stefan.sonnenberg at pythonmeister.com (Stefan Sonnenberg-Carstens) Date: Thu, 5 Jul 2007 12:18:54 +0200 (CEST) Subject: Building a Python app with Mozilla In-Reply-To: <5f30vsF3aicltU1@mid.individual.net> References: <1183524527.709730.190290@q75g2000hsh.googlegroups.com> <5f30vsF3aicltU1@mid.individual.net> Message-ID: <1068189.27726.BlRUCl8VTQA=.1183630734.squirrel@webmailer.hosteurope.de> On Do, 5.07.2007, 03:45, greg wrote: > sjdevnull at yahoo.com wrote: > >> wxWidgets will give you native looking apps on both Linux and Windows > > Well, maybe. There's more to getting a native feel than > just using the right widgets. I once saw a Qt-based app on > MacOSX that had tiny little buttons that were too small > for the text they contained -- Aqua buttons just don't > scale down like that. :-( > > -- > Greg > -- > http://mail.python.org/mailman/listinfo/python-list > > Qt based buttons don't either. If some fool uses absolute positioning and sizing, then it is not the toolkit to blame. I'm using wxPython for instance and use the sizers and placeholders there, so this is possible with Qt also. So, perhaps (which I don't know) Aqua buttons simply don't permit absolute stuff ? Or the Aqua programmers read the user interface guidelines carefully ? From stephane.larouche at polymtl.ca Sat Jul 7 12:31:59 2007 From: stephane.larouche at polymtl.ca (=?utf-8?b?U3TDqXBoYW5l?= Larouche) Date: Sat, 7 Jul 2007 16:31:59 +0000 (UTC) Subject: Mixing Python and C threads References: Message-ID: 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: ---------- primes.cpp ---------- #include #include using namespace std; int is_prime(const long n) { long i; for (i = 2; i < n; i++) if (n % i == 0) return 0; return 1; } long nb_primes(const long n) { long i, nb = 0; #pragma omp parallel for private(i) reduction(+ : nb) // It crashes here. for (i = 2; i <= n; i++) if (is_prime(i)) nb += 1; return nb; } static PyObject * nb_primes_wrapper(PyObject *self, PyObject *args) { long n, nb; if (!PyArg_ParseTuple(args, "l", &n)) return NULL; nb = nb_primes(n); return Py_BuildValue("l", nb); } static PyMethodDef primes_methods[] = { {"nb_primes", nb_primes_wrapper, METH_VARARGS}, {NULL} }; PyMODINIT_FUNC initprimes() { PyObject *module; module = Py_InitModule("primes", primes_methods); } ---------- end of primes.cpp ---------- I compile it using: gcc -c -fopenmp -IC:/Python25/include primes.cpp gcc -LC:/Python25/libs -LC:/mingw/lib -mdll -o primes.pyd primes.o -lpython25 -lgomp -lpthreadGC2 In Python: import primes primes.nb_primes(1000) works fine, but import primes import threading t = threading.Thread(target = primes.nb_primes, args = (1000,)) t.start() crashes. Would anybody be so kind and try to compile it with Microsoft or Intel compiler and tell me if it also crashes (I tried Visual C++ 2005 Express Edition, but it does not implement OpenMP). If the bug is with gcc, I will submit the problem to the appropriate people. Thank you, St?phane Larouche From sandravandale at yahoo.com Mon Jul 23 21:43:14 2007 From: sandravandale at yahoo.com (Sandra-24) Date: Mon, 23 Jul 2007 18:43:14 -0700 Subject: Hacking with __new__ Message-ID: <1185241394.990936.206360@k79g2000hse.googlegroups.com> Ok here's the problem, I'm modifying a 3rd party library (boto) to have more specific exceptions. I want to change S3ResponseError into about 30 more specific errors. Preferably I want to do this by changing as little code as possible. I also want the new exceptions to be a subclass of the old S3ResponseError so as to not break old code that catches it. If I meet these two requirements I expect my modification to make it into boto and then I won't have to worry about maintaining a seperate version. So thinking myself clever with python I thought I could change S3ResponseError to have a __new__ method which returns one of the 30 new exceptions. That way none of the raise S3ResponseError code needs changing. No problem. The trouble comes with those exceptions being subclasses of S3ResponseError, because __new__ is called again and goofs everything up. I think there may be a way to solve this but after playing around in the shell for a while, I give up. I'm less concerned with the original problem than I am curious about the technical challenge. Can anyone tell me if it's possible to do meet both of my requirements? Thanks, -Sandra Here's my shell code if you want to play with it too (Bar is S3ResponseError, Zoo is a more specific error, Foo is just the base class of Bar.) >>> class Foo(object): ... def __new__(cls, *args): ... print 'Foo.__new__', len(args) ... return super(Foo, cls).__new__(cls, *args) ... ... def __init__(self, a, b, c): ... print 'Foo.__init__', 3 ... self.a = a ... self.b = b ... self.c = c ... >>> class Bar(Foo): ... def __new__(cls, a, b, c, *args): ... print 'Bar.__new__', len(args) ... if args: ... return super(Bar, cls).__new__(cls, a, b, c, *args) ... ... return Zoo(a, b, c, 7) ... >>> class Zoo(Bar): ... def __init__(self, a, b, c, d): ... print 'Zoo.__init__', 4 ... Foo.__init__(self, a, b, c) ... self.d = d ... >>> Bar(1,2,3) Bar.__new__ 0 Bar.__new__ 1 Foo.__new__ 4 Zoo.__init__ 4 Foo.__init__ 3 Traceback (most recent call last): File "", line 1, in TypeError: __init__() takes exactly 5 arguments (4 given) From dstromberg at datallegro.com Thu Jul 12 15:57:18 2007 From: dstromberg at datallegro.com (Dan Stromberg - Datallegro) Date: Thu, 12 Jul 2007 12:57:18 -0700 Subject: bash-style pipes in python? References: <1184212548.314558.203880@n60g2000hse.googlegroups.com> Message-ID: On Wed, 11 Jul 2007 20:55:48 -0700, faulkner wrote: > On Jul 11, 8:56 pm, Dan Stromberg - Datallegro > wrote: >> I'm constantly flipping back and forth between bash and python. >> >> Sometimes, I'll start a program in one, and end up recoding in the >> other, or including a bunch of python inside my bash scripts, or snippets >> of bash in my python. >> >> But what if python had more of the power of bash-style pipes? I might not >> need to flip back and forth so much. I could code almost entirely in python. >> >> The kind of thing I do over and over in bash looks like: >> >> #!/usr/bin/env bash >> >> # exit on errors, like python. Exit on undefind variables, like python. >> set -eu >> >> # give the true/false value of the last false command in a pipeline >> # not the true/false value of the lat command in the pipeline - like >> # nothing I've seen >> set -o pipefail >> >> # save output in "output", but only echo it to the screen if the command fails >> if ! output=$(foo | bar 2>&1) >> then >> echo "$0: foo | bar failed" 1>&2 >> echo "$output" 1>&2 >> exit 1 >> fi >> >> Sometimes I use $PIPESTATUS too, but not that much. >> >> I'm aware that python has a variety of pipe handling support in its >> standard library. >> >> But is there a similarly-simple way already, in python, of hooking the stdout of >> process foo to the stdin of process bar, saving the stdout and errors from both >> in a variable, and still having convenient access to process exit values? >> >> Would it be possible to overload | (pipe) in python to have the same behavior as in >> bash? >> >> I could deal with slightly more cumbersome syntax, like: >> >> (stdout, stderrs, exit_status) = proc('foo') | proc('bar') >> >> ...if the basic semantics were there. >> >> How about it? Has someone already done this? > > class P(subprocess.Popen): > def __or__(self, otherp): > otherp.stdin.write(self.stdout.read()) > otherp.stdin.close() > return otherp > def __init__(self, cmd, *a, **kw): > for s in ['out', 'in', 'err']: kw.setdefault('std' + s, -1) > subprocess.Popen.__init__(self, cmd.split(), *a, **kw) > > print (P('cat /etc/fstab') | P('grep x')).stdout.read() > > of course, you don't need to overload __init__ at all, and you can > return otherp.stdout.read() instead of otherp, and you can make > __gt__, __lt__ read and write files. unfortunately, you can't really > fudge &>, >>, |&, or any of the more useful pipes, but you can make > more extensive use of __or__: > > class Pipe: > def __or__(self, other): > if isinstance(other, Pipe): return ... > elif isinstance(other, P): return ... > def __init__(self, pipe_type): ... > > k = Pipe(foo) > m = Pipe(bar) > > P() |k| P() > P() |m| P() This is quite cool. I have to ask though - isn't this going to read everything from foo until foo closes its stdout, and then write that result to bar - rather than doing it a block at a time like a true pipe? I continued thinking about this last night after I sent my post, and started wondering if it might be possible to come up with something where you could freely intermix bash pipes and python generators, by faking the pipes using generators and some form of concurrent function composition - perhaps threads or subprocesses for the concurrency. Of course, that imposes some extra I/O, CPU and context switch overhead, since you'd have python shuttling data from foo to bar all the time instead of foo sending data directly to bar, but the ability to mix python and pipes might be worth it. Even better might be to have a choice between intermixable and fast. Comments anyone? From robin at reportlab.com Fri Jul 6 06:46:56 2007 From: robin at reportlab.com (Robin Becker) Date: Fri, 06 Jul 2007 11:46:56 +0100 Subject: deliberate versus os socket timeout In-Reply-To: <87odiqxy8d.fsf@pobox.com> References: <87odiqxy8d.fsf@pobox.com> Message-ID: <468E1DA0.5090308@chamonix.reportlab.co.uk> John J. Lee wrote: > > What do you mean "is in fact true"? Is what true? That the reason is > always formatted in those ways when those particular errors occur? > Not sure there's any reason to rely on that: I'd expect .reason to be > an exception object, so (reading the docs for module socket) > e.reason.args[0] should be the error code if one is available, in this > case errno.ETIMEDOUT (i.e. WSAETIMEDOUT, which means the timeout > occurred before a connection was established). Sometimes > e.reason.args will be length-1, and e.reason.args[0] will be a string, > again according to the docs for module socket. > well I suspect there's a whole twisty maze of stuff to do to reliably detect whether a timeout was deliberate or not so I'll pass on that. ......... > >> More importantly is there anything I can do to avoid these wrong os >> inspired timeouts? I'm just using urllib2 to read from a remote site > [...] > > Please define "wrong" ;-) > well if I ask to be timed out after 120 seconds I don't expect a timeout error after 20 so I would define the 20 second case to be somehow wrong or unexpected. > Googling suggests Windows doesn't let you configure its connect > timeout, except through a registry setting: > > http://www.tech-archive.net/Archive/VC/microsoft.public.vc.language/2005-09/msg00918.html the implication of windows providing its own timeout seems to make the socket defaulttimeout irrelevant since I can have no per socket control over it. I think this came up before and I just forgot about it mumble mumble -- Robin Becker From nagle at animats.com Thu Jul 5 17:09:42 2007 From: nagle at animats.com (John Nagle) Date: Thu, 05 Jul 2007 21:09:42 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: <1183659478.231468.229590@57g2000hsv.googlegroups.com> References: <9uRhi.17027$xk5.14289@edtnps82> <1183659478.231468.229590@57g2000hsv.googlegroups.com> Message-ID: Falcolas wrote: > On Jul 5, 10:30 am, "Chris Mellon" wrote: > >>I don't think anyone has suggested that. Let me be clear about *my* >>position: When you need to ensure that a file has been closed by a >>certain time, you need to be explicit about it. When you don't care, >>just that it will be closed "soonish" then relying on normal object >>lifetime calls is sufficient. This is true regardless of whether >>object lifetimes are handled via refcount or via "true" garbage >>collection. Relying on the specific semantics of refcounting to give >>certain lifetimes is a logic error. We may need a guarantee that if you create a local object and don't copy a strong reference to it to an outer scope, upon exit from the scope, the object will be destroyed. John Nagle From horpner at yahoo.com Fri Jul 6 08:31:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Fri, 06 Jul 2007 12:31:18 GMT Subject: The best platform and editor for Python References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183646799.400176.144570@k79g2000hse.googlegroups.com> <1183655933.475488.157270@m36g2000hse.googlegroups.com> <1183670009.035673.256680@w5g2000hsg.googlegroups.com> <1i0so61.10qnto712c7dhpN%aleax@mac.com> Message-ID: On 2007-07-06, Alex Martelli wrote: > Kay Schluehr wrote: >> half of the community is happy with Emacs and the other half >> wants to program in a VS-like environment, neither consensus >> nor progress has > > Calling all vi/vim users (and we'll heartily appreciate the > support of TextMate fans, BBEdit ones, etc, etc) -- we're at > risk being defined out of existence, since we're neither happy > with Emacs nor wanting anything like Visual Studio, and yet Kay > claims that people in either category make up the whole (one > half plus the other half) and so that WE DON'T EXIST!!! A > ridiculous claim to be sure, but we'd better let Herr Schluehr > know that in no uncertain terms... Wow! That explains why I had so much trouble eating me Wheaties this morning. Can I still post messages if I don't exist? -- Neil Cerutti From leena_kirank at yahoo.com Sat Jul 14 04:15:22 2007 From: leena_kirank at yahoo.com (Kan) Date: Sat, 14 Jul 2007 08:15:22 -0000 Subject: Direct Client - TAC Engineer/Support Engineer -Phoenix Message-ID: <1184400922.279681.265240@i38g2000prf.googlegroups.com> Hello, We have requirement for TAC Engineer in Phoenix. If your skills and experience matches with the same, send me your resume asap with contact # and rate to 'kanchan at tbiinc.org. Job Title= TAC Engineer Location = Phoenix Duration = 6months Must / Core Skills Linux System administrator Shell scripting Knowledge of Databases Administration The ideal candidate will have 5 or more years of support engineering experience, including 3 or more years supporting telecommunications firms and/or engineering experience in complex, large-scale IT and network environments. Technology experience should be current. Experience Requirements: Previous experience with professional services support organization (large Telco or Fortune 500 customers) or technical customer service environment, required. Programming or troubleshooting of complex software source code: Java, C, scripting languages Strong UNIX System administration and usage. Red Hat Linux and Sun Solaris. Network and complex system troubleshooting, including at least 2 years of large scale network troubleshooting. Prevailing network troubleshooting tools - sniffers, log analysis, scripting tools. 2+ years experience HTML, Java, JSP, Javascript, SOAP/Webservices, XML Use of SQL database to troubleshoot and isolate application level consistency issues. (Oracle PL/SQL) Source Control Management: Perforce, Subversion Bug tracking software: Bugzilla, DDTS Thanks and regards, Kan BTech Inc Recruiter 510-438-6834 kanchan at tbiinc.org www.tbiinc.org From cai.haibin at gmail.com Mon Jul 23 08:04:42 2007 From: cai.haibin at gmail.com (james_027) Date: Mon, 23 Jul 2007 12:04:42 -0000 Subject: decorators tutorials In-Reply-To: <46a48245$0$19544$426a34cc@news.free.fr> References: <1185178383.499234.299850@z24g2000prh.googlegroups.com> <1185180112.321457.73170@n2g2000hse.googlegroups.com> <1185183257.471106.318070@x35g2000prf.googlegroups.com> <46a48245$0$19544$426a34cc@news.free.fr> Message-ID: <1185192282.331334.213730@x35g2000prf.googlegroups.com> hi bruno, That seems to be hard to read at all, or I am just very new to python? With that decorator how do I take advantage of it compare when I just write a function that could do the same as what the decorator did? I could translate the could from above into ... def check_login(msg): #... def my_func(toto, tata): #... #call it like this check_login('msg') my_func('toto', 'tata') Thanks james On Jul 23, 6:26 pm, Bruno Desthuilliers wrote: > james_027 a ?crit : > > > Hi all, > > > I am having difficulty understanding decorator. The definition was > > clear for me, but the syntax is not so clear to me. > > > will decorators will always have to be in this way > > > def check_login(func): > > def _check_login(*args): > > print "I am decorator" > > return func(*args) > > return _check_login > > Sort of... Well, depends... > > Basically, a decorator is a callable taking a callable as argument and > returning a callable. These callable are usually *but* not necessarily > functions. You may want to read the section about the special method > __call__ in the Fine Manual. > > Also, you may want to write a 'parameterized' decorator - a decorator > taking arguments. In this case, you need one more wrapping level: > > def check_login(msg): > def check_login_deco(func): > def _check_login(*args, **kw): > print msg > return func(*args, **kw) > return _check_login > return check_login_deco > > @check_login("I am the decorator") > def my_func(toto, tata): > print toto, tata From tismer at stackless.com Tue Jul 10 07:45:43 2007 From: tismer at stackless.com (Christian Tismer) Date: Tue, 10 Jul 2007 14:45:43 +0300 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: References: Message-ID: <6BAB83B8-CE14-4C09-9CEC-5A68BDC12A76@stackless.com> On 10.07.2007, at 07:21, Jim Langston wrote: > In Python 2.5 on intel, the statement > 2**2**2**2**2 > evaluates to >>>> 2**2**2**2**2 > 2003529930406846464979072351560255750447825475569751419265016973710894 > 0595563114 ... > 5337539755822087777506072339445587895905719156736L >>>> Yes, also on 2.4.4 What's wrong about it? ciao - chris -- Christian Tismer :^) tismerysoft GmbH : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9A : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 802 86 56 mobile +49 173 24 18 776 fax +49 30 80 90 57 05 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Fri Jul 13 15:08:11 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 13 Jul 2007 14:08:11 -0500 Subject: Numpy array index handling In-Reply-To: <1184352981.493615.18040@k79g2000hse.googlegroups.com> References: <1184352981.493615.18040@k79g2000hse.googlegroups.com> Message-ID: phishboh at gmail.com wrote: > Being a Matlab user wanting to switch to Python/SciPy, Fantastic! You might be interested in joining the numpy mailing list. There are a lot more of us numpy devs and users there than here. http://www.scipy.org/Mailing_Lists > I'd like to > know how the following Matlab code would be written in Python: > > % First, just some artificial data > N = 1000000 ; > input = sign(randn(1, N)) ; > a = (1 : N) ; > % This is what I'd like to do; > % for indices where the input has a certain value, compute and store > something > % for indices where the input has another certain value, compute and > store something else > output(input < 0) = 10 * a(input < 0) ; > output(input > 0) = 20 * a(input > 0) ; > > I have tried the following in Python: > N = 1000000 > input = sign(randn(N)) > a = arange(N) > output = zeros(N) > output[input < 0] = 10 * a[input < 0] > output[input > 0] = 20 * a[input > 0] > > However, that gives me in IndexError. When reporting that you get an error, copy-and-pasting the full traceback is highly recommended. We can give you an answer much more quickly if you do. In this case, your example works fine for me with numpy 1.0.3 (after supplying the missing imports). In [1]: from numpy import * In [2]: N = 1000000 In [3]: input = sign(random.randn(N)) In [4]: a = arange(N) In [5]: output = zeros(N) In [6]: output[input < 0] = 10 * a[input < 0] In [7]: output[input > 0] = 20 * a[input > 0] If you are still having problems, please join us on numpy-discussion with the full traceback. -- 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 NickVonHollen at gmail.com Thu Jul 12 16:07:49 2007 From: NickVonHollen at gmail.com (nikki) Date: Thu, 12 Jul 2007 20:07:49 -0000 Subject: DBXML and the Xerces DOM Message-ID: <1184270869.145036.215240@w3g2000hsg.googlegroups.com> I downloaded Berkeley DB XML and put together a test script to load a large 250mb XML file into the database. Storage and retrieval works great, but I need DOM access to the file without loading it all into a string and re-parsing it. In the c++ api (they used swig to expose c+ + to python) it says there is a XmlDocument::getContentAsDOM() method, but when I try to access it via python I just get an attribute error. I looked in the source and the method isn't mapped at all! Has anyone had this work, ever? from dbxml import * mgr = XmlManager() container = mgr.openContainer("test.dbxml") document = container.getDocument('test1') dom = document.getContentAsDOM() Traceback (most recent call last): File "look.py", line 10, in ? dom = document.getContentAsDOM() File "/usr/lib/python2.4/site-packages/dbxml.py", line 277, in __getattr__ = lambda self, name: _swig_getattr(self, XmlDocument, name) File "/usr/lib/python2.4/site-packages/dbxml.py", line 28, in _swig_getattr raise AttributeError,name AttributeError: getContentAsDOM From wildemar at freakmail.de Wed Jul 25 13:08:37 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 25 Jul 2007 19:08:37 +0200 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <1185375639.761280.262490@b79g2000hse.googlegroups.com> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <1185375639.761280.262490@b79g2000hse.googlegroups.com> Message-ID: <46A78395.8070508@freakmail.de> kyosohma at gmail.com wrote: > On Jul 25, 9:50 am, beginner wrote: > >> Another question is how do I pass a tuple or list of all the >> aurgements of a function to the function. For example, I have all the >> arguments of a function in a tuple a=(1,2,3). Then I want to pass each >> item in the tuple to a function f so that I make a function call >> f(1,2,3). In perl it is a given, but in python, I haven't figured out >> a way to do it. (Maybe apply? but it is deprecated?) >> > I'm not sure about the first question, but as for the second, you > could do a few different things. You could just pass the tuple itself > into the function and have the tuple unpacked inside the function. > OR you could use the syntax invented for just that purpose ;). >>> t = 1, 2, 3 >>> f(*t) bam! :) This works with dicts as well (for giving keyword arguments). There you prepend ** (two asterisk to your dict). Simple :) /W From carsten at uniqsys.com Mon Jul 9 10:11:29 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 09 Jul 2007 10:11:29 -0400 Subject: What is the most efficient way to test for False in a list? In-Reply-To: <1183989753.501355.70810@k79g2000hse.googlegroups.com> References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <7x7ipajvst.fsf@ruckus.brouhaha.com> <5fejp2F3cp3igU1@mid.individual.net> <5feju0F3c7pd1U1@mid.uni-berlin.de> <87tzsd21ld.fsf@mulj.homelinux.net> <1183989753.501355.70810@k79g2000hse.googlegroups.com> Message-ID: <1183990289.3449.11.camel@dot.uniqsys.com> On Mon, 2007-07-09 at 07:02 -0700, Paul McGuire wrote: > >>> any(map(lambda _ : _ is False,[3,2,1,0,-1])) > False > >>> any(map(lambda _ : _ is False,[3,2,1,0,-1,False])) > True > >>> Why the map/lambda? Is it faster than the more readable generator expression? >>> any(x is False for x in [3,2,1,0,-1]) False >>> any(x is False for x in [3,2,1,0,-1,False]) True -- Carsten Haese http://informixdb.sourceforge.net From pabloski at giochinternet.com Sat Jul 7 12:32:49 2007 From: pabloski at giochinternet.com (pabloski at giochinternet.com) Date: Sat, 07 Jul 2007 16:32:49 GMT Subject: Unicode problem References: <5f9t3tF3c8qopU2@mid.uni-berlin.de> Message-ID: > No it shouldn't because \x2019 is a "right single quotation mark" and not > an apostrophe. > > Ciao, > Marc 'BlackJack' Rintsch I agree, but the problem is much subtle. I have coverted a text from iso-8859-1 to utf-8 and the codecs have translated \x27 ( the iso apostrophe ) to \xe28099 in utf-8 ( or u'2019' in unicode code point notation ) So if convert an apostrophe to a "right single quotation mark" why not translate the "right single quotation mark" to "apostrophe" As I can see it works in one direction but not in the other From thomas at jollans.com Mon Jul 2 12:01:00 2007 From: thomas at jollans.com (Thomas Jollans) Date: Mon, 2 Jul 2007 18:01:00 +0200 Subject: Reading stdout and stderr of an external program In-Reply-To: <1183389787.481605.111160@k29g2000hsd.googlegroups.com> References: <1183389787.481605.111160@k29g2000hsd.googlegroups.com> Message-ID: <200707021801.00421.thomas@jollans.com> On Monday 02 July 2007, Murali wrote: > Hi Python programmers, > > I need to be able to read the stdout and stderr streams of an external > program that I launch from my python script. os.system( 'my_prog' + > '>& err.log' ) and was planning on monitoring err.log and to display > its contents. Is this the best way to do this? No. The best way to do this is with Popen, as it is portable and avoids the extranous file. -- 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 From deets at nospam.web.de Thu Jul 5 02:47:44 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 05 Jul 2007 08:47:44 +0200 Subject: IDEs for COM scripting: C# v. Python v. Iron Python v. JPython In-Reply-To: <468c844b$0$27401$ba4acef3@news.orange.fr> References: <468c844b$0$27401$ba4acef3@news.orange.fr> Message-ID: <5f3igjF39a72dU1@mid.uni-berlin.de> "M??????????????????????????????????????????" schrieb: > Hi! > >> I love the typing assist I get when using C# in VS2005 to write COM >> clients. > > But this run only for static-COM-servers. Dynamic-COM-servers are not > supported by these assists. No. The IDIspatch-interface explicitely lists what methods with what arguments it has. So code completion is possible there as well. Diez From asincero at gmail.com Tue Jul 17 15:52:19 2007 From: asincero at gmail.com (asincero) Date: Tue, 17 Jul 2007 12:52:19 -0700 Subject: Design question regarding exceptions. Message-ID: <1184701939.282684.260730@o11g2000prd.googlegroups.com> I have a class called Users that provides a higher level of abstraction to an underlying "users" table in a pgsql database. It has methods like "addUser()" and "deleteUser()" which, obviously, wrap the corresponding SQL statements. My question is would it better to let any exceptions thrown by the underlying DB-API calls bubble up from these methods, or should I catch them inside the methods, wrap them inside my own custom exceptions, and throw those exceptions instead? Thanks. -- Arcadio From samwyse at gmail.com Thu Jul 12 07:31:25 2007 From: samwyse at gmail.com (samwyse) Date: Thu, 12 Jul 2007 11:31:25 -0000 Subject: Re-raising exceptions with modified message In-Reply-To: References: <1183863713.876365.111820@57g2000hsv.googlegroups.com> Message-ID: <1184239885.828717.271410@r34g2000hsd.googlegroups.com> On Jul 8, 8:50 am, Christoph Zwerschke wrote: > Did you run this? > With Py < 2.5 I get a syntax error, and with Py 2.5 I get: > > new.__class__ = old.__class__ > TypeError: __class__ must be set to a class > > -- Chris Damn, I'd have sworn I ran the final copy that I posted, but apparently I did manage to have a typo creep in as I was prettifying the code. You need to lose the '()' in the definition of Empty. (I'd orignally had it subclass Exception but discovered that it wasn't needed.) class Empty: pass I can't figure out the other complaint, though, as old.__class_ should be a class. I guess I need to upgrade; I am using PythonWin 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on win32. (Of course, at work they're still stuck on 2.4.2.) Printing type(old.__class__) gives me ; maybe using setattr(new, '__class__', old.__class__) instead of the assignment would work, or maybe it's a bug/feature introduced in 2.5. (Trying this code: class Empty(old.__class__): pass brings us back to the "TypeError: function takes exactly 5 arguments (0 given)" message that we're trying to avoid.) Anyway, running the corrected version under 2.4.X gives me this: Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework \scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\dentos\Desktop\scripting \modify_message.py", line 19, in ? test(lambda: unicode('\xe4')) File "C:\Documents and Settings\dentos\Desktop\scripting \modify_message.py", line 16, in test raise modify_message(e, lambda: str(e) + ", sorry!") UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128), sorry! >>> From hexamorph at gmx.net Tue Jul 31 16:55:53 2007 From: hexamorph at gmx.net (Hexamorph) Date: Tue, 31 Jul 2007 22:55:53 +0200 Subject: Iteration over strings In-Reply-To: <46AF9F55.20105@gmx.net> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> <46AF7A49.3040804@jayloden.com> <46AF8046.7090702@gmx.net> <496954360707311307y7d503b8eybd72795c8e699104@mail.gmail.com> <46AF9B2D.8040501@jayloden.com> <46AF9F55.20105@gmx.net> Message-ID: <46AFA1D9.1010707@gmx.net> Hexamorph schrieb: > Jay Loden schrieb: >> >> I have to agree with you WRT to the Python documentation, it does tend >> to be lacking and difficult to find things at times. Hmm, I find the Python documentation just excellent. You are searching for a *string* related problem? Then just check the *string* class. Also try the dir() function, like dir(some_string_variable) If you come from a C++ background this should be familar to you. Check the appropriate class before trying some "procedural" way. Anyway, glad we could help :) From ladynikon at gmail.com Tue Jul 10 13:50:30 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Tue, 10 Jul 2007 13:50:30 -0400 Subject: Phoenix-iTorrent: iTunes Bit Torrent client v 0.3 release In-Reply-To: References: Message-ID: <59f9c5160707101050x3be2cd94k64b30270182fceae@mail.gmail.com> How is this related to python? From danb_83 at yahoo.com Fri Jul 6 01:13:04 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Thu, 05 Jul 2007 22:13:04 -0700 Subject: Where is the syntax for the dict() constructor ?! In-Reply-To: <1i0snor.ir5kakobtfkrN%aleax@mac.com> References: <468D1D9D.6060002@gmail.com> <468D3445.2060408@gmail.com> <1i0snor.ir5kakobtfkrN%aleax@mac.com> Message-ID: <1183698784.845237.185470@m36g2000hse.googlegroups.com> On Jul 5, 10:19 pm, a... at mac.com (Alex Martelli) wrote: > Neil Cerutti wrote: > > Besides, a string is an excellent epresentation for a zip code, > > since arithmetic upon them is unthinkable. > > Absolutely! Excel, unless you remedied that later with a column > operation, would turn some East Coast zipcodes into 3- and 4-digit > numbers (dropping the leading 0s), exactly because it's so obtuse as to > try to "treat as numbers" entries that are all-digits. What's even worse is having it treat credit card numbers as numbers. Which wouldn't be so much of a problem if they were 15 digits. But they're 16 digits. From fdu.xiaojf at gmail.com Mon Jul 30 22:50:00 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Tue, 31 Jul 2007 10:50:00 +0800 Subject: From D In-Reply-To: References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> Message-ID: <46AEA358.7010007@gmail.com> Gabriel Genellina wrote: > En Tue, 24 Jul 2007 11:10:53 -0300, Stargaming > escribi?: > >> On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote: >> >>> There are various things I like about the D language that I think Python >>> too may enjoy. Here are few bits (mostly syntactical ones): >>> >>> 1) (we have discussed part of this in the past) You can put underscores >>> inside number literals, like 1_000_000, the compiler doesn't enforce the >>> position of such underscores, so you can also put them like this: >>> 1_00_000. You can put them in literals of decimals, binary, hex, etc. I >> Sounds like a good thing to be but the arbitrary positioning doesnt make >> any sense. Additionally, I'd suggest 10**n in such cases (eg. 10**6). > > Why not? Because in English major numbers are labeled in thousands? > (thousand, million, billion...) > In India, they're grouped by two after the first thousand; in China, > they're grouped each 4 digits (that is, there is a single word for "ten > thousands" = wan4 = ?, and the next required word is for 10**8 = yi4 = ?) > Yes, in China numbers are grouped each 4 digits while it is different in other countries, so I think it would be better if we could put arbitrary white spaces inside number literals. From aahz at pythoncraft.com Sat Jul 7 13:45:48 2007 From: aahz at pythoncraft.com (Aahz) Date: 7 Jul 2007 10:45:48 -0700 Subject: Mixing Python and C threads References: Message-ID: In article , =?utf-8?b?U3TDqXBoYW5l?= Larouche 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). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I support the RKAB From sebzzz at gmail.com Fri Jul 27 13:40:23 2007 From: sebzzz at gmail.com (sebzzz at gmail.com) Date: Fri, 27 Jul 2007 17:40:23 -0000 Subject: Removing certain tags from html files Message-ID: <1185558023.501016.90050@d30g2000prg.googlegroups.com> Hi, I'm doing a little script with the help of the BeautifulSoup HTML parser and uTidyLib (HTML Tidy warper for python). Essentially what it does is fetch all the html files in a given directory (and it's subdirectories) clean the code with Tidy (removes deprecated tags, change the output to be xhtml) and than BeautifulSoup removes a couple of things that I don't want in the files (Because I'm stripping the files to bare bone, just keeping layout information). Finally, I want to remove all trace of layout tables (because the new layout will be in css for positioning). Now, there is tables to layout things on the page and tables to represent tabular data, but I think it would be too hard to make a script that finds out the difference. My question, since I'm quite new to python, is about what tool I should use to remove the table, tr and td tags, but not what's enclosed in it. I think BeautifulSoup isn't good for that because it removes what's enclosed as well. Is re the good module for that? Basically, if I make an iteration that scans the text and tries to match every occurrence of a given regular expression, would it be a good idea? Now, I'm quite new to the concept of regular expressions, but would it ressemble something like this: re.compile("")? Thanks for the help. From ptmcg at austin.rr.com Mon Jul 9 10:02:33 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 09 Jul 2007 07:02:33 -0700 Subject: What is the most efficient way to test for False in a list? In-Reply-To: <87tzsd21ld.fsf@mulj.homelinux.net> References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <7x7ipajvst.fsf@ruckus.brouhaha.com> <5fejp2F3cp3igU1@mid.individual.net> <5feju0F3c7pd1U1@mid.uni-berlin.de> <87tzsd21ld.fsf@mulj.homelinux.net> Message-ID: <1183989753.501355.70810@k79g2000hse.googlegroups.com> On Jul 9, 7:39 am, Hrvoje Niksic wrote: > "Diez B. Roggisch" writes: > > > > >>>> but what is your best way to test for for False in a list? > [...] > >>> status = all(list) > >> Am I mistaken, or is this no identity test for False at all? > > > You are mistaken. > > all take an iterable and returns if each value of it is true. > > Testing for truth is not the same as an identity test for False. OP's > message doesn't make it clear which one he's looking for. This > illustrates the difference: > > >>> False in [3, 2, 1, 0, -1] > > True # no False here>>> all([3, 2, 1, 0, -1]) > > False # false value present, not necessarily False I think if you want identity testing, you'll need to code your own; here's a map+lambda way: >>> any(map(lambda _ : _ is False,[3,2,1,0,-1])) False >>> any(map(lambda _ : _ is False,[3,2,1,0,-1,False])) True >>> -- Paul From jstroud at mbi.ucla.edu Tue Jul 24 15:27:18 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 24 Jul 2007 12:27:18 -0700 Subject: Good String Tokenizer In-Reply-To: <1185304914.344369.275770@q75g2000hsh.googlegroups.com> References: <1185304914.344369.275770@q75g2000hsh.googlegroups.com> Message-ID: JamesHoward wrote: > I have searched the board and noticed that there isn't really any sort > of good implementation of a string tokenizer that will tokenize based > on a custom set of tokens and return both the tokens and the parts > between the tokens. > > For example, if I have the string: > > "Hello, World! How are you?" > > And my splitting points are comma, and exclamation point then I would > expect to get back. > > ["Hello", ",", " World", "!", " How are you?"] > > Does anyone know of a tokenizer that will allow for this sort of use? > > Thanks in advance, > Jim Howard > Pyparsing: http://pyparsing.wikispaces.com/ James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From S.Mientki-nospam at mailbox.kun.nl Mon Jul 16 18:44:58 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 17 Jul 2007 00:44:58 +0200 Subject: how to find available classes in a file ? Message-ID: <2e302$469bf38f$d443bb3a$30036@news.speedlinq.nl> I want to have a (dynamically) list of all classes defined in a py-file. Is there a way of getting this list, without manually parsing the file ? thanks, Stef Mientki From jeff at jmcneil.net Fri Jul 20 12:02:31 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Fri, 20 Jul 2007 12:02:31 -0400 Subject: subprocess (spawned by os.system) inherits open TCP/UDP/IP port In-Reply-To: References: Message-ID: <82d28c40707200902w54e14f82lad5217f69edae2dc@mail.gmail.com> The open file descriptor/socket shouldn't "move" between processes when you kill the parent. When os.system forks, anything you've got open in the parent will transfer to the child. Both descriptors reference the same open port. Running the same 'ss' and 'cc' code you've supplied behaves like that on my workstation: [jeff at marvin ~]$ cat ss.py import socket UDPSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) UDPSock.bind(('', 12345)) import os os.system("python cc.py") [jeff at marvin ~]$ cat cc.py import time time.sleep(2036) Corresponding lsof output when the above code runs shows the following before killing the parent. [jeff at marvin ~]$ /usr/sbin/lsof | grep jeff | grep UDP python 18713 jeff 3u IPv4 34004 UDP *:italk python 18714 jeff 3u IPv4 34004 UDP *:italk I don't believe FD_CLOEXEC will not stop the child from inheriting your open file descriptors. Rather, it will ensure they're closed when execl(3) and friends are called. -Jeff On 7/20/07, alf wrote: > > Jean-Paul Calderone wrote: > > > > > You can avoid this, if you like. Set FD_CLOEXEC on the socket after you > > open it, before you call os.system: > > > > old = fcntl.fcntl(s.fileno(), fcntl.F_GETFD) > > fcntl.fcntl(s.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC) > > > > thx for responding (I was about to send the question to twisted mailing > list too ;-). > > > still would like to find out why it is happening (now FD_CLOEXEC > narrowed may yahooing/googling searches). While realize that file > descriptors are shared by forked processes it is still weird why the > port moves to the child process once parent gets killed. what it the > parent got multiple subprocesses. > > Plus it is kind of unintuitive os.system does not protect from such > behavoir which is for me more an equivalent of like issuing a ne > wcommand/ starting a process from the shell. > > Thx, > > -- > alf > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Xin.Zheng at jpl.nasa.gov Wed Jul 11 14:48:40 2007 From: Xin.Zheng at jpl.nasa.gov (Jason Zheng) Date: Wed, 11 Jul 2007 11:48:40 -0700 Subject: os.wait() losing child? In-Reply-To: References: <4694903B.8000105@cosc.canterbury.ac.nz> Message-ID: Matthew Woodcraft wrote: > greg wrote: >> I've figured out what's going on. The Popen class has a >> __del__ method which does a non-blocking wait of its own. >> So you need to keep the Popen instance for each subprocess >> alive until your wait call has cleaned it up. > > I don't think this will be enough for the poster, who has Python 2.4: > in that version, opening a new Popen object would trigger the wait on > all 'outstanding' Popen-managed subprocesses. > > It seems to me that subprocess.py assumes that it will do all wait()ing > on its children itself; I'm not sure if it's safe to rely on the > details of how this is currently arranged. > > Perhaps a better way would be for subprocess.py to provide its own > variant of os.wait() for people who want 'wait-for-any-child' (though > it would be hard to support programs which also had children not > managed by subprocess.py). > > -M- > Thanks, that's exactly what I need, my program really needs the os.wait() to be reliable. Perhaps I could pass a flag to Popen to tell it to never os.wait() on the new pid (but it's ok to os.wait() on other Popen instances upon _cleanup()). From no at no.no Tue Jul 10 15:23:07 2007 From: no at no.no (Daniel) Date: Tue, 10 Jul 2007 22:23:07 +0300 Subject: bool behavior in Python 3000? References: Message-ID: >> > Do you care to explain what is broken? >> My preference would be for the arithmetic operations *,+,- >> to be given the standard interpretation for a two element >> boolean algebra: >> http://en.wikipedia.org/wiki/Two-element_Boolean_algebra > > If I understand this right, the biggest difference from the current > implementation would be that:: > > True + True == True > > instead of: > > True + True == 2 > > What's the advantage of that? Could you give some use cases where that > would be more useful than the current behavior? > I prefer the use of 'and' and 'or', and they feel more pythonic than & and + -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From donn at u.washington.edu Wed Jul 11 18:57:09 2007 From: donn at u.washington.edu (Donn Cave) Date: Wed, 11 Jul 2007 15:57:09 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <7xejjjjtqb.fsf@ruckus.brouhaha.com> Message-ID: In article , "Chris Mellon" wrote: > I don't think it's the syntax that keeps people from checking for > errors. It's more a difference of error handling philosophy - in > Python, if you can't do something sensible with an error you just > pretend it can't happen and rely on your caller to do something > sensible. In a lot of cases, this means that nobody does anything and > errors propagate all the way up and thats fine. > > What you're describing with the type inference solution feels more > like Javas checked exceptions to me, where the compiler ends up > signaling an error if you don't pretend like you considered the error > condition. In Java, at least, this tends to create actively harmful > code where you stick in empty or otherwise useless exception handlers > to shut up the compiler, and when "can't happen" errors actually do > occur they are lost or worse. Maybe this doesn't happen in Haskel, but > I'd be interested in how it doesn't. As Paul mentioned parenthetically, Haskell's type system doesn't support all this by itself. You can write a function that is defined for only some cases of a value, so indeed you can fail to check for an error status, or match the first element of an empty list, and in general it is quite possible to get a run time error in this way. There is naturally some dissatisfaction with this state of affairs. Another point about this is that a The second point, about syntax and failure handling is another matter. In the example - > > g1 = re.match(pattern, string) > a = g2.group(0) > g2 = re.match(template % a, other_string) > result = g2.group(1) > ... if all these re functions have a monad type that supports it, this would be a sequence of monad bindings with failure options. The algebra of these things is such that a failure short circuits the larger expression just like a false result short circuits evaluation of an "and" sequence. I wouldn't say this prevents data errors in Haskell, though, it only simplifies them in a sequential computation where such a monad type is convenient. I missed the type error -> data error point that this evidently was all supposed to be some response to, and I don't know what that was supposed to mean, but Haskell's type system addresses just what we all would expect, the structural consistency of the program in terms of data types. It doesn't generally prevent data errors or correct your misunderstanding of an algorithm or in general avoid every kind of error. What it does, though, it does rather well. Donn Cave, donn at u.washington.edu From not_my_email at work Thu Jul 5 20:03:40 2007 From: not_my_email at work (M Friedeman) Date: Fri, 06 Jul 2007 12:03:40 +1200 Subject: A different debugger Message-ID: <468d86dd@clear.net.nz> Try a different type of debugger. This one does not need you to set breakpoints. Run the program once and after that everything is available to you. You then just scroll to any line you're interested in and click the variable. It requires Firefox and Python 2.5. http://codeinvestigator.googlepages.com/main From Muffin at BottomPost.Trim Tue Jul 17 12:01:11 2007 From: Muffin at BottomPost.Trim (Muffin) Date: Tue, 17 Jul 2007 12:01:11 -0400 Subject: Newbie: freebsd admin scripting Message-ID: I am using python for the first time on Unix and on FBSD. I need a few pointer, tips or tricks on scripting on config files. Mostly admin type configs like the rc.conf file usually setup like: someiteam=somevalue #sometype of description Where I would like to toggle the somevalue in an easy way. I realize I could parse it with reg expression but that sounds kinda complicated. Is there an easer way a Unix python way of dealing with these type of config files. I found a built in mod for parseconfig but it deal with .ini file styles (windows) that include a [section] header as well as uses someiteam=somevalue format. I believe it requires the header though. Books or howtos regarding Unix admin scripting(python) would be great. Is this type of scripting mainly executing a Unix command and capturing and parsing its output like this: x=command.getoutput("ifconfig") and them parsing x for what I want or is there a name space I can call to get , for example, a list of all interfaces? I have mainly used python in windows using the com space or win32 api aside from the base python lib, on Unix I am lost on what to do or how things are generally done. Advise on how to "think" in Unix python terms if that makes any sense. Thx From beliavsky at aol.com Tue Jul 24 10:27:56 2007 From: beliavsky at aol.com (Beliavsky) Date: Tue, 24 Jul 2007 07:27:56 -0700 Subject: Where do they tech Python officialy ? In-Reply-To: <215fn4-60g.ln1@lairds.us> References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <215fn4-60g.ln1@lairds.us> Message-ID: <1185287276.902750.215240@d55g2000hsg.googlegroups.com> On Jul 23, 1:27 pm, cla... at lairds.us (Cameron Laird) wrote: > Autodidacticism is an alternative; feel free to regard as a member of > that class. > > If you, for example, were to teach yourself Python, then > volunteer with prominent extensions or even the core (there's > plenty to do in regard to documentation and testing), you'd > soon have accumulated quite a bit of experience that enlightened > employers recognize is as professional as any other. I'd guess that it's a lot harder to create/extend Python than to use it, so I suggest that the OP first focus on becoming good Python programmers. An important aspect of a course in Python programming would be instructor comments on one's code. I wonder if any trainers do code reviews by email. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jul 30 11:56:16 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 30 Jul 2007 17:56:16 +0200 Subject: Replacing overloaded functions with closures. In-Reply-To: <1185807536.021216.278500@22g2000hsm.googlegroups.com> References: <1185807536.021216.278500@22g2000hsm.googlegroups.com> Message-ID: <46ae0a1e$0$10318$426a74cc@news.free.fr> king kikapu a ?crit : > Hi, > > i am trying, to no avail yet, to take a C#'s overloaded functions > skeleton and rewrite it in Python by using closures. > I read somewhere on the net (http://dirtsimple.org/2004/12/python-is- > not-java.html) that in Python we can reduce code duplication for > overloaded functions by using closures. Then you should re-read more carefully this article. While closures are effectively a great way to reduce code duplication, they are by no mean presented as a way to replace function overloading - or at least not directly[1]. The idea presented here is to use closures to write functions that will return "parameterized" functions, and (IMHE at least) this is mostly useful in frameworks, ORMs and like. [1] you may want to have a look at another work by the same author: http://peak.telecommunity.com/DevCenter/VisitorRevisited which introduces the RuleDispatch generic function package. HTH From eopadoan at altavix.com Wed Jul 18 15:35:11 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Wed, 18 Jul 2007 16:35:11 -0300 Subject: Pickled objects over the network In-Reply-To: <20070718095248.4947.1882106103.divmod.quotient.13020@ohm> References: <9c8d48280707171457p4448fdf3of40562bf62a18fc6@mail.gmail.com> <20070718095248.4947.1882106103.divmod.quotient.13020@ohm> Message-ID: On 7/18/07, Jean-Paul Calderone wrote: > On Tue, 17 Jul 2007 14:57:16 -0700, Walker Lindley wrote: [...] > The obvious thing you're doing wrong is using pickle over a network. ;) > > http://jcalderone.livejournal.com/15864.html Ok, maybe not the best tools to the job, but there are some more secure alternatives: http://trustedpickle.sourceforge.net/ http://home.gna.org/oomadness/en/cerealizer/index.html -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From CarpeSkium at gmail.com Thu Jul 12 22:59:53 2007 From: CarpeSkium at gmail.com (CarpeSkium at gmail.com) Date: Fri, 13 Jul 2007 02:59:53 -0000 Subject: Getting values out of a CSV Message-ID: <1184295593.638409.22910@22g2000hsm.googlegroups.com> How do I access the value in the second row in the first position of a CSV? Or the 3rd row, in the fifth position? a,b,c,d,e,f,g,h,i j,k,l,m,n,o,p,q,r r,s,t,v,w,x,y,z I'd want to get at "j" and "w". I know I can do import csv reader = csv.reader(open("some.csv", "rb")) for row in reader: print row[0] to get the first value in EVERY row, but I don't want that. Thanks for the help. From bill.punch at gmail.com Tue Jul 31 12:44:55 2007 From: bill.punch at gmail.com (bill.punch at gmail.com) Date: Tue, 31 Jul 2007 16:44:55 -0000 Subject: Where do they tech Python officialy ? In-Reply-To: <1i23wyk.avc945i4dwsiN%aleax@mac.com> 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: <1185900295.571150.93470@g12g2000prg.googlegroups.com> On Jul 31, 11:37 am, al... at mac.com (Alex Martelli) wrote: > 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. That will take a > while, but not as long as getting a college degree (and it will be far > cheaper than the degree). > > Alex Starting this Fall, Michigan State University's computer science department is moving to Python for its introductory courses. Student's following the ugrad curriculum will be exposed to both Python (early) and C++ (later). We feel this gives our students the best of both worlds: a high level scripting language that is easier to work with and provides many modules to do actual work, and an efficient, lower level language for speed and to interface with OS, graphics, networks etc. If you want more information, visit the dept. web pages at http://www.cse.msu.edu. However, and not suprisingly, things are out of date there and will probably not be up to date till the semester starts. So if you want something now, please send email to "bill.punch AT gmail.com" From carsten at uniqsys.com Sun Jul 8 22:24:10 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 08 Jul 2007 22:24:10 -0400 Subject: What is the most efficient way to test for False in a list? In-Reply-To: References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> Message-ID: <1183947850.3165.39.camel@localhost.localdomain> On Sun, 2007-07-08 at 18:32 -0700, Evan Klitzke wrote: > On 7/8/07, lex wrote: > > Of course there is the always the iteration method: > > > > list = [1, True, True, False, False, True] > > status = True > > for each in list: > > status = status and each > > > > but what is your best way to test for for False in a list? > > In general, you can just do: > > if something in list: > do_something() Caution! This tests whether at least one entry in 'list' is *equal* to 'something'. It is very unusual to want to test whether an object is equal to True (or False). Usually one simply wants to know whether the bool() value of that object is True (or False). While it makes no difference with the contrived example above, in general your suggestion may give unexpected results. The following variant, making use of a generator expression to take the bool() of each entry, will always work correctly: if False in (bool(x) for x in list): do_something() But then again, in Python 2.5 you can use all() as suggested by Paul Rubin: if not all(list): do_something() I'd also like to point out, since nobody has so far, that 'list' is a terrible name for a list because it shadows the name for the list type. -- Carsten Haese http://informixdb.sourceforge.net From mail at microcorp.co.za Sun Jul 8 04:30:47 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 8 Jul 2007 10:30:47 +0200 Subject: socket: connection reset by server before client gets response References: <1183819907.249945.239700@o11g2000prd.googlegroups.com> <1183827514.109496.252870@d30g2000prg.googlegroups.com> Message-ID: <00bb01c7c13f$56973900$03000080@hendrik> "ahlongxp" wrote: > me again. > > "Connection reset by peer" happens about one in fifth. > I'm using python 2.5.1 and ubuntu 7.04. > Try to wait a while in the server thread, after sending the message before closing the connection, to give the message time to get transmitted. time.sleep(0.5) should do it... - Hendrik From andreww at datanet.ab.ca Tue Jul 10 10:10:39 2007 From: andreww at datanet.ab.ca (Andrew Warkentin) Date: Tue, 10 Jul 2007 07:10:39 -0700 Subject: Best architecture for proxy? Message-ID: <1184076639.815417.48390@g4g2000hsf.googlegroups.com> I am going to write a general-purpose modular proxy in Python. It will consist of a simple core and several modules for things like filtering and caching. I am not sure whether it is better to use multithreading, or to use an event-driven networking library like Twisted or Medusa/ Asyncore. Which would be the better architecture to use? From shabda.raaj at gmail.com Mon Jul 16 10:45:48 2007 From: shabda.raaj at gmail.com (shabda raaj) Date: Mon, 16 Jul 2007 14:45:48 -0000 Subject: Implementaion of random.shuffle In-Reply-To: References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> Message-ID: <1184597148.692325.36590@x35g2000prf.googlegroups.com> On Jul 16, 5:53 pm, Steve Holden wrote: > shabda raaj wrote: > > I was going through the docs for module-random > > And I came through this, > > > * shuffle*( x[, random]) > > > Shuffle the sequence x in place. The optional argument random is a > > 0-argument function returning a random float in [0.0, 1.0); by > > default, this is the function random(). > > > Note that for even rather small |len(x)|, the total number of > > permutations of x is larger than the period of most random number > > generators; this implies that most permutations of a long sequence > > can never be generated. > > > Why would we need to generate the total number of permutations for the > > list while trying to shuffle it? Should not we just use a knuth shuffle > > which > > does not require us to generate the total number of permutations. As > > long as len(x) is smaller than period of random number generator, a > > permutation can be generated. > > > A quick first draft of implemetation might be, > > > import random > > > def shuffle(list_): > > for i in range(len(list_)): > > j = random.randint(i, len(list_)-1) > > list_[i], list_[j] = list_[j], list_[i] > > if __name__ == '__main__': > > a = range(100) > > shuffle(a) > > print a > > > This is my first post to the list, I am not sure if this is the correct > > place to ask these questions. Please advise if this is not the correct > > place. > > This is an excellent place to post the question. If it were to turn out > that your concerns were genuine that you might end up posting a patch to > the issue tracker and possibly then involving the developers. Until your > suspicions are confirmed, however, let the developers get on with > development. > > You, like all (or most) Python users, have the source of the standard > library at your disposal. Had you looked at .../Lib/random.py you would > have found that the implementation of shuffle() reads as follows: > > def shuffle(self, x, random=None, int=int): > """x, random=random.random -> shuffle list x in place; return None. > > Optional arg random is a 0-argument function returning a random > float in [0.0, 1.0); by default, the standard random.random. > """ > > if random is None: > random = self.random > for i in reversed(xrange(1, len(x))): > # pick an element in x[:i+1] with which to exchange x[i] > j = int(random() * (i+1)) > x[i], x[j] = x[j], x[i] > > So it would appear that the developers chose the Knuth algorithm (with a > slight variation) for *their* implementation. Now you have to ask > yourself whether your surmise is genuinely correct (in which case the > documentation may contain a bug) or whether the documentation is indeed > correct and you are in error. > > Note that there is no intent to generate all permutations of the list > and then choose one (that would indeed be a sub-optimal solution). The > documentation is only talking about whether the algorithm can in theory > produce all possible permutations of all possible input lists. It's > possible that the comment in the documentation is left over from an > earlier version. What do you 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 ------------- Oh, I wasn't aware that I could see the source of all python modules. I guess, then the implementation is correct(its just the knuth shuffle, moving downward), its just the doc which is in error. Might be we should log a doc bug for this? --Shabda From mtobis at gmail.com Fri Jul 20 22:15:23 2007 From: mtobis at gmail.com (Michael Tobis) Date: Sat, 21 Jul 2007 02:15:23 -0000 Subject: converting 64-bit fixed-point to float In-Reply-To: <1i1k9cc.1hyy4zm1ybovgwN%johnmfisher@comcast.net> References: <1i1k9cc.1hyy4zm1ybovgwN%johnmfisher@comcast.net> Message-ID: <1184984123.527311.139250@d55g2000hsg.googlegroups.com> It appears to be correct for positive numbers. if conval >= 2**16: conval -= 2**32 would appear to patch things up. It's not very pretty, though. You could at least start with input1 = [c_ushort(item) for item in input] instead of your first 9 lines. mt From mail at gedankenkonstrukt.de Sat Jul 7 16:28:23 2007 From: mail at gedankenkonstrukt.de (Thomas Wittek) Date: Sat, 07 Jul 2007 22:28:23 +0200 Subject: Pretty Printing Like Tidy for HTML In-Reply-To: References: <1183833340.610662.197060@o11g2000prd.googlegroups.com> Message-ID: Daniel: > On Sat, 07 Jul 2007 21:35:40 +0300, David > wrote: >> Is there a pretty printing utility for Python, something like Tidy for >> HTML? > > Why not just write python as it should be written? Oh, you write all the code you use yourself? It's relatively common that you have some "legacy" code (e.g. from (ex-)colleages) that doesn't conform to your style preferences/your companys coding guidelines. In such a case those tools can be very helpful. -- Thomas Wittek http://gedankenkonstrukt.de/ Jabber: streawkceur at jabber.i-pobox.net From shahjapan at gmail.com Tue Jul 3 09:01:51 2007 From: shahjapan at gmail.com (Japan Shah) Date: Tue, 03 Jul 2007 13:01:51 -0000 Subject: connecting to serial port + python Message-ID: <1183467711.963266.137590@m37g2000prh.googlegroups.com> Hello, I am trying to connect my Nokia 6610 using usb cable, I have installed usb-serial driver of it. I hv tested it with Hyperterminal and it works fine. but when I wrote a python script I am not able to receive the responce from the device. import os import re import time import sys from threading import Thread import serial class connect_serial(Thread): def __init__(self,socks): Thread.__init__(self) self.sock = socks self.count = 0 def run(self): self.count = 0 try: while 1: self.count +=1 if (self.count>=5): break lines = self.sock.read(100) if lines: print lines print 'read success-----------------------------------------------' else: print 'nothing to read',str(self.getName()) except Exception,e: print self.getName() print time.ctime() print try: conn1 = serial.Serial(4) conn1.baudrate = '9600' conn1.parity = serial.PARITY_EVEN conn1.timeout=1 except Exception,e: print 'port is Buzy' sys.exit(-1) print '------------------------------' print 'getSupportedBaudrates',conn1.getSupportedBaudrates() print 'getSupportedByteSizes',conn1.getSupportedByteSizes() print 'getSupportedParities',conn1.getSupportedParities() print 'getSupportedStopbits',conn1.getSupportedStopbits() print '------------------------------' print 'getBaudrates',conn1.getBaudrate() print 'getByteSizes',conn1.getByteSize() print 'getParities',conn1.getParity() print 'getStopbits',conn1.getStopbits() print '------------------------------' print 'port is in use',conn1.portstr list1 = [] command = ['AT','ATI','ATl1','AT+GMMM'] for cmd in command: conn1.write(str(cmd)) th = connect_serial(conn1) list1.append(th) th.start() for th1 in list1: print 'started joining',th1.getName(), 'counter :',th1.count th1.join() print time.ctime() From steve at holdenweb.com Mon Jul 16 13:59:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 16 Jul 2007 13:59:24 -0400 Subject: Best method for inter process communications In-Reply-To: <1184606522.541918.18870@22g2000hsm.googlegroups.com> References: <1184606522.541918.18870@22g2000hsm.googlegroups.com> Message-ID: JamesHoward wrote: > I am looking for a way of performing inter process communication over > XML between a python program and something else creating XML data. > > What is the best way of performing this communication? I could bind a > socket to localhost and perform the data transfer that way, but that > seems inefficient due to the addition of TCP/IP or UDP/IP overhead. > Is there a way to stream data via a custom datastream (I.E. not STDIO, > STDERR, etc)? > Nothing that portable across different platforms, I suspect. However I see no reason why you can't use pipelines in Unix (in other words what's wrong with using stdin/stdout?), and Windows offers something called a named pipe. You could even use shared memory if you wanted. Given the radically inefficient representations that XML typically requires, however, I think that worrying about localhost socket overhead is unnecessary: if your application was *that* critical you wouldn't be using XML in the first place. 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 Tue Jul 10 19:10:26 2007 From: jjl at pobox.com (John J. Lee) Date: Tue, 10 Jul 2007 23:10:26 GMT Subject: Passing a CookieJar instead of a cookieproc to urllib2.build_opener References: <1184028331.849197.263130@g4g2000hsf.googlegroups.com> Message-ID: <873azvg8il.fsf@pobox.com> "rrenaud at gmail.com" writes: > urllib2.build_opener happily accepts and ignores a FileCookieJar. I > had a bug in my code which looked like > > urllib2.build_opener(func_returning_cookie_jar()) > > which should have been > > urllib2.build_opener(HTTPCookieProcessor(func_returning_cookie_jar()) > > The problem is that the code ran happily without actually sending the > cookie, the CookieJar was just ignored. I think that build_opener > should throw an exception when add_handler doesn't actually add. > > Is this worth filing a bug for, or is it acceptable behavior? IMO, it's worth filing iff: a) you think it's worthwhile (this one sounds worthwhile to me) b) you write a patch and are prepared to patiently keep at it until it gets applied Make sure your patch follows PEP 8. Make sure the patch includes test and documentation updates / additions (you don't need to write docs in LaTeX format -- other people will do the conversion to LaTeX for you if you like). If there are no doc changes required, state that explicitly in the patch tracker. If your patch gets ignored, review five other patches, and post to python-dev stating you have done so and requesting that your patch is reviewed (there's a shortage of patch reviewers). John From steve at holdenweb.com Thu Jul 26 23:00:38 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Jul 2007 23:00:38 -0400 Subject: instantiate a 'classobj' In-Reply-To: <1185501791.311662.220980@57g2000hsv.googlegroups.com> References: <1185501791.311662.220980@57g2000hsv.googlegroups.com> Message-ID: <46A95FD6.9020906@holdenweb.com> westymatt wrote: > I have a class where a parameter to its constructor is a type(param) = > 'classobj'. How would I go about instantiating that given it has no > constructor. > Just call the parameter: if it's of type classobj then it's callable, and calling it will create an instance of the class. >>> class MyClass: ... def __init__(self, a, b): ... self.a = a ... self.b = b ... >>> MyClass >>> type(MyClass) >>> def builder(c): ... return c(3, 4) ... >>> builder(MyClass) <__main__.MyClass instance at 0x7ff281cc> >>> 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 giles_brown at hotmail.com Fri Jul 6 08:46:41 2007 From: giles_brown at hotmail.com (Giles Brown) Date: Fri, 06 Jul 2007 05:46:41 -0700 Subject: VB frontend to Python COM backend In-Reply-To: <1183701494.979323.301500@d30g2000prg.googlegroups.com> References: <1183701494.979323.301500@d30g2000prg.googlegroups.com> Message-ID: <1183726001.746584.110670@g13g2000hsf.googlegroups.com> On 6 Jul, 06:58, nik wrote: > I have a VB6 application that I would like to attach to a python > communications application. > > I have come across several discussions on using VB with a Python COM > back-end, but no starting point. I haven't had anymore luck with > google at finding out what this method is called and where to find > more information or examples on it. I would really appreciate it if > someone could point me in the right direction for using python objects > from VB. > > Thank you, > Nik Try this for starters... http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html Giles From exarkun at divmod.com Thu Jul 12 07:38:42 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 12 Jul 2007 07:38:42 -0400 Subject: variable naming query In-Reply-To: <1184236383.691966.56530@w3g2000hsg.googlegroups.com> Message-ID: <20070712113842.4947.1761166948.divmod.quotient.10696@ohm> On Thu, 12 Jul 2007 10:33:03 -0000, loial wrote: >I'ma a newbie python user and would like clarification on variable >naming conventions. > >What is the difference between > >self.myvariable This is the convention for public attributes. >self._myvariable This is the convention for private attributes. >self.__myvariable This causes the name to be mangled in an inconvenient way by the runtime. You probably /don't/ want to name your variables like this, since the consequence is primarily that the result is harder to use. Jean-Paul From shabda.raaj at gmail.com Tue Jul 17 02:44:05 2007 From: shabda.raaj at gmail.com (shabda raaj) Date: Tue, 17 Jul 2007 06:44:05 -0000 Subject: Implementaion of random.shuffle In-Reply-To: References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> <87d4ys9z46.fsf@mulj.homelinux.net> Message-ID: <1184654645.406393.43250@g12g2000prg.googlegroups.com> On Jul 16, 8:29 pm, Steve Holden wrote: > Hrvoje Niksic wrote: > > Steve Holden writes: > > >> So it would appear that the developers chose the Knuth algorithm > >> (with a slight variation) for *their* implementation. Now you have > >> to ask yourself whether your surmise is genuinely correct (in which > >> case the documentation may contain a bug) or whether the > >> documentation is indeed correct and you are in error. > > > That is a good question. The random module uses the Mersenne twister, > > which has a repetition period of 2**19937. The number of n-sized > > permutations of a list with n elements is n!, while each shuffle > > requires n calls to the PRNG. This means that to be able to generate > > all permutations, the PRNG must have a period of at least n! * n. In > > the case of MT, it means that, regarding the period, you are safe for > > lists with around 2079 elements. shuffle's documentation may have > > been written before the random module was converted to use the MT. > > > 2**19937 being a really huge number, it's impossible to exhaust the > > Mersenne twister by running it in sequence. However, there is also > > the question of the spread of the first shuffle. Ideally we'd want > > any shuffle, including the first one, to be able to produce any of the > > n! permutations. To achieve that, the initial state of the PRNG must > > be able to support at least n! different outcomes, which means that > > the PRNG must be seeded by at least log2(n!) bits of randomness from > > an outside source. For reference, Linux's /dev/random stops blocking > > when 64 bits of randomness are available from the entropy pool, which > > means that, in the worst case, shuffling more than 20 elements cannot > > represent all permutations in the first shuffle! > > Thanks for this thoughtful analysis. I believe we can therefore leave > the documentation (which almost certainly *was* written before the > adoption of MT) alone for 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 ------------- The code for shuffle is if random is None: random = self.random for i in reversed(xrange(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = int(random() * (i+1)) x[i], x[j] = x[j], x[i] With j = int(random() * (i+1)) being the only call to random(). As long as (i + 1) is not large enough so that j is generated with equal probability in range [0, i] we would get all permutations with equal probability. With MT with period of 2**19937 (i+1) would have to be really large before this the case. Anyway, is there some test harness we can run to test the robustness of shuffle? We can run that test harness for large values and see at what point all permutations are not possible or come with unequal probability. From istvan.albert at gmail.com Fri Jul 27 09:07:32 2007 From: istvan.albert at gmail.com (Istvan Albert) Date: Fri, 27 Jul 2007 13:07:32 -0000 Subject: zip() function troubles In-Reply-To: References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> Message-ID: <1185541652.181931.105550@19g2000hsx.googlegroups.com> On Jul 27, 1:24 am, Peter Otten <__pete... at web.de> wrote: > When you are allocating a lot of objects without releasing them the garbage > collector kicks in to look for cycles. Try switching it off: > > import gc > gc.disable() Yes, this solves the problem I was experiencing. Thanks. Istvan From anoweb at gmail.com Tue Jul 17 13:38:03 2007 From: anoweb at gmail.com (anoweb) Date: Tue, 17 Jul 2007 17:38:03 -0000 Subject: merge two ranges Message-ID: <1184693883.762124.149880@z28g2000prd.googlegroups.com> I have two ranges of numbers and I need to determine if they overlap or adjacent and if so return a new range containing the values. The values are low and high for each pair, such that the first value of the tuple is always less than or equal to the second value in the tuple. for example: a = (0, 5) b = (5, 10) print getAdjacent(a, b) # output: (0, 10) print getAdjacent(b, a) # output: (0, 10) print getOverlap(a, b) # output: None print getOverlap(b, a) # output: None a = (0, 7) b = (3, 10) print getAdjacent(a, b) # output: None print getAdjacent(b, a) # output: None print getOverlap(a, b) # output: (0, 10) print getOverlap(b, a) # output: (0, 10) a = (0, 90) b = (5, 10) print getAdjacent(a, b) # output: None print getAdjacent(b, a) # output: None print getOverlap(a, b) # output: (0, 90) print getOverlap(b, a) # output: (0, 90) a = (0, 5) b = (12, 20) print getAdjacent(a, b) # output: None print getAdjacent(b, a) # output: None print getOverlap(a, b) # output:None print getOverlap(b, a) # output: None any easy way of doing this? From sgeiger at ncee.net Thu Jul 5 09:22:35 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Thu, 05 Jul 2007 08:22:35 -0500 Subject: Building a Python app with Mozilla In-Reply-To: <1068189.27726.BlRUCl8VTQA=.1183630734.squirrel@webmailer.hosteurope.de> References: <1183524527.709730.190290@q75g2000hsh.googlegroups.com> <5f30vsF3aicltU1@mid.individual.net> <1068189.27726.BlRUCl8VTQA=.1183630734.squirrel@webmailer.hosteurope.de> Message-ID: <468CF09B.9010300@ncee.net> Brett Cannon was doing some work with the Firefox security model to allow Python coding from within Firefox. He may have stopped doing the work because it would not lead to a PhD. I am really looking forward to seeing someone making this a possibility. Stefan Sonnenberg-Carstens wrote: > On Do, 5.07.2007, 03:45, greg wrote: > >> sjdevnull at yahoo.com wrote: >> >> >>> wxWidgets will give you native looking apps on both Linux and Windows >>> >> Well, maybe. There's more to getting a native feel than >> just using the right widgets. I once saw a Qt-based app on >> MacOSX that had tiny little buttons that were too small >> for the text they contained -- Aqua buttons just don't >> scale down like that. :-( >> >> -- >> Greg >> -- >> http://mail.python.org/mailman/listinfo/python-list >> >> >> > Qt based buttons don't either. > If some fool uses absolute positioning and sizing, > then it is not the toolkit to blame. > I'm using wxPython for instance and use the sizers and placeholders > there, so this is possible with Qt also. > So, perhaps (which I don't know) Aqua buttons simply don't permit > absolute stuff ? > Or the Aqua programmers read the user interface guidelines carefully ? > -- Shane Geiger IT Director National Council on Economic Education sgeiger at ncee.net | 402-438-8958 | http://www.ncee.net Leading the Campaign for Economic and Financial Literacy -------------- next part -------------- A non-text attachment was scrubbed... Name: sgeiger.vcf Type: text/x-vcard Size: 310 bytes Desc: not available URL: From cjames at callone.net Mon Jul 23 08:40:33 2007 From: cjames at callone.net (c james) Date: Mon, 23 Jul 2007 07:40:33 -0500 Subject: Pure Python equivalent of unix "file" command? In-Reply-To: <2007071915293516807-w3@w3com> References: <2007071915293516807-w3@w3com> Message-ID: Take a look at http://www.demonseed.net/~jp/code/magic.py W3 wrote: > Hi all, > > Just a quick one... Is there such a thing? > > Thanks, > /Walter From benc.nospam at gmail.com Mon Jul 2 12:00:19 2007 From: benc.nospam at gmail.com (Ben Cartwright) Date: Mon, 02 Jul 2007 16:00:19 -0000 Subject: Reading stdout and stderr of an external program In-Reply-To: <1183389787.481605.111160@k29g2000hsd.googlegroups.com> References: <1183389787.481605.111160@k29g2000hsd.googlegroups.com> Message-ID: <1183392019.371162.46060@n2g2000hse.googlegroups.com> > I need to be able to read the stdout and stderr streams of an external > program that I launch from my python script. os.system( 'my_prog' + > '>& err.log' ) and was planning on monitoring err.log and to display > its contents. Is this the best way to do this? from subprocess import Popen stdout, stderr = Popen('my_prog').communicate() --Ben From josiah.carlson at sbcglobal.net Tue Jul 10 23:31:44 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Tue, 10 Jul 2007 20:31:44 -0700 Subject: trouble controlling vim with subprocess on windows machine In-Reply-To: <1184058013.324624.220540@i38g2000prf.googlegroups.com> References: <1183970186.663847.4380@o61g2000hsh.googlegroups.com> <1184023825.646120.251060@d55g2000hsg.googlegroups.com> <5qFki.19733$2v1.4163@newssvr14.news.prodigy.net> <1184058013.324624.220540@i38g2000prf.googlegroups.com> Message-ID: <_5Yki.26304$C96.20298@newssvr23.news.prodigy.net> agc wrote: > Hi Josiah, > >>>> This recipe for asynchronous communication usingsubprocesscould be >>>> used to write an expect-like tool: >>>> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 > > I have played with the above recipe and it is excellent, > but could you please go into some more detail about what is needed > to make a cross platform [p]expect like (non-pty based) tool? We only get ptys. Unless you can figure out some incantation to fake the creation of a tty (so that ssh and other software don't conmplain), all you get is a pty. To make it work like expect, one would (strictly speaking) need to do the pattern matching that expect does, which may require writing a new regular expression library. > Specifically, could you describe how you would connect to > *another* interactive Python process with your subclass of > subprocess.Popen? > i.e: > > a = Popen('python', stdin=?, stdout=?, stderr=?) > #now run an interactive session with 'a' Some platforms have very strange buffering behavior with Python. What I have done in my own code (for creating a Python subprocess, though not using the subprocess module) is to do something like the following... python_cmd = ''' -u -c "import sys; \ sys.stderr=sys.__stderr__=sys.stdout;import __builtin__;\ __builtin__.quit=__builtin__.exit=\ 'use Ctrl-Break to restart *this* interpreter';import code;\ code.interact(readfunc=raw_input)"''' a = Popen(python_cmd, subprocess.PIPE, subprocess.PIPE) > I have tried several combinations of the above and I seem > to be stuck on the fact that python is interacting with a > 'tty', not 'std*'. Maybe I'm missing a basic piece? I've had buffering issues on certain platforms (Windows), error messages about not having a tty (when trying to control an ssh session on *nix and Windows), etc. Getting this to work for arbitrary programs that expect a tty, and/or being able to query the terminal for other information (dimension, terminal emulation, etc.), will be a chore, if not impossible. - Josiah From horpner at yahoo.com Mon Jul 30 09:02:17 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 30 Jul 2007 13:02:17 GMT Subject: Detecting __future__ features References: <1185800016.950517.43240@g4g2000hsf.googlegroups.com> Message-ID: On 2007-07-30, Andr? wrote: > On Jul 30, 9:39 am, Neil Cerutti wrote: >> I don't understand the qualification, "at runtime," you're >> making. What's wrong with just importing what you want and >> using it? If it's already been enabled, no harm will come from >> the import statement. >> > > I'm not the OP, so perhaps I am missing his intent. However, I > can see a good reason for asking this question. > > I seem to recall that the "from __future__ import" statement > can only be done at the beginning of a script. What if you are > designing a module meant to be imported, and used by other > programs over which you have no control? You can't use "from > __future__ import" in your module. So, you may have to find a > way to figure out what's been done. (the example given with > the division operator is a good one). Is "from __future__ import" really that lame? -- 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 bj_666 at gmx.net Wed Jul 4 16:40:02 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Jul 2007 20:40:02 GMT Subject: Find This Module References: <1183579207.226611.192520@57g2000hsv.googlegroups.com> Message-ID: <5f2et2F3a62csU6@mid.uni-berlin.de> On Wed, 04 Jul 2007 20:00:07 +0000, gregpinero at gmail.com wrote: > I'm looking at the source for the module sre_compile.py and it does > this import: > > import _sre > > But I can't find a file related to _sre anywhere. Where is it? And > more generally, how does one find the location of a built in module? It's built into the interpreter executable. In [85]: import _sre In [86]: _sre Out[86]: Ciao, Marc 'BlackJack' Rintsch From gianmaria at hotmail.com Sun Jul 29 16:14:52 2007 From: gianmaria at hotmail.com (Gianmaria) Date: Sun, 29 Jul 2007 22:14:52 +0200 Subject: Events: The Python Way References: Message-ID: "David Wilson" ha scritto nel messaggio news:mailman.1295.1185665717.22759.python-list at python.org... > Hi there, > > Python has no built-in way of doing this. You may consider writing > your own class if you like this pattern (I personally do): > > class Event(object): > def __init__(self): > self.subscribers = set() > > def __iadd__(self, subscriber): > self.subscribers.add(subscriber) > return self > > def __isub__(self, subscriber): > self.subscribers.pop(subscriber) > return self > > def __call__(self, *args, **kwargs): > for subscriber in self.subscribers: > subscriber(*args, **kwargs) > > > def HandleFoo(strng): > print "HandleFoo:", strng > > OnFoo = Event() > OnFoo += HandleFoo > > OnFoo("Test.") > > > On 29/07/07, Gianmaria wrote: >> Hi, >> i'm a .net programmer and i'm learnig python, so this question can be >> very >> stupid or easy for python programmers. I've a doubt about events.... here >> is >> what: >> >> in c# for example i can write a delegate and an event in this way... >> >> public delegate SomethingChangedHandler(string message); >> public event SomethingChangedHandler SomethingChanged; >> >> and later in the code fire this event in this way... >> >> if(SomethingChanged != null) >> { >> SomethingChanged("Nothing important"); >> } >> >> and the subscription of this event of other objects can be easy as >> >> eventGeneratorObject.SomethingChanged += new >> SomethingChangedHandler(aFunctionto_takecareof_it); >> >> and even the handlig of the event is aesy... >> >> void aFunctionto_takecareof_it(string msg) >> { >> >> } >> >> >> ....now the question is.. how can i do the same using Python? Every help >> is >> appreciated >> >> >> >> >> >> Regards, >> Gianmaria >> >> -- >> http://mail.python.org/mailman/listinfo/python-list >> Txs so much. Gianmaria From http Fri Jul 27 14:51:31 2007 From: http (Paul Rubin) Date: 27 Jul 2007 11:51:31 -0700 Subject: zip() function troubles References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> <1185560330.252916.307390@j4g2000prf.googlegroups.com> Message-ID: <7x4pjp3cjw.fsf@ruckus.brouhaha.com> Raymond Hettinger writes: > > What was really surprising is that it works with no issues up > > until 1 million items, but for say 10 million it pretty much goes > > nuts. Does anyone know why? > > There's nothing in izip() that holds memory, tracks indices, or ... The issue was with zip, not izip. It was caused by gc running too often. From sjmachin at lexicon.net Mon Jul 30 20:26:00 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 30 Jul 2007 17:26:00 -0700 Subject: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why? In-Reply-To: <1185838264.101543.246150@g12g2000prg.googlegroups.com> References: <1185791793.141118.44080@x35g2000prf.googlegroups.com> <5h5ufoF3hmufcU4@mid.uni-berlin.de> <1185814119.604341.204100@z28g2000prd.googlegroups.com> <1185838264.101543.246150@g12g2000prg.googlegroups.com> Message-ID: <1185841560.223868.285110@z24g2000prh.googlegroups.com> On Jul 31, 9:31 am, Zentrader wrote: > > from decimal import Decimal > > > In [21]: a = Decimal() > > > In [22]: class Decimal(object): > > ....: pass > > ....: > > > In [23]: b = Decimal() > > > In [24]: a - b > > Perhaps I don't understand what you are doing here, but on line 22 you > overload Decimal. In the utter absence of any clues from the OP, Marc was demonstrating one possible way that the puzzling [Can't subtract one Decimal instance from another???] error message could have been caused. From kimiraikkonen85 at gmail.com Sun Jul 1 15:35:38 2007 From: kimiraikkonen85 at gmail.com (kimiraikkonen) Date: Sun, 01 Jul 2007 12:35:38 -0700 Subject: The best platform and editor for Python In-Reply-To: References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> Message-ID: <1183318538.941276.309560@o61g2000hsh.googlegroups.com> On Jul 1, 10:30 pm, "S?nmez Kartal" wrote: > Hello, > > Emacs is the best for anything for me. Some people prefers Eclipse > with PyDev extension. > > Build some real world applications with Python. Pick what do you need > from SourceForge or similar one then write it. If it is something you > need then you probably will make it more special then you found and > this will take you to the more coding and more... > > By the way, thanks for winning Magny Cours grand prix Kimi... :-P > > On 7/1/07, kimiraikkonen wrote: > > > > > Hi, > > For experienced with Pyhton users, which developing software and > > enviroment would you suggest for Pyhton programming? Compiler+Editor > > +Debugger. > > > Also what are your suggestions for beginners of Pyhton programming? > > > Thank you. > > > -- > >http://mail.python.org/mailman/listinfo/python-list- Hide quoted text - > > - Show quoted text - Thank you for the suggestions. Tesekkurler Say n Kartal :-) From abhins4 at gmail.com Thu Jul 5 12:29:36 2007 From: abhins4 at gmail.com (Abhishek Jain) Date: Thu, 5 Jul 2007 21:59:36 +0530 Subject: list.append not working? In-Reply-To: <1183651138.209079.37620@q75g2000hsh.googlegroups.com> References: <1183651138.209079.37620@q75g2000hsh.googlegroups.com> Message-ID: with every iteration your previous values are overwritten ('md' is a dictionary) so thats why your are observing this ouput.. check if the following patch solves your problem for entity in temp: md['module']= entity.addr.get('module') md['id']=entity.addr.get('id') md['type']=entity.addr.get('type') #print md mbusentities.append(md) md = {} #print mbusentities Regards Abhi On 7/5/07, Hardy wrote: > > I experience a problem with append(). This is a part of my code: > > for entity in temp: > md['module']= entity.addr.get('module') > md['id']=entity.addr.get('id') > md['type']=entity.addr.get('type') > #print md > mbusentities.append(md) > #print mbusentities > > I want something like: [{'module': 'home', 'id': 123, 'type': 'core'}, > {'module': 'work', 'id': 456, 'type': 'core'}] > md is always correct, BUT:mbusentities is wrong. Length of > mbusentities is same of temp, so it appended everything. BUT: > mbusentities only shows the values of the last append: [{'module': > 'work', 'id': 456, 'type': 'core'}, {'module': 'work', 'id': 456, > 'type': 'core'}] > > What's wrong? > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Thu Jul 19 02:28:11 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 19 Jul 2007 08:28:11 +0200 Subject: Real-time Update References: <1184747090.102324.265230@i13g2000prf.googlegroups.com> Message-ID: <000201c7c9e2$3236ea00$03000080@hendrik> "ReTrY" wrote: > I'm writing a program with Tkinter GUI, When the program is running it > need to be updated every five seconds (data comes from internet). How > should I do that ? How to make a function in main loop ? Short answer: use the after method to set up a periodic scan of a queue. In another thread, look for the new stuff, and put it on the queue when found. there is a recipe for this sort of thing, but I keep losing links. - Hendrik From python at jayloden.com Fri Jul 13 18:38:31 2007 From: python at jayloden.com (Jay Loden) Date: Fri, 13 Jul 2007 18:38:31 -0400 Subject: Right tool and method to strip off html files (python, sed, awk?) In-Reply-To: <1184353058.660535.140110@m3g2000hsh.googlegroups.com> References: <1184353058.660535.140110@m3g2000hsh.googlegroups.com> Message-ID: <4697FEE7.3090303@jayloden.com> sebzzz at gmail.com wrote: > I thought about doing that with python (for which I'm in process of > learning), but maybe an other tool (like sed?) would be better suited > for this job. Generally speaking, in my experience, the best tool for the job is the one you know how to use ;) There are of course places where certain tools are very well suited - e.g. Perl when it comes to regular expressions and text processing. BUT, the time it will take you to learn Perl would be better spent getting the work done in Python or sed/awk etc. Similarly, maintaining a script in a language you don't know well will introduce headaches later. In short, you're almost always best off using the tool you are most comfortable with. > I kind of know generally what I need to do: That's usually a good start ;) > 1- Find all html files in the folders (sub-folders ...) > 2- Do some file I/O and feed Sed or Python or what else with the file. > 3- Apply recursively some regular expression on the file to do the > things a want. (delete when it encounters certain tags, certain > attributes) > 4- Write the changed file, and go through all the files like that. This is one valid approach. There are a lot of things that you can do to help define your problem better though. For instance: * Are the files matching a predefined template of some kind? Can you use this to help define some of your processing rules? * Do you know what kind of regular expressions you are going to need? For that matter, are you even comfortable using regular expressions? From the sound of your post, you may not have experience with them so that's going to be a hurdle to overcome when it coms to using them * Regular expressions are one approach to the problem. However, they may not be the most maintainable or practical, depending on the actual requirements. An HTML or XML processing module might be a better option, particularly if the HTML Tidied pages are valid XHTML. * Define your program requirements in smaller more specific terms, e.g. "need to remove all of the following tags: ,
    " or "need to clean orphaned/invalid tags" - this will help you define the actual problem statement better and makes it easier to see what the best solution is. Are you just looking to strip all the HTML from some files? Perhaps lynx/links with the --dump option is all you need, as opposed to a full HTML parsing script. > But I don't know how to do it for real, the syntax and everything. I > also want to pick-up the tool that's the easiest for this job. I heard > about BeautifulSoup and lxml for Python, but I don't know if those > modules would help. See above about defining the problem statement. If you get it pinned down to a finite set of requirements, you can take those smaller problems and determine if, for example, lxml is the right tool for the job. If you come back to the Python mailing list with a smaller problem, e.g. "how can I remove all
    tags from HTML pages", you're much more likely to get a quick, practical, and useful answer to your question(s). > Now, I know I'm not a the best place to ask if python is the right > choice (anyways even my little finger tells me it is), but if I can do > the same thing more simply with another tool it would be good to know. If all you've got is a hammer, everything looks like a nail ;) - it's important to not be so dogmatic about one programming language or tool of any kind that you can't see when there's a much more efficient solution available. However, should you end up determining that what is needed is a good all-purpose scripting/programming language, I'm sure you'll find Python plenty capable and this list quite helpful in conquering any problems along the way. > An other argument for the other tools is that I know how to use the > find unix program to find the files and feed them to grep or sed, but > I still don't know what's the syntax with python (fetch files, change > them than write them) and I don't know if I should read the files and > treat them as a whole or just line by line. Of course I could mix > commands with some python, find command to my program's standard > input, and my command's standard output to the original file. But I do > I control STDIN and STDOUT with python? Either approach is perfectly valid should you end up using Python; you can either feed a list of filenames to Python on the command line, write a recursive directory reading function that will get the filenames, or control STDOUT/STDIN. Again see my first point about defining a problem statement, and then you can Google for example code to help you. The Python Cookbook is often enormously helpful as well, since you can find sample code for manipulating STDIN/STDOUT, reading a directory recursively, and handling command line arguments. But, it's important to know which one you want before you can search for it... > Sorry if that's a lot of questions in one, and I will probably get a > lot of RTFM (which I'm doing btw), but I feel I little lost in all > that right now. Reading the manual is excellent and important, but it won't always help you with feeling overwhelmed. The best thing to do is break a big problem into little problems and work on those so they don't seem so insurmountable. (You may be detecting a pattern to the advice I'm giving by now). HTH, -Jay From gagsl-py2 at yahoo.com.ar Wed Jul 25 02:14:38 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 25 Jul 2007 03:14:38 -0300 Subject: idiom for RE matching References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> <1185157313.356112.159020@z24g2000prh.googlegroups.com> <2f6dnUlUxd2_7TjbnZ2dnUVZ_qy3nZ2d@comcast.com> Message-ID: En Wed, 25 Jul 2007 00:02:51 -0300, Gordon Airporte escribi?: > Gabriel Genellina wrote: > >> As is often the case, a regular expression is NOT the right tool to use >> in this case. > > Very interesting, thank you. I think 'pattern matching' and I > automatically think 'regular expressions'. Once again this famous quote is true: -- Gabriel Genellina From steve at holdenweb.com Wed Jul 11 21:50:16 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 11 Jul 2007 21:50:16 -0400 Subject: asyncore and OOB data In-Reply-To: References: <1184172867.420979.215300@q75g2000hsh.googlegroups.com> Message-ID: Douglas Wells wrote: > In article <1184172867.420979.215300 at q75g2000hsh.googlegroups.com>, > billiejoex writes: >> In an asyncore based FTP server I wrote I should be able to receive >> OOB data from clients. >> A client sending such kind of data should act like this: >> >>>>> import socket >>>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) >>>>> s.connect(('127.0.0.1', 21)) >>>>> s.sendall('hello there\r\n', socket.MSG_OOB) >> According to asyncore documentation I should handle this kind of event >> in "handle_expt" method of dispatcher class, that should be called >> when OOB is received by the underlying socket. I've tried to override >> handle_expt method in such way: >> >> def handle_expt(self): >> print "OOB data arrived" >> data = self.socket.recv(1024, socket.MSG_OOB) >> print data >> >> ...but, even if it is called, "data" contains only a "\n" character >> instead of the entire string ("hello there\r\n"). >> Why does this happen? Should I have to use a different approach? > > You should use a different approach, but first you need to read > the relevant documentation. > > I've never used asyncore, but when I look at the documentation, > the only reference that I find to OOB says: > "Called when there is out of band (OOB) data for a socket > connection. This will almost never happen, as OOB is > tenuously supported and rarely used." > That should be fair warning. > > Second, when I look at the FTP specification, I don't find the > concept of OOB anywhere. So, it's not clear what OOB data would > mean in terms of the defined FTP commands in any case. > > Third, the TCP protocol, which you have selected via the SOCK_STREAM > option doesn't support OOB at all, so there's no way that you can > even send OOB data in the manner that you are expecting. > Wrong. The URGENT pointer indicates that the data begins with out-of-band data. You are correct, however, in stating that the FTP protocol doesn't support or implement out-of-band data transmissions. > Let's switch to the positive, however. What TCP does have is the > concept of "urgent" data. Urgent data is data that the sender > believes is so important that the receiver should discard intermediate > data, if necessary, in order to process the urgent data -- but the > urgent data is sent *in-band*. > No, technically the urgent data is out-of-band, isn't it? There is no requirement to ditch the other data in the packet, so urgent data can be interspersed without loss of regular in-band data if required. > In the case of FTP, the concept of urgent data is used to allow > the user side to interrupt the data transfer, which it does by > sending an ABOR command. The underlying problem is that the server > might be blocked on a receive on the data connection and not > listening for commands on the control connection. So the user > side is required to perform some "special action" that includes > sending urgent data, which the server can then process specially. > This problem arises primarily in systems without either threading > or asynchronous I/O APIs. Your use of asyncore should alleviate > this problem. > The data and control connections are typically dealt with in most implementations by separate processes, so an ABOR command can be sent without having to wait even if the data connection is blocked. Of course if a specific implementation uses a single-threaded single process to drive both the data and control connections then all bets are off. > The thing that may be confusing you is that for whatever reason > the designers of the Berkeley socket API (which is what you are > using when running under POSIX/Linux/MS Windows), chose to use the > OOB flags (e.g., MSG_OOB) to indicate the *transmission* of OOB > data -- but it's not really OOB data. In fact, when I attempt to > receive using the MSG_OOB flag using the OS interfaces on my system, > I get back an error (EINVAL - Invalid argument). I would expect > that asyncore would report this error somehow or other. > You can, of course, expect what you like, but experience is the best guide to what will actually happen. > In summary, you almost certainly can't use the concept of a separate > OOB channel to transfer data in an FTP environment. If you really, > really need something like this, you will need to extend the FTP > protocol for your special purposes. > I'd certainly concur with that: anything that's processing FTP streams will almost certainly barf when urgent data arrives, since this is outside the scope of the FTP protocol specification. 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 Tue Jul 10 23:52:40 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 11 Jul 2007 05:52:40 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7x7ip87spx.fsf@ruckus.brouhaha.com> References: <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <468c0827$0$22906$426a74cc@news.free.fr> <7x3b03lusa.fsf@ruckus.brouhaha.com> <468c18fc$0$26377$426a74cc@news.free.fr> <7xabu7e9ku.fsf@ruckus.brouhaha.com> <46925cdf$0$27972$426a34cc@news.free.fr> <7x7ip87spx.fsf@ruckus.brouhaha.com> Message-ID: <4693e34f$0$11786$426a74cc@news.free.fr> Paul Rubin a ?crit : > Bruno Desthuilliers writes: > >>>If the assertion is wrong, the compiler signals an error. In >>>that sense it's like a unit test; it makes sure the function does what >>>the user expects. >> >>It still boils down to the same problem : possibly valid types are >>rejected based on a declaration. > > > I'm not sure what you mean. If the programmer intended for the > function to compute an integer, then it's invalid for the function to > return (say) a string, whether there is a static typecheck or not. I was mostly thinking of inputs, but it's the same thing for outputs - in most cases the concrete "type" (=> class) of the object returned by a function is no more significant than the concrete type(s) of it's input(s). What is important is that these objects supports the (implicit) protocols expected by either the function itself (for inputs) or the caller (for output(s)). And FWIW, in Python, it's not unusual for a function or method to be able to return objects of any type - cf the dict.get(key, default=None) method. (snip) >>>However, that may be a self-fulfilling prophecy since maybe I'm >>>cultivating a coding style that doesn't use the dynamism, >> >>Perhaps is this coding style not making the best use of Python's >>features ? To me, it sounds like doing procedural programming in OCaml - >>it's of course possible, but probably not the best way to use the language. > > This is in principle possible, though I feel like I'm coding more > effectively since gravitating to this style. > Anton van Straaten (a > dynamic typing proponent) wrote of static checks > (http://lambda-the-ultimate.org/node/2216#comment-31954): > > In most cases, the correctness proof itself is not the most important > advantage of static checking of a program. Rather, it's the type > discipline that must be followed in order to achieve that correctness > proof. The final proof is like the certificate you get when you > graduate from college: it's not that important by itself, but to have > obtained it you must have done a lot of work, at least some of which > is important and necessary. You can do the work without getting the > certificate, but many people don't, and in the programming case they > may pay a price for that in terms of programs with poor type > discipline, which can have consequences for reasoning and the > "ilities". > > I coded a fair amount of Lisp before starting with Python though, so > even before, I tended to code Python in a Lisp-like style, ignoring > Python's more dynamic features such as metaclasses. While my knowledge of Lisp is somewhat limited - I played with Common Lisp and Scheme (and Emacs Lisp) but never seriously used any Lisp dialect - it also had some influence on my coding style. But Python's support for "hi-level" programming - including the restricted support for functional approach - mostly comes from it's object model, and I prefer to take advantage of this object model instead of trying to write Lisp (or Haskell or whatever other FPL) in Python. A good example could be partial application - which in Python is better implemented as a class than using closures. > I'd also compare the situation with Forth, where functions can consume > and insert arbitrary numbers of values to the stack, but programmers > in practice maintain careful stack discipline (making sure to pop and > push a constant number of values, and documenting the meaning of each > one) in order to avoid going crazy. Just because the language offers > you rope, doesn't mean you can't decline to hang yourself with it. Indeed. But this doesn't mean you should not use the rope at all - specially when it happens to be the RightThing(tm) to do. Compare an old framework like Zope 2.x, and new ones (internally) making heavy use of metaclasses, descriptors etc, and you may find out that these features not only greatly help wrt/ both robustness (less boilerplate) and readability (less boilerplate), but also tend to encourage a more declarative style (. > Finally, this article about "gradual typing" (you can write your code > dynamically and then later add static annotations resulting in type > safety) might be of interest: I have too few problems with type errors to feel a need for more "type safety" than what Python actually provides, and I don't see the point of adding arbitrary restrictions. What's appropriate for language X is not necessarily appropriate for language Y, and I know where to find smart statically typed languages if and when I do need them. From see_website at mindprod.com.invalid Sun Jul 1 11:54:14 2007 From: see_website at mindprod.com.invalid (Roedy Green) Date: Sun, 01 Jul 2007 15:54:14 GMT Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> Message-ID: On 25 Jun 2007 18:46:25 -0700, Paul Rubin wrote, quoted or indirectly quoted someone who said : >TAI really does seem like the most absolute--if you are a user in >orbit or on Mars, then UTC timestamps will seem pretty meaningless and >artificial. According to Einstein all time is local time, so perhaps our wish for a clean UT is a pipedream. To add to the confusion you have GPS, Loran and Julian day also used as scientific times. -- Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com From dstromberg at datallegro.com Wed Jul 11 22:31:41 2007 From: dstromberg at datallegro.com (Dan Stromberg - Datallegro) Date: Thu, 12 Jul 2007 02:31:41 GMT Subject: Screen Scraping Question References: <1184157921.488811.295570@n60g2000hse.googlegroups.com> Message-ID: On Wed, 11 Jul 2007 12:45:21 +0000, jeffbg123 wrote: > Hey, > > I am trying to make a bot for a flash game using python. However I am > having some trouble with a screen scraping strategy. Is there an > accepted way to compare a full screenshot with the image that I want > to locate? It is a math based game, so I just have to check what > number, 1-9, appears in the center of the flash game. Is there an > easier method to do this? > > Thanks > > -Jeff That sounds like an OCR problem, unless the numbers are so consistently rendered that you can just store copies of all 9 (I'd pick a non-lossy format) and compare. From aahz at pythoncraft.com Thu Jul 19 13:42:54 2007 From: aahz at pythoncraft.com (Aahz) Date: 19 Jul 2007 10:42:54 -0700 Subject: class C: vs class C(object): References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> Message-ID: In article , Steven D'Aprano wrote: > >It isn't wrong to use the old style, but it is deprecated, [...] Really? Can you point to some official documentation for this? AFAIK, new-style classes still have not been integrated into the standard documentation. Maybe I missed something, though. Note very carefully that "going away eventually" is *not* the same as deprecation. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I support the RKAB From bj_666 at gmx.net Tue Jul 17 13:44:15 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 17 Jul 2007 17:44:15 GMT Subject: merge two ranges References: <1184693381.008061.116840@m37g2000prh.googlegroups.com> Message-ID: <5g4dffF3dv5s2U3@mid.uni-berlin.de> On Tue, 17 Jul 2007 17:29:41 +0000, anoweb wrote: > I have two ranges of numbers and I need to determine if they overlap > or adjacent and if so return a new range containing the values. The > values are low and high for each pair, such that the first value of > the tuple is always less than or equal to the second value in the > tuple. > > for example: > a = (0, 5) > b = (5, 10) > > print getAdjacent(a, b) # output: (0, 10) > print getAdjacent(b, a) # output: (0, 10) > print getOverlap(a, b) # output: None > print getOverlap(b, a) # output: None > > a = (0, 7) > b = (3, 10) > print getAdjacent(a, b) # output: None > print getAdjacent(b, a) # output: None > print getOverlap(a, b) # output: (0, 10) > print getOverlap(b, a) # output: (0, 10) > > a = (0, 90) > b = (5, 10) > print getAdjacent(a, b) # output: None > print getAdjacent(b, a) # output: None > print getOverlap(a, b) # output: (0, 90) > print getOverlap(b, a) # output: (0, 90) > > a = (0, 5) > b = (12, 20) > print getAdjacent(a, b) # output: None > print getAdjacent(b, a) # output: None > print getOverlap(a, b) # output:None > print getOverlap(b, a) # output: None > > any easy way of doing this? Yes. That's quite an easy homework you really should do yourself. ;-) Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Thu Jul 12 02:00:59 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 12 Jul 2007 06:00:59 GMT Subject: storing pickles in sql data base References: <592087469.jZQWuvoN0q@teancum> Message-ID: <5flucrF3cnokrU1@mid.uni-berlin.de> On Wed, 11 Jul 2007 17:14:43 -0500, Chris Mellon wrote: > [pickle] > > Protocol 0 (the default) is a text protocol, it's safe to store in a > text field or write to a text file. It's not really a text protocol it's more a binary protocol that uses just the ASCII range of byte values. You have to write and read the "text" files in binary mode or they break if taken across platform boundaries because of the different line endings in Linux and Windows for instance. Ciao, Marc 'BlackJack' Rintsch From Afro.Systems at gmail.com Thu Jul 12 20:46:32 2007 From: Afro.Systems at gmail.com (Tzury) Date: Fri, 13 Jul 2007 00:46:32 -0000 Subject: MaildirMessage Message-ID: <1184287592.509355.310110@g4g2000hsf.googlegroups.com> I am getting the following error when trying to iterate in a message in a Maildir directory. please help. >>> from mailbox import Maildir, MaildirMessage >>> mbox = Maildir('path/to/mailbox', create = False, factory = MaildirMessage) >>> for msg in mbox: ... for m in msg: ... print m ... Traceback (most recent call last): File "", line 2, in File "email/message.py", line 286, in __getitem__ File "email/message.py", line 352, in get AttributeError: 'int' object has no attribute 'lower' >>> From daniel at zelisko.net Mon Jul 2 02:23:11 2007 From: daniel at zelisko.net (Drex) Date: Sun, 01 Jul 2007 23:23:11 -0700 Subject: how to send files via bluetooth with python to a mobile In-Reply-To: <5eqg94F39cdomU1@mid.uni-berlin.de> References: <1183294323.556314.293860@m36g2000hse.googlegroups.com> <1183305873.736724.116680@c77g2000hse.googlegroups.com> <1183306850.712226.313800@m36g2000hse.googlegroups.com> <1183310919.771396.268760@q69g2000hsb.googlegroups.com> <5eq94iF3a5b8bU1@mid.uni-berlin.de> <46880a0b$0$37195$4fafbaef@reader3.news.tin.it> <5eqg94F39cdomU1@mid.uni-berlin.de> Message-ID: <1183357391.239520.220490@q69g2000hsb.googlegroups.com> Hello, > > seams thatpythonbindings are already there? > >http://dev.zuckschwerdt.org/openobex/wiki/ObexFtpExampleClientPython > > Cool, didn't find that. thanks, this looks to be what I was looking for! regards dz From kyosohma at gmail.com Mon Jul 30 11:29:12 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 30 Jul 2007 15:29:12 -0000 Subject: Events: The Python Way In-Reply-To: References: Message-ID: <1185809352.787658.299190@x35g2000prf.googlegroups.com> On Jul 29, 3:14 pm, "Gianmaria" wrote: > "David Wilson" ha scritto nel messaggionews:mailman.1295.1185665717.22759.python-list at python.org... > > > > > Hi there, > > > Python has no built-in way of doing this. You may consider writing > > your own class if you like this pattern (I personally do): > > > class Event(object): > > def __init__(self): > > self.subscribers = set() > > > def __iadd__(self, subscriber): > > self.subscribers.add(subscriber) > > return self > > > def __isub__(self, subscriber): > > self.subscribers.pop(subscriber) > > return self > > > def __call__(self, *args, **kwargs): > > for subscriber in self.subscribers: > > subscriber(*args, **kwargs) > > > def HandleFoo(strng): > > print "HandleFoo:", strng > > > OnFoo = Event() > > OnFoo += HandleFoo > > > OnFoo("Test.") > > > On 29/07/07, Gianmaria wrote: > >> Hi, > >> i'm a .net programmer and i'm learnig python, so this question can be > >> very > >> stupid or easy for python programmers. I've a doubt about events.... here > >> is > >> what: > > >> in c# for example i can write a delegate and an event in this way... > > >> public delegate SomethingChangedHandler(string message); > >> public event SomethingChangedHandler SomethingChanged; > > >> and later in the code fire this event in this way... > > >> if(SomethingChanged != null) > >> { > >> SomethingChanged("Nothing important"); > >> } > > >> and the subscription of this event of other objects can be easy as > > >> eventGeneratorObject.SomethingChanged += new > >> SomethingChangedHandler(aFunctionto_takecareof_it); > > >> and even the handlig of the event is aesy... > > >> void aFunctionto_takecareof_it(string msg) > >> { > > >> } > > >> ....now the question is.. how can i do the same using Python? Every help > >> is > >> appreciated > > >> Regards, > >> Gianmaria > > >> -- > >>http://mail.python.org/mailman/listinfo/python-list > > Txs so much. > Gianmaria I think the pubsub module in wxPython does what you are referring to. Of course, usually you would need to be writing a GUI if you used it. Here's some links on it: http://www.wxpython.org/docs/api/wx.lib.pubsub-module.html http://www.wxpython.org/docs/api/wx.lib.pubsub.PublisherClass-class.html They also mention it in their wiki / cookbook. Unfortunately, the wxPython website seems screwed up today. I've never seen it behave like this. But when it's back up, I'd highly recommend checking it out. Or just browse Google's cached copies... Mike From Dave.Baum at motorola.com Fri Jul 13 17:59:02 2007 From: Dave.Baum at motorola.com (Dave Baum) Date: Fri, 13 Jul 2007 16:59:02 -0500 Subject: Can a low-level programmer learn OOP? References: Message-ID: In article , Chris Carlen wrote: > Why would OOP be better? Different is not better. Popular is not > better. What the academics say is not better. Less lines of code might > be better, if the priority is ease of programming. Or, less machine > execution time or memory usage might be better, if that is the priority. Short answer: Increasing programmer productivity is better, and OO frequently accomplishes this. Longer answer: Consider OOP as one tool in the toolbox. It isn't "best" for every conceivable problem, but neither is procedural programming, functional programming, table driven state machines, or any other style of design and/or programming. Each works well in some situations and poorly in others. Having a large number of tools at your disposal, and knowing which ones to use, is a big plus. Let's talk about design versus implementation for a moment, since OO really applies to both, but in different ways. You mentioned state machines, and that is a good example of a design technique. You can look at a problem and convert it to a state machine (design), then implement the state machine in whatever language your computer understands. Over the years, finite state machines have proven to be very effective models because: 1) there are plenty of real world problems that map cleanly to a state machine 2) state machines are easy to implement reliably in most computer languages 3) if you have already implemented a state machine for problem A, then implementing it for problem B is pretty easy - the real work is translating problem B into a state machine OOD is similar. There are a large number of problems for which an object oriented design is a good fit. Once you have an OO design, you then need to implement it, and languages with good OO support make this a lot easier. >From what I have seen, the advantages of OO tend to increase with the size of the project. For example, polymorphism generally lets M clients work with N different kinds of objects by writing M+N chunks of code rather than M*N. When M or N is small, this difference in minor, but as M and N increase, it becomes significant. By combining state and function, objects provide a good means of encapsulating operations and keeping client code independent of lower level code. This is a very big win since it allows for the evolution of the lower level code without breaking all of the client code. As with polymorphism, the benefits of encapsulation tend to increase with the size of the project. Even before OO languages were popular, it was quite common to use some basic OO design in order to increase encapsulation. If you look at almost any GUI framework from the 80's or early 90's you'll find lots of C code with structs that the user is not supposed to mess with, and then functions that take pointers/handles/indexes to those "magic" structs as the first argument. This is really OO design implemented in a procedural language. In fact, GUI frameworks are an excellent example of a domain for which OO has established itself a very good way to model the problem. I could probably spend a lot more time on the merits of OO, but I think if you really want to understand its benefits you need to work with it in a domain for which OO is useful. It is possible that the specific projects you work on really wouldn't benefit much from OO, and that is why you haven't had the "a-ha!" moment. Forcing an OO model onto a problem just for the sake of OO will only result in frustration. Dave From a-alpha at otenet.gr Fri Jul 6 21:23:09 2007 From: a-alpha at otenet.gr (A KOURNIKOVA) Date: Sat, 7 Jul 2007 04:23:09 +0300 Subject: Maria Sharapova Angelina joli Message-ID: Maria Sharapova Angelina joli search engines , cams , adult , photogallery , dating , travel , autos, cars , real estate , ads , spor , shopping , domain names ------------------------ www.alphasearch.gr -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Sun Jul 22 19:03:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 22 Jul 2007 19:03:39 -0400 Subject: Lazy "for line in f" ? In-Reply-To: <1185143634.778056.227720@g4g2000hsf.googlegroups.com> References: <1185120650.412694.314280@o61g2000hsh.googlegroups.com> <1185143634.778056.227720@g4g2000hsf.googlegroups.com> Message-ID: Alexandre Ferrieux wrote: > On Jul 22, 7:21 pm, Miles wrote: >> On 7/22/07, Alexandre Ferrieux wrote: >> >>> The Tutorial says about the "for line in f" idiom that it is "space- >>> efficient". >>> Short of further explanation, I interpret this as "doesn't read the >>> whole file before spitting out lines". >>> In other words, I would say "lazy". Which would be a Good Thing, a >>> much nicer idiom than the usual while loop calling readline()... >>> But when I use it on the standard input, be it the tty or a pipe, it >>> seems to wait for EOF before yielding the first line. >> It doesn't read the entire file, but it does use internal buffering >> for performance. On my system, it waits until it gets about 8K of >> input before it yields anything. If you need each line as it's >> entered at a terminal, you're back to the while/readline (or >> raw_input) loop. > > How frustrating ! Such a nice syntax for such a crippled semantics... > > Of course, I guess it is trivial to write another iterator doing > exactly what I want. > But nonetheless, it is disappointing not to have it with the standard > file handles. > And speaking about optimization, I doubt blocking on a full buffer > gains much. > For decades, libc's fgets() has been doing it properly (block- > buffering when data come swiftly, but yielding lines as soon as they > are complete)... Why is the Python library doing this ? > What makes you think Python doesn't use the platform fgets()? As a matter of policy the Python library offers as thin as possbile a shim over the C standard library when this is practical - as it is with "for line in f:". But in the case of file.next() (the file method called to iterate over the contents) it will actually use getc_unlocked() on platforms that offer it, though you can override that configuration feature by setting USE_FGETS_IN_GETLINE, It's probably more to do with the buffering. If whatever is driving the file is using buffering itself, then it really doesn't matter what the Python library does, it will still have to wait until the sending buffer fills before it can get any data at all. Try running stdin unbuffered (use python -u) and see if that makes any difference. It should, in the shell-driven case, 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 sturlamolden at yahoo.no Fri Jul 13 17:37:32 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 13 Jul 2007 14:37:32 -0700 Subject: Numpy array index handling In-Reply-To: <1184359937.326180.107370@g4g2000hsf.googlegroups.com> References: <1184352981.493615.18040@k79g2000hse.googlegroups.com> <1184359937.326180.107370@g4g2000hsf.googlegroups.com> Message-ID: <1184362652.982580.113910@m3g2000hsh.googlegroups.com> On 13 Jul, 22:52, phish... at gmail.com wrote: > It seems a bit risky to use 'from scipy import *'. Maybe it's better > to use 'import scipy' and then scipy.arange, to be sure what is > actually being used? Would there be any disadvanages with that > approach, other than more use of the keyboard? Generally the idiom from something import * is discouraged as it clutters the namespace (it can e.g. shadow globals). I prefer something like: import numpy as np Also I suggest you don't use SciPy and Matplotlib (pylab) unless you mean it. Import from numpy instead. Import pylab if you need graphs and scipy if you need something special that is not in numpy. Get the latest installer (or sources) from: Python 2.5.1: www.python.org NumPy 1.0.3: www.scipy.org SciPy 0.5.2: www.scipy.org Matplotlib 0.90.1: matplotlib.sourceforge.net PIL 1.1.6: www.pythonware.com/products/pil/ wxPython 2.8.4.0: www.wxpython.org gcc and gfortran (for scipy.wave): http://gcc.gnu.org/wiki/GFortranBinaries At least that is what makes me as a scientist happy with Python :) Enthought and similar distros are in my experience "unclean". They don't always work and they are difficult to update. I rather download the binary installers (for Windows) and install the packages I need. I also suggest you buy a copy of "Guide to NumPy" by Travis Oliphant. http://www.tramy.us/guidetoscipy.html S.M. From wesbrooks at gmail.com Mon Jul 9 05:12:14 2007 From: wesbrooks at gmail.com (Wesley Brooks) Date: Mon, 9 Jul 2007 10:12:14 +0100 Subject: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc) In-Reply-To: References: <1183939608.088756.178320@m37g2000prh.googlegroups.com> Message-ID: For a robotics project I would highly recommend the use of Phidgets, they can supply sensors and interface kits with APIs. Not sure if Python is fully supported yet but there certinally seems to be a considerable effort ongoing creating an API for python. I've only used them to date for servo control and accelorometer sencor data collection through c++ / wxWidgets. http://www.phidgets.com/ They offer direct motor controllers but I'll be looking to control a 7.2V motor with a 100A draw, so I'll be using the servo controller to drive a standard Radio Control Car motor controller. Cheers, Wes. On 09/07/07, Gabriel Genellina wrote: > En Sun, 08 Jul 2007 21:06:48 -0300, escribi?: > > > in this project, we need something that would basically function as a > > blender. we know we'll need to buy a motor that spins, but what we're > > having trouble with is figuring out how to program it. we want to be > > able to control the speed of the motor. how would we accomplish this? > > This is mostly an electronics question. How much power? For small power > and fine control I'd look for "stepwise motor" on any robotics book; for a > high power "blender" I think you don't care so much about fine control. In > any case, it's the available motor which dictates how you can control it. > > > i'm new to all of this, so i'm having a hard time wrapping my mind > > around how it'd be possible to program one of those things :\ > > > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then > > turn the other direction. > > You may write the GUI using python, and the high level controlling API > too. But you may need to use a PIC or some kind of controller, listening > for commands from the PC and acting over the motor accordingly. > > Picasso: a Python-controlled robot for doing paintings > http://youtube.com/watch?v=PsbKq5Kysj0 > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > From jimxu at google.com Tue Jul 3 12:35:15 2007 From: jimxu at google.com (Yongjian Xu) Date: Tue, 3 Jul 2007 09:35:15 -0700 Subject: POpen - Wait For Process To Complete In-Reply-To: <4330026442954609509@unknownmsgid> References: <4330026442954609509@unknownmsgid> Message-ID: <9c09a1210707030935p7fa505e9pe8e92cc98186ce6@mail.gmail.com> That's by using the P3/P4 classes not the function. the function does not provide wait() call, it simply does it for you by default. Jim On 7/3/07, Robert Rawlins - Think Blue wrote: > > Hello guys, > > > > Quite a simple one I'm hoping. I've got a process that I run using popen > which writes to a file, I'm then going to read the file and parse its > contents. However, getting the application to wait until the process is > complete and finished writing before it reads and parses the file is > becoming complicated. > > > > Popen is meant to have a wait() function along with a poll() function > (according to the docs), both of which can be used to make the app wait for > the process to finished, but for some reason I can't get them working, when > I try this: > > > > Import popen2 > > > > Process = popen2.popen4('This is my command to run from > cmd') > > > > Process.wait() > > > > f = open('path/to/output/file.txt') > > new = f.read() > > f.close() > > > > It throws back the following error to me: > > > > push.wait() > > AttributeError: 'tuple' object has no attribute 'wait' > > > > Which is fair enough as popen4 returns a tuple containing the output > streams from the cmd command, but how the hell can I have it wait so I can > read the physical files? > > > > I'll be interested to hear your thoughts guys, > > > > Rob > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Yongjian (Jim) Xu =========== Sysops -------------- next part -------------- An HTML attachment was scrubbed... URL: From gh at gregor-horvath.com Thu Jul 5 07:23:35 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Thu, 05 Jul 2007 13:23:35 +0200 Subject: The best platform and editor for Python In-Reply-To: <1183630730.251890.238900@m36g2000hse.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> Message-ID: Kay Schluehr schrieb: > That's what I love most about the Python community. Whenever there is > just a non-standard, platform-dependent or crappy implementation of a > feature you get told that you don't need it. When printf was good for > little David print is good enough for me. > That's a property of open source projects. Features nobody really needs are not implemented. Gregor From nospam at williamsdurkin.co.uk Mon Jul 2 00:38:17 2007 From: nospam at williamsdurkin.co.uk (Martin Durkin) Date: 2 Jul 2007 04:38:17 GMT Subject: Reversing a string References: <1182997438.541012.54100@o61g2000hsh.googlegroups.com> <1i0kjpx.wjw44j15np22dN%aleax@mac.com> Message-ID: aleax at mac.com (Alex Martelli) wrote in news:1i0kjpx.wjw44j15np22dN%aleax at mac.com: > Martin Durkin wrote: > ... >> >>>>>> def rev(x): >> >>> mylist = [] >> >>> for char in x: >> >>> mylist.append(char) >> >>> mylist.reverse() >> >>> for letter in mylist: >> >>> print letter >> >>> >> >>> However, compare the incredible difference in clarity and >> >>> elegance between that and: >> >>> >> >>>> >>> print "\n".join("spam"[::-1]) > ... >> >> OK, maybe I'm missing the point here as I'm new to Python. The >> >> first one seems clearer to me. What am I missing? >> >> >> > I think all you are missing is familarity with Python, but I too >> > don't like one-liners simply for their own sake. >> >> I guess that's it. The first one reads more like a textbook example >> which is about where I am at. Is there any speed benefit from the one >> liner? > > The first example reads "excruciatingly low-level" to me: its autor is > thinking in terms of what the machine is doing, mapped into pretty > elementary low-level constructs. > sorry you've lost me there. > > So, something like: > > for c in reversed(x): print c > > is mostly likely how I'd present the solution to the task. This is an interesting point to me. I am just learning Python and I wonder how I would know that a built in function already exists? At what point do I stop searching for a ready made solution to a particular problem and start programming my own function? Is it just a matter of reading *all* the documentation before I start coding? From onceuponapriori at gmail.com Mon Jul 2 16:41:57 2007 From: onceuponapriori at gmail.com (onceuponapriori at gmail.com) Date: Mon, 02 Jul 2007 20:41:57 -0000 Subject: Dynamic Language Ninja (or Pirate) - Telecommuting Allowed Message-ID: <1183408917.921581.311060@g4g2000hsf.googlegroups.com> I searched for old messages containing job posts, and saw no one complaining, so I assume it is ok to post here. Please accept my apologies if it is not. That said, here's our position! Dynamic Language Ninja (or Pirate) Etsy is an online marketplace for buying and selling all things handmade: clothing, music, furniture, software, jewelry, robots. We launched on June 18, 2005, and ever since then have been empowering our users to make a living doing what they love most. We are seeking an experienced dynamic language devotee to join our web development effort. You'll be using python, javascript and other technologies to whip up innovative web applications in many challenging and interesting domains: social and community, ecommerce, search, and even software development. Please take a moment to read through the more detailed requirements listed below to insure that you are the right person for the job. If so, send an email introducing yourself to work at etsy.com, being sure to include your resume and an answer to the programming challenge at the bottom. Required: * 5+ years of web development experience * 3+ years of writing production-level code with a dynamic language (python, ruby, lisp, smalltalk, OO javascript, etc) * Strong OOP skills * Understanding of dynamic language idioms and patterns * Ability and willingness to pick up other languages and technologies Desired: * Ability to write python code idiomatically * Experience with javascript * Experience with the django framework * Experience with java, postgresql and/or php Neat: * Lives in South Bay California, New York City or South Florida * Plays guitar hero Challenge: A valid answer will be either a solution to the problem below, or a link to some code of which you are particularly proud. Problem: In the dynamic language of your choice, write a short program that will: 1. define a list of the following user ids 42346, 77290, 729 (you can hardcode these, but it should still work with more or less ids) 2. retrieve an xml document related to each user at this url "http:// api.etsy.com/feeds/xml_user_details.php?id=" 3. retrieve the data contained in the city element from each xml document 4. keep a running total of how many users are found in each city 5. display the total count of users living in each city You can assume user ids are valid and that the url is available. The output should look something like: Charlotte: 1 New York: 2 From oren.tsur at gmail.com Thu Jul 26 07:24:54 2007 From: oren.tsur at gmail.com (oren.tsur at gmail.com) Date: Thu, 26 Jul 2007 04:24:54 -0700 Subject: Parsing XML with ElementTree (unicode problem?) In-Reply-To: <46A618E9.6010304@web.de> References: <1185200976.082516.105420@57g2000hsv.googlegroups.com> <1185279975.254458.7510@57g2000hsv.googlegroups.com> <1185287404.060182.314750@57g2000hsv.googlegroups.com> <46A618E9.6010304@web.de> Message-ID: <1185449094.998635.67870@w3g2000hsg.googlegroups.com> OK, I solved the problem but I still don't get what went wrong. Solution - use tree builder in order to create the new xml file (previously I was "manually" creating it). I'm still curious so I'm adding a link to a short and very simple script that gets an xml (containing non ascii chars) from the web and saves some of the elements to 2 different local xml files - one is created by XMLWriter and the other is created manually. you could see that parsing of the first local file is OK while parsing of the "manually" created xml file fails. obviously I'm doing something wrong and I'd love to learn what. the toy script: http://staff.science.uva.nl/~otsur/code/xmlConversions.py Thaks for all your help, Oren From tjreedy at udel.edu Wed Jul 11 21:46:41 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Jul 2007 21:46:41 -0400 Subject: bool behavior in Python 3000? References: <5ficp9F3cram2U2@mid.individual.net><469472f4$0$1293$9b622d9e@news.freenet.de> Message-ID: In reply to various current discussants: there was a long discussion here (clp) of similar points of view when bool was introduced. In Guido's opinion (and mine, but his counts 100x), the positive benefits of the current implementation are greater than the net positive benefits of a 'pure' type. See http://www.python.org/dev/peps/pep-0285/ tjr From lucascarvalho at gmail.com Tue Jul 17 15:47:51 2007 From: lucascarvalho at gmail.com (orehon) Date: Tue, 17 Jul 2007 19:47:51 -0000 Subject: PDF2ODT Message-ID: <1184701671.321156.62040@e16g2000pri.googlegroups.com> Hello, I need to convert PDF to ODT or PDF to DOC using python! I was taking a look at http://www.kde-apps.org/content/show.php/show.php?content=18638&vote=bad&tan=6679097&PHPSESSID=a342d14ea5b9afdfe38580e29ff8bdd9 and this project is outdated. So any idea? Thank you! From alextabone at gmail.com Tue Jul 31 10:23:06 2007 From: alextabone at gmail.com (Alchemist) Date: Tue, 31 Jul 2007 07:23:06 -0700 Subject: get directory and file names Message-ID: <1185891786.452267.57120@57g2000hsv.googlegroups.com> I am working with Python 2.5 on Windows XP (SP2). How can I traverse a folder, loop through a list of files and get their file name and extension in an elegant, pythonic way? Thank you. From carsten at uniqsys.com Fri Jul 13 16:42:47 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 13 Jul 2007 16:42:47 -0400 Subject: Pass by reference or by value? In-Reply-To: <1184354563.861992.119070@22g2000hsm.googlegroups.com> References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> <1184354563.861992.119070@22g2000hsm.googlegroups.com> Message-ID: <1184359367.3372.58.camel@dot.uniqsys.com> On Fri, 2007-07-13 at 19:22 +0000, Robert Dailey wrote: > Correction: > > I ran a few more tests and python actually does a pass by value, > meaning that a "copy" is made That is patently incorrect. A function call in Python *never* makes a copy of any of its arguments. > and the external variable that was > passed in remains unchanged. That depends entirely on what kind of object the "variable" is and how you're trying to change the "variable." > I actually want to know how to "pass by > reference", in that any changes made to a parameter inside of a > function also changes the variable passed in. Python is Pass By Reference. Always. Period. The root of your misunderstanding is that you don't understand how the assignment statement works in Python. You come from the world of C where a variable is a predefined memory location and "a=1;" means "Write the value '1' into the memory location that is inhabited by 'a', obliterating any contents that were previously in this memory location." Python doesn't actually have variables. Python has objects and namespaces, and assignment statements work very differently. This has been widely discussed before. For more information, see http://effbot.org/zone/python-objects.htm and the thread "Understanding python functions" that started just yesterday on this very same list. HTH, -- Carsten Haese http://informixdb.sourceforge.net From afriere at yahoo.co.uk Tue Jul 24 22:28:23 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Tue, 24 Jul 2007 19:28:23 -0700 Subject: Base class for file-like objects? (a.k.a "Stream" in Java) In-Reply-To: <1185317490.607920.100200@z24g2000prh.googlegroups.com> References: <1185317490.607920.100200@z24g2000prh.googlegroups.com> Message-ID: <1185330503.115918.41520@z24g2000prh.googlegroups.com> On Jul 25, 8:51 am, Boris Du?ek wrote: > In Python, I found that "file" objects exist. While specifying > argument types in Python is not possible as in Java, it is possible to > check whether an object is an instance of some class and that's what I > need - I need to check if an argument is a "file"-like object, and if > yes, behave accordingly, if not, treat the argument as string with > URL. > > But I am afraid there is no such a base class - I tried the following: > Yup you are right. Look. >>> type(g).mro() [, ] >>> type(f).mro() [, ] "File-like object" refers the the behaviour of the object, not it's inheritance. Python is an equal opportunity employer, we don't ask and object what race it is, we simply ask "can you do the job?" This is known colloquially as "duck-typing." In other words Python has 'polymorphism by interface,' in contradistinction to Java's 'polymorphism by implementation.' Until you understand this you will be trying to write Java in Python, and you will not have much joy. > P.S.: The code should finally look in esence something like this: > > if isinstance(f, file): > pass > elif isinstance(f, string): > f = urllib.urlopen(f) > else: > raise "..." > process_stream(f) Because of duck-typing, you should almost never use the isintance() (or type(), hasattr(), or any others that don't immediately come to mind ...) in actual code. It (usually) breaks Python's polymorphism! If you find these methods popping up in your code it strongly indicates that you should be using a try/except statement, if not a complete change of your code's logic. Search for LBYL (look before you leap) vs EAFP (easier to ask forgiveness than permission) for a full explanation. I'm not sure why you would ever be sending a file object to urlopen (or is the test isinstance(f, file) supposed to test for an already opened url?), but you final code should actually look more like something along these lines: try : f = urlopen(f) except AttributeError : pass This is not as elegant as it could be, as it will pass not only on open files (or urls), but on any type that lacks the .strip method (ie. it doesn't account for your else condition). You'd probably have to catch an exception later when you try to use what should be an open url, or rewrite your code not to get in this position in the first place. But however you refactor your code, it is advisable to concentrate on what an object can do (and catch an exception where it fails to perform), rather on the type of the object. From steve at holdenweb.com Sun Jul 15 09:26:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 15 Jul 2007 09:26:22 -0400 Subject: CSV without first line? In-Reply-To: <9e2f512b0707142030if7cd91ay53f82924e3c686eb@mail.gmail.com> References: <9e2f512b0707142030if7cd91ay53f82924e3c686eb@mail.gmail.com> Message-ID: Sebastian Bassi wrote: > Hi, > > In my CSV file, the first line has the name of the variables. So the > data I want to parse resides from line 2 up to the end. Here is what I > do: > > import csv > lines=csv.reader(open("MYFILE")) > lines.next() #this is just to avoid the first line > for line in lines: > DATA PARSING > > This works fine. But I don't like to do "lines.next()" just to get rid > of the first line. So I wonder if the reader function on the csv > module has something that could let me parse the file from the second > line (w/o doing that lines.next()). > > That's a perfectly legitimate thing to do, so don't worry about it. If it makes you feel better you could use the Sniffer class's has_header() method. 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 Jul 20 10:11:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Jul 2007 10:11:37 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <7x8x9lwka9.fsf@ruckus.brouhaha.com> Message-ID: John Nagle wrote: > Juergen Erhard wrote: >> On proving programs correct... from my CS study days I distinctly >> remember thinking "sure, you can prove it correct, but you cannot do >> actual useful stuff with it". We might have come a long way since >> then (late 80s :P), but I don't hold out much hope (especially since >> the halting problem does exist, and forever will). > > The halting problem only applies to systems with infinite memory. > > Proof of correctness is hard, requires extensive tool support, and > increases software development costs. But it does work. > > Check out the "Spec#" effort at Microsoft for current work. > Work continues in Europe on Extended Static Checking for Java, > which was developed at DEC before DEC disappeared. > The issue I have with correctness proofs (at least as they were presented in the 1980s - for all I know the claims may have become more realistic now) is that the proof of correctness can only relate to some highly-formal specification so complex that it's only comprehensible to computer scientists. In other words, we can never "prove" that a program does what the customer wants, because the semantics are communicated in different ways, involving a translation which, since it is necessarily performed by humans using natural language, will always be incomplete at best and inaccurate at worst. 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 Wed Jul 25 19:32:50 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 25 Jul 2007 23:32:50 GMT Subject: Singleton in Python Cookbook References: <5gq00tF3fm71gU1@mid.uni-berlin.de> Message-ID: <877ioot5y5.fsf@pobox.com> "Diez B. Roggisch" writes: [...] > AFAIK the cookbook is completely found online at ASPN. So no sweat > publishing it here. [...] No: the book-form cookbook is edited, and has extra text. I believe the recipes are under a BSD-style license, though. John From bignose+hates-spam at benfinney.id.au Tue Jul 10 04:05:49 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 10 Jul 2007 18:05:49 +1000 Subject: Simple operator associativity and precedence rules (was: 2**2**2**2**2 wrong? Bug?) References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> Message-ID: <87zm24lm3m.fsf_-_@benfinney.id.au> "Jim Langston" writes: > 2**2 = 4 > 4**2 = 16 > 16**2 = 256 > 256**2 = 65536 > 65536**2 = 4294967296 > > In fact, if I put (2**2)**2**2**2 > it comes up with the correct answer, 4294967296 I have never gone wrong with mathematical expressions since I reduced the set of operator associativity and precedence rules to these: 1. Addition and subtraction have the same precedence, and are left-to-right associative 2. Multiplication and division have the same precedence, and are left-to-right associative 3. Use parentheses to make explicit all other precedence and associativity The specific programming language I use at any given moment might follow more complex rules, but I ignore them in favour of the above set. I thus spend less time uselessly thinking about tasks I should be delegating to explicit expression syntax, and am never surprised by a misunderstood mathematical associativity or precedence rule. -- \ "A hundred times every day I remind myself that [...] I must | `\ exert myself in order to give in the same measure as I have | _o__) received and am still receiving" -- Albert Einstein | Ben Finney From michele.simionato at gmail.com Tue Jul 10 00:32:45 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Tue, 10 Jul 2007 04:32:45 -0000 Subject: Should I use Python for these programs? In-Reply-To: References: Message-ID: <1184041965.807750.6140@c77g2000hse.googlegroups.com> On Jul 10, 5:09 am, CC wrote: > 2. Develop a simple vector drawing program that will allow one to > freehand draw a sketch composed of a few lines, or perhaps render text > in a vector form. Then sample the lines with a certain (user > configurable) spacing, and use the mouse to move the sample points along > the lines to tweak the sample locations if desired. Then output a file > of X,Y coordinates for the samples. You may look at dia for that. Michele Simionato From jeffbg123 at gmail.com Wed Jul 11 08:45:21 2007 From: jeffbg123 at gmail.com (jeffbg123) Date: Wed, 11 Jul 2007 12:45:21 -0000 Subject: Screen Scraping Question Message-ID: <1184157921.488811.295570@n60g2000hse.googlegroups.com> Hey, I am trying to make a bot for a flash game using python. However I am having some trouble with a screen scraping strategy. Is there an accepted way to compare a full screenshot with the image that I want to locate? It is a math based game, so I just have to check what number, 1-9, appears in the center of the flash game. Is there an easier method to do this? Thanks -Jeff From restycena at gmail.com Thu Jul 12 05:42:25 2007 From: restycena at gmail.com (kublai) Date: Thu, 12 Jul 2007 09:42:25 -0000 Subject: web page text extractor Message-ID: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> Hello, For a project, I need to develop a corpus of online news stories. I'm looking for an application that, given the url of a web page, "copies" the rendered text of the web page (not the source HTNL text), opens a text editor (Notepad), and displays the copied text for the user to examine and save into a text file. Graphics and sidebars to be ignored. The examples I have come across are much too complex for me to customize for this simple job. Can anyone lead me to the right direction? Thanks, gk From klove at tax.ok.gov Mon Jul 30 15:30:45 2007 From: klove at tax.ok.gov (Kenneth Love) Date: Mon, 30 Jul 2007 14:30:45 -0500 Subject: Comparing Dictionaries In-Reply-To: <1185611025.943782.162330@w3g2000hsg.googlegroups.com> References: <1185611025.943782.162330@w3g2000hsg.googlegroups.com> Message-ID: <6.1.0.6.2.20070730142159.026a2ec0@tax.ok.gov> At 03:23 AM 7/28/2007, you wrote: >Hi Kenneth, being new to Python i wondered if you at least considered >Doctests as part of your testing solution. >Other languages don't have Doctest. > >- Paddy. Until I read your post, I had never even heard of Doctest. I will look into it. Here is the list of online sources I've found: http://www.ibiblio.org/obp/thinkCSpy/index.html http://www.diveintopython.org/toc/index.html http://aspn.activestate.com/ASPN/Cookbook/Python Here are the O'Reilly books I purchased from Barnes & Noble: Python in a Nutshell (2nd ed.) Python Cookbook (2nd ed.) Programming Python (3rd ed.) I am a slow reader. So, if Doctests are mentioned in any of the above, I haven't encountered it yet. Specifically, my information on unit testing comes from reading about half of this online chapter: http://www.diveintopython.org/unit_testing/index.html I will search on Google for more info on Doctest. Thanks! Sincerely, Kenneth Love -- -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- Kenneth Love | Oklahoma Tax Commission DP Programmer/Analyst | Information Technology (405) 522 - 5864 | http://www.tax.ok.gov/ -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- From gagsl-py2 at yahoo.com.ar Thu Jul 12 21:50:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Jul 2007 22:50:36 -0300 Subject: inspite of proper package structure, no module named xyz error. References: Message-ID: En Thu, 12 Jul 2007 16:54:24 -0300, krishnakant Mane escribi?: > hello all, > can some one suggest me the best solution for a package? > I have a package folder called idm and there are the following files in > there. > __init__.py which is right now empty. > mainwindow.py which has a single class called MainWindow which is an > MDI Parent frame from wxpython. > student.py which is a child frame which gets called from the main menu. > exam.py, another child frame. > now when I try to run mainwindow.py file with the "import > idm"statement, I get the following error. > no module named idm. I would avoid importing the package itself from inside of it. That is, from the *outside*, import idm as any other client would do. And from *inside* the package, import the relevant parts using relative imports. I'm not convinced this is absolutely the right way to do things, but at least it's less bug prone. -- Gabriel Genellina From python at jayloden.com Wed Jul 25 18:38:45 2007 From: python at jayloden.com (Jay Loden) Date: Wed, 25 Jul 2007 18:38:45 -0400 Subject: first, second, etc line of text file In-Reply-To: <13aff82d1v7ge0f@corp.supernews.com> References: <5f56302b0707251244p24080f1ct87a5f459cb175dae@mail.gmail.com> <13afdpp7a6t24c5@corp.supernews.com> <1185396840.702955.31890@l70g2000hse.googlegroups.com> <13aff82d1v7ge0f@corp.supernews.com> Message-ID: <46A7D0F5.8090609@jayloden.com> Grant Edwards wrote: > On 2007-07-25, Jeff wrote: > >> That might be a memory problem if you are running multiple processes >> regularly, such as on a webserver. > > I suppose if you did it in parallel 50 processes, you could use > up 250MB of RAM. Still not a big deal on many servers. A > decent OS will swap regions that aren't being used to disk, so > it's likely not to be a problem. Or, you might be reading from a text file dramatically larger than a 3MB copy of War and Peace. I regularly deal with log files that are often many times that, including some that have been well over a GB or more. Trust me, you don't want to read in the entire file when it's a 1.5GB text file. It's true that many times readlines() will work fine, but there are also certainly cases where it's not acceptable for memory and performance reasons. -Jay From buzzard at urubu.freeserve.co.uk Fri Jul 20 18:47:56 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 20 Jul 2007 23:47:56 +0100 Subject: Sorting dict keys In-Reply-To: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> Message-ID: montyphyton at gmail.com wrote: > Consider the following: > >>>>a = {1:2, 3:4, 2:5} > > > Say that i want to get the keys of a, sorted. First thing I tried: > > >>>>b = a.keys().sort() >>>>print b > > None > > Doesn't work. Probably because I am actually trying to sort the keys > of the dictionary without copying them first. If that is the case, > fine. Next thing I do: > > >>>>b = a.keys() >>>>b.sort() > > [1, 2, 3] > > Works fine, but I would really like it if I could somehow do it in one > line. As the problem seems to be copying the object, i try the > following: > > >>>>import copy >>>>b = copy.copy(a.keys()).sort() >>>>print b > > None > > Hmmm, why doesn't it work? Also, > > >>>>b = copy.deepcopy(a.keys()).sort() >>>>print b > > None > > (not that I thought that deepcopy will work since shallow didn't, I > understand the difference :) ) > Obviously, I am missing something here. What am I thinking wrong? Why > doesn't copying the object work? > Thanks for all the help > sort() sorts a list in place and returns None. For a one-liner: >>> a = {1:2, 3:4, 2:5} >>> b = sorted(a.keys()) >>> b [1, 2, 3] Duncan From deets at nospam.web.de Mon Jul 30 11:45:12 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 30 Jul 2007 17:45:12 +0200 Subject: Bug? exec converts '\n' to newline in docstrings!? References: Message-ID: <5h6fc8F3ik4oeU1@mid.uni-berlin.de> Edward K Ream wrote: > It looks like both exec and execfile are converting "\n" to an actual > newline > in docstrings! > > Start idle: > > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] > on win32 > [rest of signon deleted] > >>>> s = '''\ > strings = 'abc'.split("\n") > ''' >>>> print s > strings = 'abc'.split(" > ") > > I see this in my own calls to exec and execfile. Is this a bug or am I > missing something? AFAIK docstrings are nothing special. So \-escaping is of course available, as it's an important feature for strings in general. For the case at hand, strings = 'abc'.split("\\n") might help. Diez From nick at craig-wood.com Wed Jul 11 16:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 11 Jul 2007 15:30:04 -0500 Subject: storing pickles in sql data base References: <592087469.jZQWuvoN0q@teancum> Message-ID: David Bear wrote: > I need to store pickled objects in postgresql. I reading through the pickle > docs it says to always open a file in binary mode because you can't be sure > if the pickled data is binary or text. So I have 2 question. Can I set the > pickle to be text -- and then store it in a 'text' type field in my sql > table, or should what sql type should I save the pickle as? You could always encode it into text form, eg >>> from cPickle import dumps, loads >>> a = range(10) >>> a [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> b = dumps(a).encode("zip").encode("base64").strip() >>> b 'eJzTyCkw5PI04Er0NARiIyA2BmITIDYFYjMgNgdiCyC25ErUAwD5DQqD' >>> loads(b.decode("base64").decode("zip")) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> -- Nick Craig-Wood -- http://www.craig-wood.com/nick From mhellwig at xs4all.nl Sat Jul 28 09:43:14 2007 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Sat, 28 Jul 2007 15:43:14 +0200 Subject: Comparing Dictionaries In-Reply-To: References: <87abtih7x0.fsf@benfinney.id.au> Message-ID: <46ab480e$0$10721$e4fe514c@dreader21.news.xs4all.nl> Kenneth Love wrote: > That should teach me not to change working code at the same time I am > writing unit tests. Even so, I realize it won't be the last time I > do something so silly. Yes, I know about TDD's "write the test first", > but I'm not comfortable with the philosophy of these new fangled unit > tests yet. > I've been using python for about 3 years now, it was the first programming language I learned and I haven't done any other since (well that is if you dismiss sql and shell scripting on various platforms). Though in my daily job I have some coding tasks, I do not see my self as a programmer since in my perspective a programmer is someone who can write good code regardless of the language. My code isn't any good, it is barely functional (so I really needed unit-test way of coding, for my own protection and not even because it gives more maintenance security for the project). But the funny thing that I have seen in the development scene is that writing tests first and code later is a lot easier when you have a technical specification to base it on. A technical specification is of course based on a functional design. A functional design is written on the base of the assignment and the scope definition. The scope and design can change in the course of the project but good practice is usually to do changes in another release. And that is what software change management and release management is for. Still there are tons of reasons why you shouldn't follow blindly the best practice, since best practice is founded on theory molded around the most occurring reality. And the only thing that I am absolutely sure of is that reality differs enough from person to person and situation to situation, that forcing the same practice to every person/situation is a guarantee for wasting time and energy. IMHO there are two extreme basic types of programmers, on the left are the ones that have a problem them self, solve it while happily hacking along the way, leaving the design part for a later stage, on the right are people that know beforehand on an almost bit level what a program is supposed to do, already have a design and aren't really that interested in the problem that their code should solve in the first place. Me I am a bit schizophrenic, I move in between of them, on a hourly base. So for me the reality is that I have a certain 'problem' I write some code with the built-in IDLE mostly following functional coding practice (since I still have to figure out how some stuff works in python). Then when I have a an idea what I am doing, I create a new project tree in subversion and write my technical specification (still having IDLE open to test some of the wild ideas that pop-up along the way). After that I open Eclipse/PyDEV and start working on the unit-test and follow from there, when the code is finished I check it in and branch it as 0.0.1. Sleep over it and probably refactor it later on because I didn't like some variables names and want to add some comments in the code or move out some code to other classes, etc. etc. The only problem is that I wish I was a bit more stable, because several times it has happend that I thought that the problem is a one-liner, so skipped the whole part after the figure-out-the-problem-code and used that what I have already written. Sometimes that works out well, but if it doesn't it always bites me hard. But all these are just experiences from my side, I have no idea whether I am right or not, but for me it seems to work, so don't take it as advice (I am not really the person to take advice from) but as a little 'story' along the way :-) -- mph From mail at microcorp.co.za Thu Jul 12 02:36:18 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 12 Jul 2007 08:36:18 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net><468565a0$0$3686$426a74cc@news.free.fr><7xhcopj10g.fsf@ruckus.brouhaha.com><46863ea7$0$970$426a34cc@news.free.fr><1i0ikru.1uccqtm1efnzn3N%aleax@mac.com><1i0n0tr.ve0o791347ugyN%aleax@mac.com><7xd4za1086.fsf@ruckus.brouhaha.com><5f0mhuF3b0stbU1@mid.individual.net><7xd4z837e2.fsf@ruckus.brouhaha.com><468b7426$0$9063$426a34cc@news.free.fr><7x4pkkun56.fsf@ruckus.brouhaha.com><1183575597.272150.152200@w5g2000hsg.googlegroups.com><7xzm2budfv.fsf@ruckus.brouhaha.com><7xir8vju1l.fsf@ruckus.brouhaha.com><7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: <000901c7c47a$f8cd3240$03000080@hendrik> "John Nagle" wrote: > I've worked in big mainframe shops, where an operating system > crash caused everything to suddenly freeze, red lights came on all > over the building, and a klaxon sounded. I've worked for aerospace > companies, where one speaks of "defects", not "bugs", and there > are people around whose job involves getting in high performance > aircraft and flying with the software written there. I've worked > with car-sized robot vehicles, ones big enough to injure people. > > This gives one a stronger feeling about wanting to eliminate > software defects early. > Does this actually cause you to make less goofy mistakes? - I find that no matter how careful I try to be, I still f***k up. not so much in the big things, its the little things that get me... And the errors seem to come in runs - almost like a "bad hair day". - Hendrik From kyosohma at gmail.com Mon Jul 30 09:48:13 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 30 Jul 2007 13:48:13 -0000 Subject: How to write GUI and event separately in wxPython?? In-Reply-To: <1185777254.925902.204500@z28g2000prd.googlegroups.com> References: <1185777254.925902.204500@z28g2000prd.googlegroups.com> Message-ID: <1185803293.941965.223520@j4g2000prf.googlegroups.com> On Jul 30, 1:34 am, Jia Lu wrote: > HI all > > I am making an application with wxpython. > But I got a problem when I want to change the display string > according to process status. > > I passed the frame to the processing function and use the > frame.txtobj to change displaying strings. > > I found it is a bad method to do that. > Can any one tell me how to do that usually? > ( How to separate GUI and Control code? ) > > Thank you. If you're doing a long running task that needs to send data periodically to the GUI front-end for status, there's some good ways listed here: http://wiki.wxpython.org/LongRunningTasks The wiki seems down right now (8:40 CST 07/30/2007), but hopefully it'll be up soon. Mike From the.mindstorm.mailinglist at gmail.com Wed Jul 11 18:10:28 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Wed, 11 Jul 2007 15:10:28 -0700 Subject: stripping the first byte from a binary file In-Reply-To: <5fkfpjF37im5qU1@mid.uni-berlin.de> References: <1184063032.195000.25880@i13g2000prf.googlegroups.com> <1184115964.912526.273780@e16g2000pri.googlegroups.com> <1184148168.639675.85900@a26g2000pre.googlegroups.com> <4694B01A.30107@web.de> <1184153416.798767.163740@d55g2000hsg.googlegroups.com> <5fk3geF3b8794U1@mid.uni-berlin.de> <1184164948.266014.178760@g4g2000hsf.googlegroups.com> <5fkfpjF37im5qU1@mid.uni-berlin.de> Message-ID: <1184191828.037264.197860@w3g2000hsg.googlegroups.com> On Jul 11, 7:45 pm, "Diez B. Roggisch" wrote: > Alex Popescu wrote: > > On Jul 11, 4:15 pm, "Diez B. Roggisch" wrote: > >> > Forgive my newbie ignorance, but I am wondering why the other method > >> > would not work? I mean it may not be very safe, > >> > but I guess it may perform a lot better, than having to read the whole > >> > file just to cut out the first byte. > > >> Because seeking is not moving? Shifting data bytewise isn't something > >> that is supported by the underlying OS filesystems, and thus not > >> supported. But replacing bytes with others is. Which seek is for. > > >> Diez > > > As far as I know seek is just about positioning and nothing else. > > It is. > > > So, in fact the problem boils down to os support for deleting a bytes. > > Which there isn't, as I and several others pointed out. And "replacing" is > not removing. > > Diez I do agree with your last statement (and it was my mistake to consider replacing a possible way to remove). Just wanted to clarify that seek is only for positioning. bests, ./alex -- .w( the_mindstorm )p. From kyosohma at gmail.com Thu Jul 19 09:10:38 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 19 Jul 2007 06:10:38 -0700 Subject: Posted messages not appearing in this group In-Reply-To: References: <1184742315.618696.202600@z24g2000prh.googlegroups.com> Message-ID: <1184850638.496091.279160@g4g2000hsf.googlegroups.com> On Jul 18, 5:50 am, Alex Popescu wrote: > Sanjay gmail.com> writes: > > > > > Hi All, > > > I tried posting in this group twice since last week, but the messages > > did not appear in the forum. Don't know why. Trying this message > > again... > > > Sanjay > > Something similar seemed to happen to me too, but when checking with gmane I've > noticed that all my posts got in (and now I am trying to figure out how can I > apologize for multiple posts :-) ). > > bests, > ./alex > -- > .w( the_mindstorm )p. If you use google groups to post, then it's something to do with Google. It seems to be having some serious issues this week. And I've had it not post my posts before even though it ended up on gmane. Google seems to forward the message, but it does a lousy job updating itself of late. Mike From steve at holdenweb.com Thu Jul 26 20:02:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Jul 2007 20:02:42 -0400 Subject: SQLObject 0.9.1 In-Reply-To: References: <20070726143614.GI30176@phd.pp.ru> Message-ID: Sherm Pendley wrote: > Gerardo Herzig writes: > >> So..at 11:23 we got version 0.7.8...at 11:30 was version 0.8.5...now >> there is a 0.9.1 version?? Have a coffe dude > > Sounds more to me like he needs to lay off the coffee, or at least switch > to decaffeinated for a while. :-) > Come on, give Oleg a break. He's maintaining three separate versions in parallel. While I haven't downloaded the releases yet I am prepared to bet that 0.7.8 and 0.8.5 backport all the bugfixes that have been applied to 0.9.1. Should the PSF not have released 2.4.4? 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 gherron at islandtraining.com Thu Jul 26 16:29:39 2007 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 26 Jul 2007 13:29:39 -0700 Subject: question about math module notation In-Reply-To: <46a901c5$0$25771$9b622d9e@news.freenet.de> References: <46a901c5$0$25771$9b622d9e@news.freenet.de> Message-ID: <46A90433.9040307@islandtraining.com> Stargaming wrote: > On Thu, 26 Jul 2007 15:54:11 -0400, brad wrote: > > >> How does one make the math module spit out actual values without using >> engineer or scientific notation? >> >> I get this from print math.pow(2,64): 1.84467440737e+19 >> >> I want this: >> 18,446,744,073,709,551,616 >> >> I'm lazy... I don't want to convert it manually :) >> > > Explicitly converting it to `int` works for me. (Without the 3-digit- > block notation, of course.) > It's got nothing to do with the math module. Any floating point number, whether produced by the math module or not, can be converted to a printable representation using the % operator with a format string: >>> x = 1.84467440737e+19 >>> x 1.84467440737e+19 >>> print '%25.3f' % x 18446744073699999744.000 >>> print '%12.5e' % x 1.84467e+19 >>> print '%12.5g' % x 1.8447e+19 See http://docs.python.org/lib/typesseq-strings.html for all he details. Gary Herron From ahlongxp at gmail.com Sun Jul 8 04:20:38 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Sun, 08 Jul 2007 08:20:38 -0000 Subject: socket: connection reset by server before client gets response In-Reply-To: <5fbgbdF3b4vgcU1@mid.individual.net> References: <1183819907.249945.239700@o11g2000prd.googlegroups.com> <1183827514.109496.252870@d30g2000prg.googlegroups.com> <46902a45$0$331$e4fe514c@news.xs4all.nl> <1183870439.595652.305590@z28g2000prd.googlegroups.com> <5fbgbdF3b4vgcU1@mid.individual.net> Message-ID: <1183882838.988784.241780@g37g2000prf.googlegroups.com> > So, umm, what exactly are you trying to accomplish? > It looks like what is happening is the server only accepts 99 bytes. It > then does the send and the close. yes. What I want is that, server sends response to client and closes connection when it feels recieving enough information, and make sure at the same time ,client will definitely get the response from server. > The client wants to send 120 bytes, 10 bytes at a time. By the time is > does the 12th send the server has already finished, closing its socket > and exiting. So when the client attempts send #12 the socket is already > closed. Thus the error. > > I'm not sure why you are getting the 'connection reset' instead of > 'broken pipe'. Probably different OS. (I'm using Mac OS X 10.4.10.) > as I saied before, running results will varies. And most of the time they are working quite well. But that's not enough. > Anyway, I changed your code slightly, wrapping the send in a try/except > block like this: > try: > s.send('0123456789') > except socket.error ,e: > print "Socket Error:", e > break > > Now here are my results for the client: > time 0 > time 1 > time 2 > time 3 > time 4 > time 5 > time 6 > time 7 > time 8 > time 9 > time 10 > time 11 > error: (32, 'Broken pipe') > Received 'OK' This really helped. Now I know the client will still get the response even under 'Connection reset by peer' or 'Broken pipe'. > The way you had it the program crashed before it could do the receive. > > Frank Frank, thanks a lot. -- ahlongxp Software College,Northeastern University,China ahlongxp at gmail.com http://www.herofit.cn From James.w.Howard at gmail.com Mon Jul 16 13:22:02 2007 From: James.w.Howard at gmail.com (JamesHoward) Date: Mon, 16 Jul 2007 17:22:02 -0000 Subject: Best method for inter process communications Message-ID: <1184606522.541918.18870@22g2000hsm.googlegroups.com> I am looking for a way of performing inter process communication over XML between a python program and something else creating XML data. What is the best way of performing this communication? I could bind a socket to localhost and perform the data transfer that way, but that seems inefficient due to the addition of TCP/IP or UDP/IP overhead. Is there a way to stream data via a custom datastream (I.E. not STDIO, STDERR, etc)? Thanks in advance, Jim Howard From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jul 9 12:06:09 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 09 Jul 2007 18:06:09 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xabu7e9ku.fsf@ruckus.brouhaha.com> References: <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <468c0827$0$22906$426a74cc@news.free.fr> <7x3b03lusa.fsf@ruckus.brouhaha.com> <468c18fc$0$26377$426a74cc@news.free.fr> <7xabu7e9ku.fsf@ruckus.brouhaha.com> Message-ID: <46925cdf$0$27972$426a34cc@news.free.fr> Paul Rubin a ?crit : > Bruno Desthuilliers writes: >>> Some users in fact recommend writing an explicit type signature for >>> every Haskell function, which functions sort of like a unit test. >> Stop here. explicit type signature == declarative static typing != >> unit test. > > The user-written signature is not a declaration that informs the > compiler of the type. The compiler still figures out the type by > inference, just as if the signature wasn't there. The user-written > signature is more like an assertion about what type the compiler will > infer. If the assertion is wrong, the compiler signals an error. In > that sense it's like a unit test; it makes sure the function does what > the user expects. It still boils down to the same problem : possibly valid types are rejected based on a declaration. >> I have few "surprises" with typing in Python. Very few. Compared to >> the flexibility and simplicity gained from a dynamism that couldn't >> work with static typing - even using type inference -, I don't see it >> a such a wonderful gain. At least in my day to day work. > > I'm going to keep an eye out for it in my day-to-day coding but I'm > not so convinced that I'm gaining much from Python's dynamism. I sure do. > However, that may be a self-fulfilling prophecy since maybe I'm > cultivating a coding style that doesn't use the dynamism, Perhaps is this coding style not making the best use of Python's features ? To me, it sounds like doing procedural programming in OCaml - it's of course possible, but probably not the best way to use the language. > and I could > be doing things differently. I do find since switching to Python 2.5 > and using iterators more extensively, I use the class/object features > a lot less. Data that I would have put into instance attributes on > objects that get passed from one function to another, instead become > local variables in functions that get run over sequences, etc. Dynamism is more than simply adding "cargo" attributes to objects. From kimiraikkonen85 at gmail.com Sun Jul 1 16:10:26 2007 From: kimiraikkonen85 at gmail.com (kimiraikkonen) Date: Sun, 01 Jul 2007 13:10:26 -0700 Subject: The best platform and editor for Python In-Reply-To: <48881$46880677$d443bb3a$16222@news.speedlinq.nl> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183318637.021496.185990@k29g2000hsd.googlegroups.com> <48881$46880677$d443bb3a$16222@news.speedlinq.nl> Message-ID: <1183320626.081034.233560@q69g2000hsb.googlegroups.com> On Jul 1, 10:59 pm, Stef Mientki wrote: > > Thank you for the suggestions. I'd prefer a GUI-based, helpful and > > easy-implemention skilled enviroment. Tesekkurler Sayin Kartal :-) > > then first decide which graphical package you want to use, > because that limits your choice. > > cheers, > Stef Mientki I only have experience with Dev C++ for GUI and debugging based programming for C/C++. But i didn't know about Python. So, like Visual Studio and Dev C++ similiar Python editor is welcome. From ahlongxp at gmail.com Tue Jul 24 05:16:51 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Tue, 24 Jul 2007 09:16:51 -0000 Subject: some parts of wxPython broken on Mac Message-ID: <1185268611.681037.298490@m37g2000prh.googlegroups.com> Sorry, I know this is not the most appropriate place to talk about wxPython. But I can't have access to wxPython mail list page(because I don't pay enough). I downloaded python2.5 and wxPython 2.8.4.0 from pythonmac.org and installed them into one of my friends' Mac 10.4.8(intel) and I found wx.lib.flatnotebook and wx.xrc were broken(which are quite OK under both Linux and Windows). because I don't have the machine, I can't give more details. I hope someone will be good enough to check out these problems. -- ahlongxp Software College,Northeastern University,China ahlongxp at gmail.com http://www.herofit.cn From jeffrey at fro.man Thu Jul 26 11:59:16 2007 From: jeffrey at fro.man (Jeffrey Froman) Date: Thu, 26 Jul 2007 08:59:16 -0700 Subject: Why PHP is so much more popular for web-development References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> Message-ID: <13ahh6kosqqeba1@corp.supernews.com> walterbyrd wrote: > The point is: PHP framework makers are very considerate of the > realities of shared hosting. I think the opposite is true: PHP applications typically ignore the realities of shared hosting in order to be considerate to non-developers (that is to say, "users"). In particular, security in a shared hosting environment is almost always discarded. Consider a PHP-based CMS that allows users to upload files. Because the application runs as the webserver user, uploaded files, and the directory where they reside, must be accessible and writable by that user. It is the same user that any other hosting customer on that machine has access to. Thus, any user on the shared host could write a quick CGI script that accesses, adds, removes, or defaces your uploaded content. While it is true that PHP can be deployed through fastcgi/suexec to avoid this problem, doing so is just as complicated as deploying python applications through fastcgi. Deploying python applications through mod_python suffers the same drawbacks on a shared host that using mod_php does, but it is quite simple to set up: 3 lines or so in an .htaccess file is all that is required to get mod_python configured. Surely PHP developers need to write their own .htaccess files as well in most cases? On a related note, most PHP hosting providers offer only PHP4. While this is again fine for the typical PHP *user*, I would hope that PHP *developers* are looking primarily (if not exclusively) for PHP5 at this point. PHP5 providers are much rarer. All that said, I am sympathetic to your concerns, and am currently working hard to set up a commercial shared hosting environment that offers turn-key Django and Plone provisioning. Certainly, the automated, generic set-up won't suit everyone's fine-tuned requirements, but I agree that more hosts should think about providing a working default configuration for python frameworks. Jeffrey From aleax at mac.com Wed Jul 18 02:06:11 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 17 Jul 2007 23:06:11 -0700 Subject: Can a low-level programmer learn OOP? References: Message-ID: <1i1f43w.1mme4h8bjjsqlN%aleax@mac.com> Dennis Lee Bieber wrote: > On Mon, 16 Jul 2007 11:45:04 -0700, Chris Carlen > declaimed the following in > comp.lang.python: > > > The more I play with Python, the more I like it. Perhaps I will > > understand OOP quicker than I thought. What I've learned so far about > > names binding to objects instead of values stored in memory cells, etc. > > has been interesting and fascinating. > > Don't confuse Python's "roaming names" with OOP, though. There are > OOP languages that still follow the variable=>memory address containing > object structure. C++, definitely. But most OO languages, like Java &c, use a more modern "object reference" naming scheme, just like Python, FP languages, etc. Alex From jjkk73 at gmail.com Mon Jul 2 16:41:05 2007 From: jjkk73 at gmail.com (jj kk) Date: Mon, 2 Jul 2007 22:41:05 +0200 Subject: python script for monitoring input/output parameters of online gaming client Message-ID: Hi, I'd like to be able to capture parameters of online gaming client applications (the kind of client software you install to play poker, backgammon... online) with the aim of writing python software that analyzes this data. I'm clueless, as I know next to nothing about python networking. Could anyone please point out in what direction I should look to solve this, what libraries I should look at, etc. ? Thanks a lot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Sun Jul 1 11:59:07 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 01 Jul 2007 17:59:07 +0200 Subject: object references/memory access In-Reply-To: <7xfy48871j.fsf@ruckus.brouhaha.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> Message-ID: <4687cf4b$0$24940$9b622d9e@news.freenet.de> > If this is a Linux server, it might be possible to use the SCM_RIGHTS > message to pass the socket between processes. I very much doubt that the OP's problem is what he thinks it is, i.e. that copying over a local TCP connection is what makes his application slow. > That would require a > patch to Python's socket library which I've never gotten around to > writing but it's been on my want-to-do list for a long time. There is > something similar for Solaris and probably for *BSD. I've been under > the impression that this is how preforked Apache distributes requests > between processes, but I never got around to checking. No, it doesn't. Instead, it is the operating system itself which distributes the requests: the parent process opens the server socket, then forks the actual server processes. They all do accept, and the operating system selects an arbitrary one for the next request. That process returns from accept, so for the next incoming connection, one of the remaining processes will be selected. Regards, Martin From cam.ac.uk at mh391.invalid Mon Jul 2 09:26:55 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 02 Jul 2007 14:26:55 +0100 Subject: Python changing keywords name In-Reply-To: References: <1182630774.701295.50890@k79g2000hse.googlegroups.com> <1182651282.747106.239720@o61g2000hsh.googlegroups.com> Message-ID: Gabriel Genellina wrote: > "except" is hard to translate, and > even in English I don't see what is the intended meaning (is it a noun? > a verb? an adverb? all look wrong). It's a preposition. -- Michael Hoffman From gdamjan at gmail.com Tue Jul 10 09:03:50 2007 From: gdamjan at gmail.com (Damjan) Date: Tue, 10 Jul 2007 15:03:50 +0200 Subject: Building a Python app with Mozilla References: <1183524527.709730.190290@q75g2000hsh.googlegroups.com> <5f30vsF3aicltU1@mid.individual.net> <1183647423.458469.166460@m36g2000hse.googlegroups.com> Message-ID: <46938369$0$90268$14726298@news.sunsite.dk> > Last I looked (3.1-ish), Qt didn't use the Aqua widgets Qt is now up to 4.3 and they use native Aqua -- damjan From stargaming at gmail.com Tue Jul 24 10:10:53 2007 From: stargaming at gmail.com (Stargaming) Date: 24 Jul 2007 14:10:53 GMT Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> Message-ID: <46a6086d$0$8399$9b622d9e@news.freenet.de> On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote: > There are various things I like about the D language that I think Python > too may enjoy. Here are few bits (mostly syntactical ones): > > 1) (we have discussed part of this in the past) You can put underscores > inside number literals, like 1_000_000, the compiler doesn't enforce the > position of such underscores, so you can also put them like this: > 1_00_000. You can put them in literals of decimals, binary, hex, etc. I > think it's quite useful, because when in Python code I have a line like: > for i in xrange(1000000): > I need some time to count the zeros, because the lower levels of my > visual systems can't count/group them quickly (perceptually). While in a > syntax like: > for i in xrange(1_000_000): > my eyes help me group them at once. Sounds like a good thing to be but the arbitrary positioning doesnt make any sense. Additionally, I'd suggest 10**n in such cases (eg. 10**6). > 2) Base 2 number literals, and base 2 "%b" printing with the writefln. > Base-2 numbers are less common in Python code, but once in a while I use > them. For example: > import std.stdio; > void main() { > auto x = 0b0100_0011; > writefln("%b", x); > writefln("%.8b", x); > writefln(x); > } > Prints: > 1000011 > 01000011 > 67 Accepted. http://www.python.org/dev/peps/pep-3127/#abstract > 3) All string literals are multi line. So you can write: a = "how are > you"; > There's no need for """ """. Well, I think it's just better to recognize visually. If you read ``foo = """...``, it's clear you can skip the next few lines because they're most likely a chunk of data, not program code. Single quotation mark makes clear this is just a very small token in the whole line. (Yes, there may be exceptions, there may be syntax highlighting.) > 4) With D I have created an xsplit() generator, and from my tests it's > quite faster than the split(), expecially if the string/lines you want > to split are few hundred chars long or more (it's not faster if you want > to split very little strings). So I think Python can enjoy such string > method too (you can probably simulate an xsplit with a regular > expression, but the same is true for some other string methods too). Yea, that's a good idea -- fits into the current movement towards generator'ing everything. But (IIRC) this idea came up earlier and there has been a patch, too. A quick search at sf.net didn't turn up anything relevant, tho. > Bye, > bearophile Regards, Stargaming From raims at dot.com Wed Jul 18 09:48:02 2007 From: raims at dot.com (Lawrence Oluyede) Date: Wed, 18 Jul 2007 15:48:02 +0200 Subject: Copy List References: <-29831789359750479@unknownmsgid> Message-ID: <1i1geiz.1hzeify9qvkzkN%raims@dot.com> Joe Riopel wrote: > I am pretty new to python but this works: > > >>> list_one = [0,1,2,3,4,5,6,7,8,9] > >>> list_two = [i for i in list_one] > >>> print list_two > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >> list_two = list_one[:] or >> list_two = list(list_one) are better :D -- 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 anonymisiert85 at mymail.ch Thu Jul 5 07:47:57 2007 From: anonymisiert85 at mymail.ch (anonymisiert85 at mymail.ch) Date: Thu, 05 Jul 2007 04:47:57 -0700 Subject: (EMBEDDING) Can't get python error message Message-ID: <1183636077.260642.31760@q69g2000hsb.googlegroups.com> I run this string to produce a error "x+1" PyRun_SimpleStringFlags() return -1, so that i know this is a script with error inside... but now - how can i get error message? i tested some py-functions - but this functions do not work... i called this functions direct after PyRun_SimpleStringFlags PyErr_Occurred() return always 0 PyErr_Fetch() with 3 pointers... all values are always Null PyErr_Print() do nothing strange... but after my programm end... here comes a error message (from StdErr i think) Traceback (most recent call last): File "", line 1, in NameError: name 'x' is not defined From steve at REMOVE.THIS.cybersource.com.au Sat Jul 28 23:39:35 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 29 Jul 2007 13:39:35 +1000 Subject: replacement for execfile References: Message-ID: On Sat, 28 Jul 2007 15:17:56 +0000, Alex Popescu wrote: > Hi all! > > From another thread (and the pointed PEP) I have found that execfile > will not be present in Py3k. So, I am wondering what will be its > replacement? Considering that most probably Py3k will keep eval and > exec, this will still be possible (indeed requiring manual loading of > the file string), so I would really appreciate some enlightning comments > on this. (1) Don't use eval, exec or execfile. (2) If you're an expert, don't use eval, exec or execfile. (3) If you're an expert, and are fully aware of the security risks, don't use eval, exec or execfile. (4) If you're an expert, and are fully aware of the security risks, and have a task that can only be solved by using eval, exec or execfile, find another solution. (5) If there really is no other solution, you haven't looked hard enough. (6) If you've looked REALLY hard, and can't find another solution, AND you're an expert and are fully aware of the security risks, THEN you can think about using eval, exec or execfile. > Background: > Basically this question is related to my learning process/working > project. In this, I have the need to allow the final user to provide a > configuration like script, but built using my API (and whatever other > normal Python code they want). I hope this is running on their own computer, not yours. If they're running it on a multi-user system, I hope they don't care about security, because they probably don't have any now. > For this, having execfile was a nice surprise Oh yes, I bet it was, in more ways than one. > as I was able to automatically expose the API (so the end user > doesn't need to bother about imports) and also easily execute it in the > context I wanted. Let's see that I understand you... you're expecting the users to write working Python code, but you think "import module" is too hard for them? Anyway, with all the disclaimers above, execfile is trivial: def execfile_(filename, globals_=None, locals_=None): if globals_ is None: globals_ = globals() if locals_ is None: locals_ = globals_ text = file(filename, 'r').read() exec text in globals_, locals_ -- Steven. From stesch at no-spoon.de Sat Jul 28 16:09:49 2007 From: stesch at no-spoon.de (Stefan Scholl) Date: Sat, 28 Jul 2007 22:09:49 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> <0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de> <0T49iehiIt1hNv8%stesch@parsec.no-spoon.de> <46AB8194.2060906@web.de> <0T49il77ItapNv8%stesch@parsec.no-spoon.de> Message-ID: <0T49ish0ItfaNv8%stesch@parsec.no-spoon.de> Chris Mellon wrote: > On 7/28/07, Stefan Scholl wrote: >> Just checked on a system without PyXML: xml/sax/__init__.py >> defines parseString() and uses cStringIO (when available). >> >> Python 2.5.1 >> > > Yes, thats the fixed bug. After all this you still do not seem to be > clear on what the bug is. The bug is not that your code fails in 2.5, > it's that it worked at all in 2.4. Don't let the subject line fool you. I'm OK with cStringIO. The thread is now about xml.sax's parseString(). -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From zaperaj at gmail.com Fri Jul 13 22:57:33 2007 From: zaperaj at gmail.com (zaperaj at gmail.com) Date: Fri, 13 Jul 2007 19:57:33 -0700 Subject: how to install pygame package? In-Reply-To: References: <1184303076.915138.43310@o11g2000prd.googlegroups.com> Message-ID: <1184381853.115531.122440@g37g2000prf.googlegroups.com> There seems to be some problem. For the tar version, initial steps execute OK, but after typing: [root at localhost pygame-1.7.1release]# ./configure bash: ./configure: No such file or directory So i don't hav a configure file? What should i do now? From moranar at gmail.com Mon Jul 9 07:03:29 2007 From: moranar at gmail.com (Adriano Varoli Piazza) Date: Mon, 09 Jul 2007 04:03:29 -0700 Subject: socket: connection reset by server before client gets response In-Reply-To: <1183972571.875740.13930@z28g2000prd.googlegroups.com> References: <1183819907.249945.239700@o11g2000prd.googlegroups.com> <1183900086.021428.83580@e9g2000prf.googlegroups.com> <1183969844.697022.298650@w3g2000hsg.googlegroups.com> <1183972571.875740.13930@z28g2000prd.googlegroups.com> Message-ID: <1183979009.295965.60230@d55g2000hsg.googlegroups.com> ahlongxp wrote: > I feel officially offended. I didn't intend to offend you, I was joking. I apologise in any case. There's a few things to be said, though: As per your message in another thread, it isn't that you don't express yourself clearly in English, but that you were too quick to claim a standard function was buggy without first thinking if your own code could be buggy instead. That presumption isn't related to the language. Second, if you do say that you aren't comfortable in English, try to assume that people aren't trying to insult you by default. I was speaking generallyin my message. Third, this is usenet. Although probably not in this newsgroup, if you continue to make the assumptions I and others pointed out, you will receive this kind of answer. Perhaps with much more insult than right now. So it is a great idea to grow a thick skin. -- Saludos Adriano From chris.lyon at spritenote.co.uk Thu Jul 26 20:21:46 2007 From: chris.lyon at spritenote.co.uk (chris.lyon at spritenote.co.uk) Date: Thu, 26 Jul 2007 17:21:46 -0700 Subject: generating objects of a type from a name. Message-ID: <1185495706.034366.58180@k79g2000hse.googlegroups.com> I'm trying to generate visual python objects from django objects and therefore have objects called 'Ring' and 'Cylinder' as django objects and I want to create objects of those names in visual. I can cludge it in varius ways by using dir and lots of if lookups but is there a way of doing this that allows the name to generate a visual object of the appropriate name or fail nicely if the visual object doesn't exist? From bbxx789_05ss at yahoo.com Thu Jul 5 12:11:29 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Thu, 05 Jul 2007 09:11:29 -0700 Subject: list.append not working? In-Reply-To: <1183651138.209079.37620@q75g2000hsh.googlegroups.com> References: <1183651138.209079.37620@q75g2000hsh.googlegroups.com> Message-ID: <1183651889.219469.64950@n60g2000hse.googlegroups.com> Hardy wrote: > I experience a problem with append(). This is a part of my code: > > for entity in temp: > md['module']= entity.addr.get('module') > md['id']=entity.addr.get('id') > md['type']=entity.addr.get('type') > #print md > mbusentities.append(md) > #print mbusentities > > I want something like: [{'module': 'home', 'id': 123, 'type': 'core'}, > {'module': 'work', 'id': 456, 'type': 'core'}] > md is always correct, BUT:mbusentities is wrong. Length of > mbusentities is same of temp, so it appended everything. BUT: > mbusentities only shows the values of the last append: [{'module': > 'work', 'id': 456, 'type': 'core'}, {'module': 'work', 'id': 456, > 'type': 'core'}] > > What's wrong? Inside your loop, you assign md["module"], md["id"], and md["type"] the same values over and over again. From __peter__ at web.de Sun Jul 22 14:53:43 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 22 Jul 2007 20:53:43 +0200 Subject: UnicodeDecodeError References: <46A2709C.3040602@seehart.com> Message-ID: Ken Seehart wrote: >> I am wondering if anyone knows where I can find a mapping from this >> particular extended ascii code (where \xd1 is ?), to the corresponding >> unicode characters. > Um, never mind. The recent unicode conversation gave me my answer :-) > unicode(s, 'Windows-1252') Run the following script to get a few more candidates: import encodings import os import glob def encodings_from_modulenames(): ef = os.path.dirname(encodings.__file__) for fn in glob.glob(os.path.join(ef, "*.py")): fn = os.path.basename(fn) yield os.path.splitext(fn)[0] def find_encodings(unistr, bytestr, encodings=None): if encodings is None: encodings = encodings_from_modulenames() for encoding in encodings: try: encoded = unistr.encode(encoding) except Exception: pass else: if encoded == bytestr: yield encoding for encoding in find_encodings(u"\N{LATIN CAPITAL LETTER N WITH TILDE}", "\xd1"): print encoding Peter From kw at codebykevin.com Tue Jul 24 10:28:16 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 24 Jul 2007 10:28:16 -0400 Subject: Tix not properly installed on OS X? In-Reply-To: References: <48B39FEC-D3B9-4FAF-AD45-0DD744D8D289@bryant.edu> Message-ID: <46A60C80.60502@codebykevin.com> Jay Loden wrote: > Brian Blais wrote: >> Hello, >> >> I am running OS X 10.4, on an Intel Mac, Python 2.5 not installed by >> source (I used the binary install from the website). When I do the >> following, I get an error: >> >> 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 Tix >> >>> root=Tix.Tk() >> Traceback (most recent call last): >> File "", line 1, in >> File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ >> python2.5/lib-tk/Tix.py", line 210, in __init__ >> self.tk.eval('package require Tix') >> _tkinter.TclError: can't find package Tix >> > > I can confirm the same behavior and Google results are not promising: > > http://www.thescripts.com/forum/thread653175.html > http://aspn.activestate.com/ASPN/Mail/Message/ActivePython/3525325 > > I tried installing Tix from the binary TclAqua package, and when I run root=Tix.Tk() I still get the same error (though, interestingly, a Tk window does open). Looks like your best bet right now would be to install Tix via fink if that's an option. > > -Jay You need an up-to-date installation of the base Tix package on your system, in the same path as your Tcl/Tk libraries. I downloaded and built the most recent version of Tix from http://tix.sf.net (dated November 2006) and the Python samples run fine. I think the problem is that Tix is generally considered obsolete, or at least very outdated, by Tcl developers, so many distributions do not include it. It is not shipped with ActiveState on the Mac, nor does Apple include Tix in the Tcl/Tk libraries bundled with OS X. From my perspective there are far better, more modern alternatives, such as BWidgets, TkTreeCtrl, Tablelist, and Tile (all of which have Python wrappers) to enhance the core Tk widgets. Tix appears to be more widely used by Python/Tkinter developers than Tcl/Tk developers. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From jayharvard at gmail.com Mon Jul 16 19:54:16 2007 From: jayharvard at gmail.com (jayharvard at gmail.com) Date: Mon, 16 Jul 2007 23:54:16 -0000 Subject: Binary blobs to jpeg In-Reply-To: <139nhcpl4jk7he6@corp.supernews.com> References: <1184612270.455699.254560@r34g2000hsd.googlegroups.com> <1184612920.610854.226290@57g2000hsv.googlegroups.com> <139nhcpl4jk7he6@corp.supernews.com> Message-ID: <1184630056.809650.34070@g4g2000hsf.googlegroups.com> On Jul 16, 3:23 pm, Grant Edwards wrote: > On 2007-07-16, jayharva... at gmail.com wrote: > > >> Have you tried to open the file in "wb" mode? > > > The data is coming from a record set selection from the Access > > database. I guess I could write the data to a temp file and > > open that file handle with the "wb" mode. But, no, I haven't > > tried that. > > I think you missed the point. > > When you want to write the binary data to a file, you must open > the destination file using "wb" mode. It's binary data, not > text data, so you have to open the output file in binary mode. > > -- > Grant Edwards grante Yow! Is my fallout shelter > at termite proof? > visi.com I did miss the point. I will give that a shot. Thanks Carsten and Grant From steve at holdenweb.com Sun Jul 8 08:59:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 08 Jul 2007 08:59:12 -0400 Subject: httplib module In-Reply-To: References: Message-ID: Boris Ozegovic wrote: > Steve Holden wrote: > >>>> Why do I get double new lines when geting data from server? Example: >> How? It's customary to include details when you've solved your own >> problem in case someone else gets the same issue. > > Ok. In do_GET I had this two lines: > > for line in file: > print line > > As you can see, print inserted another \n. :-) > > Correct code is: > > for line in file: > print line, > Thanks. Glad you got it sorted out. 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 aahz at pythoncraft.com Wed Jul 18 17:43:36 2007 From: aahz at pythoncraft.com (Aahz) Date: 18 Jul 2007 14:43:36 -0700 Subject: Real-time Update References: <1184747090.102324.265230@i13g2000prf.googlegroups.com> Message-ID: In article <1184747090.102324.265230 at i13g2000prf.googlegroups.com>, ReTrY wrote: > >I'm writing a program with Tkinter GUI, When the program is running it >need to be updated every five seconds (data comes from internet). How >should I do that ? How to make a function in main loop ? See the Tkinter example from my threads tutorial on my website. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I support the RKAB From horpner at yahoo.com Wed Jul 4 07:21:14 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 04 Jul 2007 11:21:14 GMT Subject: what is wrong with that r"\" References: Message-ID: On 2007-07-04, Nick Craig-Wood wrote: >> String quotes can be escaped with a backslash, but the >> backslash remains in the string; for example, r"\"" is a >> valid string literal consisting of two characters: a >> backslash and a double quote; > > a) That is weird! Why would you ever want to do that - ie > insert \" into your string as a special case? If I wanted a " > in a raw string then I'd use a r'' string or a triple quoted > string. > > If we removed a) then we could remove b) also and r"" strings > would work as everyone expects. > > Does anyone know the justification for a)? Maybe we should > remove it in py3k? If the escaped quotes didn't function in raw strings, I'd be unable to construct (with a single notation) a regex that included both kinds of quotes at once. re.compile(r"'\"") -- Neil Cerutti From gnewsg at gmail.com Wed Jul 25 11:04:58 2007 From: gnewsg at gmail.com (billiejoex) Date: Wed, 25 Jul 2007 08:04:58 -0700 Subject: How to tell when a socket is closed on the other end? In-Reply-To: References: <1185371863.622473.205010@19g2000hsx.googlegroups.com> Message-ID: <1185375898.605135.182080@57g2000hsv.googlegroups.com> On 25 Lug, 16:37, Roy Smith wrote: > This isn't really a Python question, it's a Berkeley Socket API question. > You don't say, but I assume you're talking about a TCP (i.e. SOCKSTREAM) > connection? Yes. > The answer is you can use the select() system call to detect "exceptional > conditions" on a socket. Python's select module provides this > functionality, but to understand how to use it, you need to study the > underlying API. > > On the other hand, socket.read() returning 0 works too. What do you find > "poor" about that? What do you want to know about the connection being > closed that you don't find out by getting 0 back from read()? 'poor' because it's 'tricky', since that send/write() and recv/read() should be used for other tasks... As far as I can tell this works on Linux and Windows, but I don't know on other platforms. From omari at smileystation.com Sat Jul 28 07:54:28 2007 From: omari at smileystation.com (Omari Norman) Date: Sat, 28 Jul 2007 07:54:28 -0400 Subject: Where do they tech Python officialy ? In-Reply-To: <7xveca4ajp.fsf@ruckus.brouhaha.com> References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> Message-ID: <20070728115428.GA1816@cameron> On Mon, Jul 23, 2007 at 10:48:10PM -0700, Paul Rubin wrote: > If you're having trouble with Python because you're new at > programming, I can sympathize--I don't think it's the most > beginner-friendly of languages despite the efforts in that direction > by the designers. Just curious--what language would you recommend as most beginner-friendly? My previous programming experience was with BASIC--and I think it is true that BASIC will, in many ways, rot your brain. I had used QBasic and, later, a little VBA and some PHP. It took some time to unlearn some bad things (object orientation in VBA seems to be mostly a hack, for example, while PHP seems to be a big hack generally) but it seems to me that Python helped me learn my first modern programming language. > I think Python is not used in university programs very much. Look for > one that uses SICP (Scheme) or CTM (Mozart/Oz) or a functional > language like Haskell, in preference to the ones that use Java (the > Cobol of the 1990's). With some reasonable experience in Scheme or > Mozart or Haskell, plus a Python manual, you'll be well on your way. I had heard of these languages, but learning them is a bit discouraging because (Java excepted) they don't seem to get much practical use. In college I had a programming course that used C++. Big mistake in my view, and we didn't learn much in the way of true principles (in retrospect it would have been nice if they had us use GCC rather than Borland on Windows.) From wbrehaut at mcsnet.ca Fri Jul 13 15:31:22 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Fri, 13 Jul 2007 13:31:22 -0600 Subject: 2**2**2**2**2 wrong? Bug? References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> <1184173446.779276.250530@k79g2000hse.googlegroups.com><1184182757.797808.206480@d55g2000hsg.googlegroups.com> Message-ID: On Wed, 11 Jul 2007 21:37:00 -0400, "Terry Reedy" wrote: > >"Evan Klitzke" wrote in message >news:cfb58d850707111747x4b83cb88wcaf45437e8e14511 at mail.gmail.com... >| On 7/11/07, Gabriel Genellina wrote: >| > Just for curiosity: This helps to find the answer to the problem "Which >is >| > the largest number that can be written with only 3 digits?" >| > Some people stop at 999, others try 99**9 and 9**99, and the winner is >| > 9**9**9, or: >| > >| > | 9 >| > | 9 >| > | 9 >| > >| > Sorry, couldn't resist. >| >| But you can append ! (i.e. factorial) indefinitely without adding any >| digits to make the number arbitrarily large ;-) > >But as Gabriel showed, 9**9**9 in standard math pen-and-paper or >chalk-and-blackboard notation, not the squished computer linear imitation >thereof, uses three nines and nothing else ;-) Since no base was specified: (hex) F**F**F > (dec) 9**9**9 and we could use BASE-64 numbers (immediately coming to mind if we ever drove a CDC CYBER machine), where: (base-64) del**del**del > (hex) F**F**F > (dec) 9**9**9 Then someone who had read the Busy Beaver reference would introduce base-BB2, or (where we assume the digits base-BB2 are 0, 1, ..., BB2(???)): BB2(11111) ** BB2(11111) ** BB2(11111) and so on, ad infinitum--as the bard said (http://www-groups.dcs.st-and.ac.uk/~history/Quotations/De_Morgan.html): Great fleas have little fleas upon their backs to bite 'em, And little fleas have lesser fleas, and so ad infinitum. And the great fleas themselves, in turn, have greater fleas to go on; While these again have greater still, and greater still, and so on. wwwayne === "Come along son, and put your whip away. That horse is dead!" --- Wise Old Man >tjr > > From steve at holdenweb.com Fri Jul 13 08:14:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Jul 2007 08:14:11 -0400 Subject: MaildirMessage In-Reply-To: <874pk8kedo.fsf@benfinney.id.au> References: <1184287592.509355.310110@g4g2000hsf.googlegroups.com> <874pk8kedo.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > "Gabriel Genellina" writes: > >> msg is an instance of MaildirMessage (subclass of Message) - it has >> no specific iterator, so "for m in msg" tries to use the sequence >> protocol, starting at 0; that is, tries to get msg[0]. Message >> objects support the mapping protocol, and msg[0] tries to find a >> *header* 0, converting the name 0 to lowercase, and fails miserably. > > Which is a bug in the 'email.message' module, in my view. If it's > attempting to support a mapping protocol, it should allow iteration > the same way standard Python mappings do: by iterating over the keys. > Stop assuming that everyone sees requirements the same as you - the author of the email module has long years of experience, and has provided an excellent and overall usable piece of software. Criticisms such as yours are easy (we can all experess our opinions, to which we are all entitled), but mere expression of an opinion isn't going to change anything. Instead, change the module to do what you think it should. Then you can at least use it yourself, and if your code is a genuine improvement you can submit it as a patch. 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 Tue Jul 24 02:59:27 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 24 Jul 2007 08:59:27 +0200 Subject: Pickled objects over the network References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com><011401c7caa0$3e3e5900$03000080@hendrik> <012901c7cb60$5ba530c0$03000080@hendrik> <00c601c7cc38$d826ba00$03000080@hendrik> <00bd01c7ccf6$8fa62540$03000080@hendrik> Message-ID: <00be01c7cdc0$2db1f240$03000080@hendrik> "Steve Holden" wrote: > It's difficult to establish, and then correctly implement, almost any > security protocol without leaving cracks that attackers can lever open > and use to inject code into your process's memory space. I can accept this - its difficult enough to write a receiver that syncs up and produces correctly that which was transmitted for all concievable input, without even worrying about evil input - so a string can contain code, and there is not a hell of a lot that you can do about it on the receiving side, when all the rest of the framing and error checking is correctly presented. It seems to me that the threat is not so much having evil code lying around in the machine's memory, but the mechanism for actually executing it. - If you think about it, your PC's memory normally has a lot of stuff in it that is ultra poisonous if it were to be executed - any data table or image would soon crash if executed as code. So it seems to me that to be safe, you can only transfer highly structured data, and not live objects, as objects tend to get control at some stage... > > By all means go ahead and hack on pickle to do what you want to. Just > don't claim your solution is secure without a thorough review. > I am not the OP, and I have had a (very) brief look at the code in the pickle module - and when I saw it was still using marshal, I did not follow through. - but from what I can understand of it, the whole functionality would probably have to be crippled to the point of just transferring very simple structures to make it secure. - it seems to be a mini stack based language, driven by its input. So after all this hoo haw - I find myself kind of agreeing with Steve Holden. - a secure pickle is not the way to go. Damn! : - ) But more seriously - is there any need for a simple serialiser that will be able to be used to transfer a subset of the built in types over an open network in a safe manner, for the transfer of things like lists of parameters? Or am I the only person in the squad that hears this particular drum? - Hendrik From dennis.varghese at wipro.com Tue Jul 10 11:28:05 2007 From: dennis.varghese at wipro.com (pycraze) Date: Tue, 10 Jul 2007 08:28:05 -0700 Subject: Need Help Message-ID: <1184081285.869000.75460@i38g2000prf.googlegroups.com> Hi , I need some info about the following snippet . ----------------------------------------------------------- protocol = 'NTLMSSP\000' #name type = '\001\000' #type 1 zeros1 = '\000\000' zeros2 = '\000\000\000\000\000\000\000\000\000' zeros3 = '\000\000\000\000\000\000\000\000\000\000\000' smthg1 = '0\000\000\000\000\000\000\000' # something with chr(48) length? smthg2 = '0\000\000\000' # something with chr(48) lenght? msg1 = protocol + type + zeros1 + flags + zeros2 + zeros3 + smthg1 + smthg2 msg1 = base64.encodestring(msg1) msg1 = string.replace(msg1, '\012', '') ------------------------------------------------------- In the above code what does " 000\000\000\000\000\000\000\000\000 " signify ? Which form of representation is this ? This code is from the NTLM APS python code from sourceforge 0.98 version . From marcpp at gmail.com Thu Jul 5 05:02:29 2007 From: marcpp at gmail.com (Marcpp) Date: Thu, 05 Jul 2007 02:02:29 -0700 Subject: WXPYTHON push button call a frame Message-ID: <1183626149.036739.281070@w5g2000hsg.googlegroups.com> Hi I need to call a widget from a button in WXPYTHON. I've tried to this from a function like this, but when push the button, the program opens a window and do error. Any idea? ..... def DialogRRHH(self,event): prog = wx.PySimpleApp(0) wx.InitAllImageHandlers() DialogRRHH = MTRRHH(None, -1, "") prog.SetTopWindow(DialogRRHH) DialogRRHH.Show() prog.MainLoop() class MTRRHH(wx.Frame): ....... if __name__ == "__main__": app = wx.PySimpleApp(0) wx.InitAllImageHandlers() tasques = tasques(None, -1, "") app.SetTopWindow(tasques) tasques.Show() app.MainLoop() From nytrokiss at gmail.com Thu Jul 19 13:16:43 2007 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 19 Jul 2007 10:16:43 -0700 Subject: Posted messages not appearing in this group In-Reply-To: <469f92ac$0$1345$834e42db@reader.greatnowhere.com> References: <1184742315.618696.202600@z24g2000prh.googlegroups.com> <1184859628.544564.127670@m3g2000hsh.googlegroups.com> <469f92ac$0$1345$834e42db@reader.greatnowhere.com> Message-ID: <8a6b8e350707191016y37ce3326k49d2818e471443ca@mail.gmail.com> I am also having some issues. There is a post on the list that appeared 7 times because of this issue i think. On 7/19/07, David H Wild wrote: > > In article <1184859628.544564.127670 at m3g2000hsh.googlegroups.com>, > Adrian Petrescu wrote: > > Maybe it has shown up and Google simply isn't showing it yet. Can > > anyone confirm that a thread posted yesterday (July 18th, 2007) whose > > title was something like "interpreting os.lstat() output" exists or > > not? > > That thread is there, with four postings. > > -- > David Wild using RISC OS on broadband > www.davidhwild.me.uk > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/watches.asp?Brand=14 http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From hjp-usenet2 at hjp.at Sun Jul 1 10:11:32 2007 From: hjp-usenet2 at hjp.at (Peter J. Holzer) Date: Sun, 1 Jul 2007 16:11:32 +0200 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: On 2007-06-22 20:33, James Harris wrote: > I have a requirement to store timestamps in a database. Simple enough > you might think but finding a suitably general format is not easy. The > specifics are > > 1) subsecond resolution - milliseconds or, preferably, more detailed > 2) not bounded by Unix timestamp 2038 limit > 3) readable in Java > 4) writable portably in Perl which seems to mean that 64-bit values > are out > 5) readable and writable in Python > 6) storable in a free database - Postgresql/MySQL Stick to unix timestamps but store them as a double precision floating point number. The 53 bit mantissa gives you currently a resolution of about 200 ns, slowly deteriorating (you will hit ms resolution in about 280,000 years, if I haven't miscalculated). Any language and database should be able to handle double-precision FP numbers, so that's as portable as it gets and conversion from/to system time should be trivial. If you need to represent milliseconds exactly, you can just multiply the timestamp with 1000 (and get java timestamps). hp -- _ | Peter J. Holzer | I know I'd be respectful of a pirate |_|_) | Sysadmin WSR | with an emu on his shoulder. | | | hjp at hjp.at | __/ | http://www.hjp.at/ | -- Sam in "Freefall" From steve at holdenweb.com Wed Jul 4 11:59:10 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Jul 2007 11:59:10 -0400 Subject: using subprocess for non-terminating command In-Reply-To: <20070704143641.GA3434@gmail.com> References: <1183549118.773813.132940@r34g2000hsd.googlegroups.com> <1183550943.531211.306410@n60g2000hse.googlegroups.com> <20070704143641.GA3434@gmail.com> Message-ID: O.R.Senthil Kumaran wrote: > * zacherates [2007-07-04 12:09:03]: > >>> How should I handle these kind of commands (ping 127.0.0.1) with >>> subprocess module. I am using subprocess, instead of os.system because >>> at anypoint in time, I need access to stdout and stderr of execution. >> Ping, for one, allows you to set an upper bound on how long it runs >> (the -c option). This is probably the cleanest approach if it's >> available. >> > > Yes, I am aware of the ping -c option. But again even that does not help. > try > process = subprocess.Popen('ping -c 10 127.0.0.1', stdin=subprocess.PIPE, > shell=True) > process.stdout.read() # This will hang again. > > I am not sure, why subprocess is behaving so. > >> You can also send the subprocess signals if you need it to exit >> (although, this is a unix thing so I'm not sure how portable it is). > > Yes, I have tried to kill and then get the standard output result. > But the result has been the same. I could not read the Popen returned file > object. > >> You could emulate having a timeout on child.stdout.read by registering >> a callback with Timer to kill the child. > > I dont know how to do this. I shall give it a try ( by looking around ) and > trying. > Is it possible your ping implementation outputs to stderr? 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 Tue Jul 31 13:30:32 2007 From: fabioztessitore at libero.it (Fabio Z Tessitore) Date: 31 Jul 2007 17:30:32 GMT Subject: Error with Tkinter and tkMessageBox Message-ID: <46af71b7$0$10619$4fafbaef@reader2.news.tin.it> 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 From ask at me Mon Jul 16 00:55:26 2007 From: ask at me (alf) Date: Sun, 15 Jul 2007 23:55:26 -0500 Subject: determining the source code and module based on the class Message-ID: Hi, Let's say I have a class defined somewhere: class A: pass now I import (indirectly) a module defining that class (and in fact thousands of others defined in hundreds of modules) where all I have is a list of them provided: l=[A,B,C] now I need a piece of code which based on the class name can point to the module as well as the line number where the given class is defined. Is it doable in Python? -- alf From oneelkruns at hotmail.com Mon Jul 2 11:17:00 2007 From: oneelkruns at hotmail.com (rtk) Date: Mon, 02 Jul 2007 08:17:00 -0700 Subject: Tiny/small/minimalist Python? In-Reply-To: <7xved3satm.fsf@ruckus.brouhaha.com> References: <1183332951.122782.212720@o11g2000prd.googlegroups.com> <7xved3satm.fsf@ruckus.brouhaha.com> Message-ID: <1183389420.175712.59460@z28g2000prd.googlegroups.com> On Jul 1, 10:12 pm, Paul Rubin wrote: > You've gotten good suggestions about Python configurations. Depending > on your application you might look at alternative languages as well. > Lua and Hedgehog Lisp both come to mind as small embedded interpreters. PyMite will get a closer look from me eventually but I found that Lua will fit my immediate needs quite nicely. Thanks for the suggestion. FYI.. I wanted a simple version of Python to run on an ancient DEC Alpha box. I got VMS Python 2.5 up and running but it is too slow to use. It takes *minutes* to get the interpreter prompt after typing 'python'! Lua, on the other hand, compiled without changes (used the ANSI switch) and runs nicely. I'm always up for learning a new language anyway. Ron From semanticist at gmail.com Fri Jul 13 02:45:40 2007 From: semanticist at gmail.com (Miles) Date: Fri, 13 Jul 2007 06:45:40 -0000 Subject: bool behavior in Python 3000? In-Reply-To: References: <46961f33$0$90263$14726298@news.sunsite.dk> Message-ID: <1184309140.606670.109950@r34g2000hsd.googlegroups.com> On Jul 12, 8:37 pm, Alan Isaac wrote: > I do not like that bool(False-True) is True. I've never seen the "A-B" used to represent "A and not B", nor have I seen any other operator used for that purpose in boolean algebra, though my experience is limited. Where have you seen it used? What's wrong with 'and', 'or', and 'not'? I think that redefining *, +, and - to return booleans would only encourage programmers to use them as shortcuts for standard boolean operations--I'd hate to see code like this: >>> if user.registered * (user.age > 13) - user.banned: ... I don't mind that arithmatic operations are _possible_ with bools, but I would strongly prefer to see the boolean keywords used for operations on booleans. -Miles From escalation746 at yahoo.com Sun Jul 22 23:23:48 2007 From: escalation746 at yahoo.com (escalation746) Date: Sun, 22 Jul 2007 20:23:48 -0700 Subject: custom plugin architecture: how to see parent namespace? In-Reply-To: References: <1185113192.049692.258310@k79g2000hse.googlegroups.com> <1185148311.431968.148520@m3g2000hsh.googlegroups.com> <1185156202.232114.319300@n60g2000hse.googlegroups.com> Message-ID: <1185161028.601194.202170@22g2000hsm.googlegroups.com> Jorge Godoy wrote: > escalation746 wrote: > > I have updated documentation for this on my blog, diagrammes modernes. > > Surf: > >http://diagrammes-modernes.blogspot.com/ > > Your motivation looks a lot like what is solved by setuptools, eggs and > entry points. Though that problem domain looks different (installation, app dependencies), you are no doubt correct that there is functionality overlap. However, that is a maximal solution while mine is minimal and hence (maybe) of use to people who prefer a couple dozen lines of code to an entire package. -- robin From nagle at animats.com Mon Jul 16 13:14:42 2007 From: nagle at animats.com (John Nagle) Date: Mon, 16 Jul 2007 10:14:42 -0700 Subject: Fetching a clean copy of a changing web page In-Reply-To: <1184566190.197725.296610@n60g2000hse.googlegroups.com> References: <1184566190.197725.296610@n60g2000hse.googlegroups.com> Message-ID: Miles wrote: > On Jul 16, 1:00 am, John Nagle wrote: > >> I'm reading the PhishTank XML file of active phishing sites, >>at "http://data.phishtank.com/data/online-valid/" This changes >>frequently, and it's big (about 10MB right now) and on a busy server. >>So once in a while I get a bogus copy of the file because the file >>was rewritten while being sent by the server. >> >> Any good way to deal with this, short of reading it twice >>and comparing? >> >> John Nagle > > > Sounds like that's the host's problem--they should be using atomic > writes, which is usally done be renaming the new file on top of the > old one. How "bogus" are the bad files? If it's just incomplete, > then since it's XML, it'll be missing the "" and you should > get a parse error if you're using a suitable strict parser. If it's > mixed old data and new data, but still manages to be well-formed XML, > then yes, you'll probably have to read it twice. > > -Miles Yes, they're updating it non-atomically. I'm now reading it twice and comparing, which works. Actually, it's read up to 5 times, until the same contents appear twice in a row. Two tries usually work, but if the server is updating, it may require more. Ugly, and doubles the load on the server, but necessary to get a consistent copy of the data. John Nagle From nytrokiss at gmail.com Thu Jul 26 15:28:35 2007 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 26 Jul 2007 12:28:35 -0700 Subject: <> vs != Message-ID: <8a6b8e350707261228x234b7da0g17d43736e45e67ca@mail.gmail.com> Dear Lists What is the difference between <> and != Thank You James -- http://www.goldwatches.com/watches.asp?brand=55 http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From no at no.no Tue Jul 17 08:25:50 2007 From: no at no.no (Daniel) Date: Tue, 17 Jul 2007 15:25:50 +0300 Subject: a=0100; print a ; 64 how to reverse this? References: <1184670575.205759.115360@i13g2000prf.googlegroups.com> Message-ID: On Tue, 17 Jul 2007 14:09:35 +0300, mosi wrote: > > Problem: > how to get binary from integer and vice versa? > The simplest way I know is: > a = 0100 > a > 64 Also that is not binary - that is octal, binary would be: '01000000' (denoted as a string, since 01000000 in octal is actually 262144 in decimal. From semanticist at gmail.com Mon Jul 23 16:34:20 2007 From: semanticist at gmail.com (Miles) Date: Mon, 23 Jul 2007 16:34:20 -0400 Subject: URL parsing for the hard cases In-Reply-To: References: <1185138747.707836.69740@n2g2000hse.googlegroups.com> Message-ID: On 7/23/07, Miles wrote: > On 7/22/07, John Nagle wrote: > > Is there any library function that correctly tests for an IP address vs. a > > domain name based on syntax, i.e. without looking it up in DNS? > > import re, string > > NETLOC_RE = re.compile(r'''^ # start of string > (?:([^@])+@)? # 1: > (?:\[([0-9a-fA-F:]+)\]| # 2: IPv6 addr > ([^\[\]:]+)) # 3: IPv4 addr or reg-name > (?::(\d+))? # 4: optional port > $''', re.VERBOSE) # end of string > > def normalize_IPv4(netloc): > try: # Assume it's an IP; if it's not, catch the error and return None > host = NETLOC_RE.match(netloc).group(3) > octets = [string.atoi(o, 0) for o in host.split('.')] > assert len(octets) <= 4 > for i in range(len(octets), 4): > octets[i-1:] = divmod(octets[i-1], 256**(4-i)) > for o in octets: assert o < 256 > host = '.'.join(str(o) for o in octets) > except (AssertionError, ValueError, AttributeError): return None > return host Apparently this will generally work as well: import re, socket NETLOC_RE = ... def normalize_IPv4(netloc): try: host = NETLOC_RE.match(netloc).group(3) return socket.inet_ntoa(socket.inet_aton(host)) except (AttributeError, socket.error): return None Thanks to http://mail.python.org/pipermail/python-list/2007-July/450317.html -Miles From wbrehaut at mcsnet.ca Sun Jul 15 16:10:04 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Sun, 15 Jul 2007 14:10:04 -0600 Subject: 2**2**2**2**2 wrong? Bug? References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> <1184362033.094940.199250@n60g2000hse.googlegroups.com> Message-ID: On Fri, 13 Jul 2007 14:27:13 -0700, "mensanator at aol.com" wrote: >On Jul 13, 1:20 pm, Wayne Brehaut wrote: >> On Mon, 09 Jul 2007 23:51:25 -0700, "mensana... at aol.com" >> >> >> >> >> >> wrote: >> >On Jul 9, 11:42?pm, Paul McGuire wrote: >> >> On Jul 9, 11:21 pm, "Jim Langston" wrote:> In Python 2.5 on intel, the statement >> >> > 2**2**2**2**2 >> >> > evaluates to>>> 2**2**2**2**2 === 8< === >> >Did you count the 'L'? >> >> numdigits(n)? === 8< === >> What? 'L' is a digit in Python? > >No, but it's a character. Don't you know the difference >between str() and repr()? Don't you know the difference between humorous (even if slightly silly at times) banter and serious discussion? Did you bother to read the context before responding? Do you know what you're attributing to whom, and whether they're actually the ones who said it--and, if so, do you understand what they meant by it? === 8< === >> I'm going back to Fortran! > >Sounds like you never left. Now that's a low blow--but I'll consider the source and overlook it. w >> >> wwwayne >> >> >>so this seems to be at least in >> >> the ball park. >> >> >> -- Paul From sjmachin at lexicon.net Sun Jul 29 17:41:45 2007 From: sjmachin at lexicon.net (John Machin) Date: Sun, 29 Jul 2007 14:41:45 -0700 Subject: Understanding mxODBC Insert Error In-Reply-To: References: Message-ID: <1185745305.233676.231370@e16g2000pri.googlegroups.com> On Jul 30, 2:41 am, Greg Corradini wrote: > Hello, > I'm trying to perform a simple insert statement into a table called > Parcel_Test (see code below). Yet, I get an error message that I've never > seen before (see traceback below). I've tried to put a semicolon at the end > of the sql statement, but with no luck. Any ideas from more experienced > mx.ODBC users? You tried to put a semicolon at the end of the SQL statement, but you failed? Luck?? I would have thought it needed only steady hands and a minimally functional text editor. > > CODE > > >>> driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace > >>> conn = odbc.DriverConnect(driv) > >>> crs = conn.cursor() > >>> sql = "INSERT into Parcel_Test(NEAR_FID,NEAR_DIST) values > >>> ('0.000000','0.000000') where PIN_ID = '042822120008'" Are you sure that that is exactly what you ran? I'm not familiar with "pyshell", but I'd expect an error message (SyntaxError: EOL while scanning single-quoted string) on the line that starts with "sql =". At this stage do this to see exactly what you've got: print repr(sql) Maybe this pyshell gadget is trying to do statment continuation and failing. > >>> crs.execute(sql) > > TRACEBACK > Traceback (most recent call last): > File "", line 1, in ? > crs.execute(sql) > ProgrammingError: ('37000', -3516, '[Microsoft][ODBC Microsoft Access > Driver] Missing semicolon (;) at end of SQL statement.', 4612) > Suggestions: Type your code snippet into a text editor. Get whatever help you need with the semicolon. Save the snippet to a .py file. Run the .py file from your operating system's command line (not from "pyshell"). Show us the full traceback and the contents of your .py file. It might also help to mention what OS, what version of Python, and what version of mxODBC. HTH John From aleax at mac.com Wed Jul 18 21:59:13 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 18 Jul 2007 18:59:13 -0700 Subject: how to implementation latent semantic indexing in python.. References: <1184803885.142218.152490@g12g2000prg.googlegroups.com> Message-ID: <1i1gnc8.1yuwax3eieex3N%aleax@mac.com> Tim Churches wrote: > malkarouri wrote: > > On 13 Jul, 17:18, 78ncp wrote: > >> hi... > >> how to implementation algorithm latent semantic indexing in python > >> programming...?? > > > > Of course you are aware that LSA is patented.. > > There is a US patent on it, sealed in 1989, but is it patented in any > other countries? There is no such thing as a "global patent" - patents > only cover the country which issues them. There is a global patent > application process (the Patent Co-operation Treaty), but that just > establishes a priority date for the invention in each country, but the > inventor still needs to file patent applications and have them approved > (sealed) is each and every country. Did Bellcore do that back in the 1980s? Aren't patents supposed to last 17 years, anyway? A patent granted in 1989 should have expired in 2006, I believe (though IANAL, so...). Alex From rcdailey at gmail.com Mon Jul 9 16:44:56 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 09 Jul 2007 20:44:56 -0000 Subject: Distributing python apps In-Reply-To: <1184011429.403297.270560@n2g2000hse.googlegroups.com> References: <1184011164.346200.9330@q75g2000hsh.googlegroups.com> <1184011429.403297.270560@n2g2000hse.googlegroups.com> Message-ID: <1184013896.006483.176970@w3g2000hsg.googlegroups.com> Thanks a ton guys. You both gave me the exact answers I was looking for. From bignose+hates-spam at benfinney.id.au Thu Jul 12 07:26:50 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 12 Jul 2007 21:26:50 +1000 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <468565a0$0$3686$426a74cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <1i13w96.kyyobph71qxrN%aleax@mac.com> <7xwsx63we6.fsf@ruckus.brouhaha.com> Message-ID: <878x9llv5x.fsf@benfinney.id.au> Paul Rubin writes: > The idea of designing languages with more and more support for > ensuring program correctness is to put the established, repetitive > processes into the computer where it belongs, freeing the programmer > to be innovative while still providing high assurance of that the > program will be right the first time. This seems to make the dangerous assumption that the programmer has the correct program in mind, and needs only to transfer it correctly to the computer. I would warrant that anyone who understands exactly how a program should work before writing it, and makes no design mistakes before coming up with a program that works, is not designing a program of any interest. > Also, taking a learn-from-mistakes approach is fine and dandy if the > consequences of the mistakes stay contained to those who make them. > It's completely different if the consequences are imposed on other > people who weren't part of the process. Certainly. Which is why the trend continues toward developing programs such that mistakes of all kinds cause early, obvious failure -- where they have a much better chance of being caught and fixed *before* innocent hands get ahold of them. -- \ "We have to go forth and crush every world view that doesn't | `\ believe in tolerance and free speech." -- David Brin | _o__) | Ben Finney From gagsl-py2 at yahoo.com.ar Mon Jul 9 04:27:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Jul 2007 05:27:03 -0300 Subject: Htmllib help References: <070620070644.2754.468DE4C400077E4F00000AC222007348300D010C0E06A10407020E@comcast.net> Message-ID: En Fri, 06 Jul 2007 03:44:20 -0300, escribi?: > Thats right I don't need the output any where so I don't need to use the > writer. I can remove it wowever will the formater work since it needs > writer? Maybe I can use the Null writer? Exactly. Look at the HTMLParser module too; depending on your needs, it may be easier to use. > -------------- Original message ---------------------- > From: "Gabriel Genellina" >> En Thu, 05 Jul 2007 20:23:08 -0300, escribi?: >> > >> > Even though I don't use any print statements, the htmllib seems to be >> > throwing parts of the html page on to the standard out(my screen in >> this >> > case). Is there a way to disable the output? >> > >> > import htmllib >> > w = formatter.DumbWriter() >> >> Change the above line. From >> http://docs.python.org/lib/writer-impls.html: >> "class DumbWriter([file[, maxcol = 72]]) >> Simple writer class which writes output on the file object passed in as >> file or, if file is omitted, on standard output." -- Gabriel Genellina From aafshar at gmail.com Tue Jul 31 06:28:31 2007 From: aafshar at gmail.com (Ali) Date: Tue, 31 Jul 2007 10:28:31 -0000 Subject: win32 question in Python In-Reply-To: References: Message-ID: <1185877711.985538.73740@l70g2000hse.googlegroups.com> On Jul 30, 11:49 pm, Brad Johnson wrote: > Huang, Shun-Hsien ercot.com> writes: > > > > but how do I copy a excel file into > > > database table by using Python? > > I'm not sure if this helps, but you can access the Excel Automation model very > easily with: > > import win32com.client > > x1 = client.Dispatch("Excel.Application") > > Now you can use the x1 object to access any of the properties and methods in the > Excel Automation model. I have only used this to export data as Excel, but it may fulfill your needs for importing: http://sourceforge.net/projects/pyexcelerator/ Ali From bignose+hates-spam at benfinney.id.au Fri Jul 13 03:47:17 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 13 Jul 2007 17:47:17 +1000 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: <87zm20iw3e.fsf@benfinney.id.au> John Nagle writes: > Donn Cave wrote: > > In its day, goto was of course very well loved. > > No, it wasn't. By 1966 or so, "GOTO" was starting to look like a > bad idea. It was a huge hassle for debugging. This is interesting. Do you have any references we can read about this assertion -- specifically, that "GOTO" was not well loved (I assume "by the programming community at large") even by around 1966? -- \ "It is not enough to have a good mind. The main thing is to use | `\ it well." -- Rene Descartes | _o__) | Ben Finney From zellux at gmail.com Mon Jul 16 11:42:08 2007 From: zellux at gmail.com (ZelluX) Date: Mon, 16 Jul 2007 23:42:08 +0800 Subject: how to read python-doc in ubuntu? In-Reply-To: <5g1grrF3ekaguU1@mid.uni-berlin.de> References: <5g1grrF3ekaguU1@mid.uni-berlin.de> Message-ID: Got it. Thanks ;-) Diez B. Roggisch wrote: > ZelluX wrote: > >> Hi all, >> I'm a new comer to Python. >> I've installed python-doc module, but just don't know how to open it. >> Could you help me? >> >> Many thanks ^_^ > > dpkg -L > > will list the contents of the package at question. > > Doc packages usually reside under > > /usr/shar/doc/ > > diez From arkanes at gmail.com Wed Jul 11 11:17:48 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 11 Jul 2007 10:17:48 -0500 Subject: wxPython vs. Tkinter event loops In-Reply-To: <392e8$4694ee0a$4275d90a$27942@FUSE.NET> References: <392e8$4694ee0a$4275d90a$27942@FUSE.NET> Message-ID: <4866bea60707110817p123bd1a0k2868e15fd37939ed@mail.gmail.com> On 7/11/07, Kevin Walzer wrote: > I'm porting a Tkinter application to wxPython and had a question about > wxPython's event loop. > > The Tkinter app provides a GUI to a command-line tool. It gathers user > input, and opens an asynchronous pipe to the external tool via > os.popen(). Then, it dumps the output from the external process into a > text display. Although threads are often recommended for use with GUI > apps, I am able to keep the GUI responsive with Tkinter's event loop, > i.e. with regular calls to self.update(); I am still able to update the > GUI as needed. When I tried the same functions using threads, I noticed > no measurable improvement in application responsiveness or performance. > Thus, the application currently runs in a single thread and is updated > via Tkinter's event loop only. > > Does wxPython's event loop function as smoothly as Tkinter's with an > asynchronous process, i.e. is the wx.UpdateUIEvent() class analogous to > Tkinter.update(), No. It provides a totally different purpose - it's an idle event thats used to do things like ensure that menu items and toolbar buttons are kept in sync. >or are threads absoutely essential to keeping a wx GUI > updated with a long-running background process? No again. wxPython provides a Process class for executing external applications and providing events in response to input, app exit, and similar. You can also implement it in a similar way to your Tkinter implementation, but backwards - poll the pipe repeatedly using wx.CallAfter or wx.CallLater calls. From zaperaj at gmail.com Fri Jul 13 01:04:36 2007 From: zaperaj at gmail.com (zaperaj at gmail.com) Date: Thu, 12 Jul 2007 22:04:36 -0700 Subject: how to install pygame package? Message-ID: <1184303076.915138.43310@o11g2000prd.googlegroups.com> Im working in red hat linux 9.0. I've downloaded the pygame package but i dont know how to install it. If anybody has the time to detail the steps sequentially... thanx! P.S. I've downloaded both the tar and the rpm packages... From lance at augustmail.com Fri Jul 13 17:43:59 2007 From: lance at augustmail.com (Lance Hoffmeyer) Date: Fri, 13 Jul 2007 21:43:59 GMT Subject: newbie question on def, passing param's help Message-ID: Hey all, I have a def that I have been using but I realized that sometimes I need a LIST with 5 or 6 brands instead of 4 so I want to put LIST outside of the def but I can't wrap my head around a way to get LIST outside the def while still passing the same 4 parameters in the function. I'm sure there is probably a simple answer but I can't seem to think of it. Thanks in advance, Lance def attributesbyID(row,base,slideID,spreadsheet): sh = wb.Worksheets (spreadsheet) sh.Select() ############### EXCEL SECTION TO GET NUMBERS ############# LIST=((row,base,lastcol,"A13","013"),(row,base,lastcol-1,"A14","014"),(row,base,lastcol-2,"A15","015"),(row,base,lastcol-3,"A16","016"), #brand1 (row+20,base+20,lastcol,"A9","09"),(row+20,base+20,lastcol-1,"A10","010"),(row+20,base+20,lastcol-2,"A11","011"),(row+20,base+20,lastcol-3,"A12","012"),#brand2 (row+40,base+40,lastcol,"A5","05"),(row+40,base+40,lastcol-1,"A6","06" ), (row+40,base+40,lastcol-2,"A7","07" ), (row+40,base+40,lastcol-3,"A8","08" ), #brand3 (row+60,base+60,lastcol,"A1","01"),(row+60,base+60,lastcol-1,"A2","02" ), (row+60,base+60,lastcol-2,"A3","03" ), (row+60,base+60,lastcol-3,"A4","04" )) #brand4 ########################################################## ################ POWERPOINT SECTION ###################### for shape in WB.Slides.FindBySlideID(slideID).Shapes: if (shape.Type== 7): for oROW,oBASE,oCOL,oCELL,oHEADERCELL in LIST: oVALUE = sh.Cells(oROW,oCOL).Value oHEADER = sh.Cells(4,oCOL).Value + " (n=" + str(int(sh.Cells(oBASE,oCOL).Value)) + ")" PWB = WB.Slides.FindBySlideID(slideID).Shapes(shape.Name) oGraph = PWB.OLEFormat.Object oGraph.Application.datasheet.Range(oCELL).Value = oVALUE oGraph.Application.datasheet.Range(oHEADERCELL).Value = oHEADER ########################################################### del oGraph attributesbyID(14,12,31,"Attributes") # attr1 Here is what I want: LIST=((row,base,lastcol,"A13","013"),(row,base,lastcol-1,"A14","014"),(row,base,lastcol-2,"A15","015"),(row,base,lastcol-3,"A16","016"), #brand1 (row+20,base+20,lastcol,"A9","09"),(row+20,base+20,lastcol-1,"A10","010"),(row+20,base+20,lastcol-2,"A11","011"),(row+20,base+20,lastcol-3,"A12","012"),#brand2 (row+40,base+40,lastcol,"A5","05"),(row+40,base+40,lastcol-1,"A6","06" ), (row+40,base+40,lastcol-2,"A7","07" ), (row+40,base+40,lastcol-3,"A8","08" ), #brand3 (row+60,base+60,lastcol,"A1","01"),(row+60,base+60,lastcol-1,"A2","02" ), (row+60,base+60,lastcol-2,"A3","03" ), (row+60,base+60,lastcol-3,"A4","04" ), #brand4 (row+80,base+80,lastcol,"A1","01"),(row+80,base+80,lastcol-1,"A2","02" ), (row+80,base+80,lastcol-2,"A3","03" ), (row+80,base+80,lastcol-3,"A4","04" )) #brand5 def attributesbyID(row,base,slideID,spreadsheet): sh = wb.Worksheets (spreadsheet) sh.Select() ########################################################## ################ POWERPOINT SECTION ###################### for shape in WB.Slides.FindBySlideID(slideID).Shapes: if (shape.Type== 7): for oROW,oBASE,oCOL,oCELL,oHEADERCELL in LIST: oVALUE = sh.Cells(oROW,oCOL).Value oHEADER = sh.Cells(4,oCOL).Value + " (n=" + str(int(sh.Cells(oBASE,oCOL).Value)) + ")" PWB = WB.Slides.FindBySlideID(slideID).Shapes(shape.Name) oGraph = PWB.OLEFormat.Object oGraph.Application.datasheet.Range(oCELL).Value = oVALUE oGraph.Application.datasheet.Range(oHEADERCELL).Value = oHEADER ########################################################### del oGraph attributesbyID(14,12,31,"Attributes") # attr1 From jarausch at skynet.be Tue Jul 3 12:16:24 2007 From: jarausch at skynet.be (Helmut Jarausch) Date: Tue, 03 Jul 2007 18:16:24 +0200 Subject: wxPython Cannot convert from the charset 'latin-1' Message-ID: <468a7659$0$13864$ba620e4c@news.skynet.be> Hi, I'm trying to teach "dugui.py" (a tiny GUI for restructuredtext written in wxPython) to accept files in isolatin-1 encoding. It displays e.g. German umlauts correctly but then I get a popup window saying Python Error Cannot convert from the charset 'latin-1'! How can I find out where this did come from. Running it under pdb isn't helpful either. Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From electronixtar at gmail.com Mon Jul 23 05:50:17 2007 From: electronixtar at gmail.com (est) Date: Mon, 23 Jul 2007 09:50:17 -0000 Subject: set_proxy in urllib2 is driving my crazy Message-ID: <1185184217.388353.104400@z24g2000prh.googlegroups.com> A simple py script import urllib2 req=urllib2.Request("http://www.google.com") req.set_proxy("127.0.0.1:1","http") print urllib2.urlopen(req).read() Here is error: "C:\Python25\python.exe" -u "E:\Python\Crawler\test.py" Traceback (most recent call last): File "E:\Python\Crawler\test.py", line 4, in print urllib2.urlopen(req).read() File "C:\Python25\lib\urllib2.py", line 121, in urlopen return _opener.open(url, data) File "C:\Python25\lib\urllib2.py", line 374, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 392, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 353, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1101, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1076, in do_open raise URLError(err) urllib2.URLError: I built a proxy with CCproxy 6.3.2 on my own machine, and it's working absolutely all right, but how can my simple python script go wrong ? From brenNOSPAMbarn at NObrenSPAMbarn.net Sun Jul 8 14:31:03 2007 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Sun, 08 Jul 2007 18:31:03 GMT Subject: In search of python idiom for accessing arbitrary fields at run time References: <1183918901.388300.220620@o61g2000hsh.googlegroups.com> Message-ID: mshiltonj wrote: > In python, I'm doing something like this: > > def three_fields(self, field1, field2, field3): > for field in (field1, field2, field3): > value = eval('self.' + field) # this is the one I'm > interested in > [...] > > This seems to do what I expect it to do. I'm wondering if that's the > preferred or standard way to do this in python. I wasn't sure how to > tease the answer to this question out of Google. I believe you are looking for the getattr function. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From rustompmody at gmail.com Wed Jul 18 08:56:15 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Wed, 18 Jul 2007 18:26:15 +0530 Subject: Copy List In-Reply-To: <6a2ccd190707180544k4909ad3enc6a962917a26f43d@mail.gmail.com> References: <-29831789359750479@unknownmsgid> <6a2ccd190707180544k4909ad3enc6a962917a26f43d@mail.gmail.com> Message-ID: The standard idiom (I guess) is to use the slice >>> a=[1,2,3,4] >>> b=a >>> b is a True >>> b [1, 2, 3, 4] >>> c=a[:] >>> c is a False >>> c [1, 2, 3, 4] This is shallow copy If you want deep copy then from copy import deepcopy From stesch at no-spoon.de Thu Jul 26 09:16:46 2007 From: stesch at no-spoon.de (Stefan Scholl) Date: Thu, 26 Jul 2007 15:16:46 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> Message-ID: <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> Stefan Behnel wrote: > Stefan Scholl wrote: >> Well, http://docs.python.org/lib/module-xml.sax.html is missing >> the fact, that I can't use Unicode with parseString(). >> >> This parseString() uses cStringIO. > > Well, Python unicode is not a valid *byte* encoding for XML. > > lxml.etree can parse unicode, if you really want, but otherwise, you should > maybe stick to well-formed XML. The XML is well-formed. Works perfect in Python 2.4 with Python unicode and Python sax parser. This stays all inside Python. From evan at yelp.com Wed Jul 25 20:39:56 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 25 Jul 2007 17:39:56 -0700 Subject: python-fam documentation. In-Reply-To: References: <1185181629.147654.248420@r34g2000hsd.googlegroups.com> Message-ID: On 7/25/07, Evan Klitzke wrote: > On 7/23/07, Shriphani wrote: > > Folks, > > I am trying to create an app which stares at a file and when the file > > is altered, the script joins a channel on freenode and reports that > > the file has been altered. > > I found a module called python-fam, unfortunately i have been unable > > to find documentation for it. Can someone please help me ? > > Thanks, > > Shriphani Palakodety. > > If you're running a newish version of Linux; this module has fairly > complete documentation. Oops, that was supposed to be If you're running a newish version of Linux, you might try pyinotify; this module has fairly complete documentation. -- Evan Klitzke From roger.dahlstrom at gmail.com Fri Jul 13 12:02:34 2007 From: roger.dahlstrom at gmail.com (rdahlstrom) Date: Fri, 13 Jul 2007 16:02:34 -0000 Subject: Tibco Rendezvous Message-ID: <1184342554.680503.174340@r34g2000hsd.googlegroups.com> Has anyone found or written a Tibco Rendezvous (tibrv) module for Python? I've only found some really old ones with German documentation and not updated since some time around 2000. From deets at nospam.web.de Mon Jul 30 13:35:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 30 Jul 2007 19:35:10 +0200 Subject: Database objects? Persistence? Sql Server woes In-Reply-To: References: Message-ID: <5h6lqkF3ih6scU1@mid.uni-berlin.de> Mike Howarth schrieb: > I've been having a few problems with connecting to SQL Server, initially I > was using dblib however found some problems with returning text fields > whereby all text fields were ignored and it bawked at multiline sql > statements. > > Having found these major stumbling blocks I've started using pymssql which > seems less flaky. One problem I've stumbled across is that I seem to reach > my max connections on the database fairly easily (given how my script was > written) and therefore have used the singleton pattern on my database > object. > > Great problem solved, or so I thought. > > Using the following code I'm finding that the Set is now also being enforced > as a singleton as well. > > class Set(Database,Product): > > def __init__(self, *args, **kw): > > Database.__init__(self) > Product.__init__(self) > > def dosomething(self): > cu = self.c.cursor() > > Having sat back and thought about it, its easy to understand why this is > occurring given I'm indicating that Set belongs to Database and therefore > this is a singleton as well. > > Being relatively new to Python I'm unsure on how to then go about using a > database object between each class. Can anyone advise me on how they > approach this, and whether there is a common approach to this? You might consider using a ORM mapper, like SQLObject or SQLAlchemy. If they support your backend, that is. Apart from that, this might help: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302088 Store a connection per thread. Diez From yinghe.chen at jeppesen.com Tue Jul 24 06:31:42 2007 From: yinghe.chen at jeppesen.com (Yinghe Chen) Date: Tue, 24 Jul 2007 12:31:42 +0200 Subject: how to get next month string? Message-ID: Hi, Could someone help on how to use python to output the next month string like this? "AUG07", suppose now is July 2007. I think also need to consider Dec 07 case, it is supposed to output as below: "JAN07". datetime module seems not supporting the arithmatic operations, any hints? Thanks in advance, Yinghe Chen From musiccomposition at gmail.com Sat Jul 28 09:40:10 2007 From: musiccomposition at gmail.com (Benjamin) Date: Sat, 28 Jul 2007 13:40:10 -0000 Subject: Tkinter -- Show Data in an Excel like Read-Only Grid In-Reply-To: <1185573410.087935.146830@d30g2000prg.googlegroups.com> References: <1185573410.087935.146830@d30g2000prg.googlegroups.com> Message-ID: <1185630010.805799.122480@i38g2000prf.googlegroups.com> On Jul 27, 4:56 pm, beginner wrote: > Hi All, > > I am really new to Tk and Tkinter. I googled the web but it was not > mentioned how to build a data grid with Tkinter. > > Basically, I want to show an excel like data grid with fixed column > and row headers and sortable columns. But the grids can be read-only. > > Can anyone give some hint on implementing this? If tkTable isn't what you're looking for, take a look at wxPython (http://www.wxpython.org). It's a different widget set and bit of a higher learning curve than Tkinter, but it has hundreds of widgets for things like this (wx.Grid). > > Thanks, > beginner From mail at microcorp.co.za Tue Jul 17 02:08:45 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 17 Jul 2007 08:08:45 +0200 Subject: Best method for inter process communications References: <1184606522.541918.18870@22g2000hsm.googlegroups.com> Message-ID: <019a01c7c83d$1e6f0120$03000080@hendrik> "Steve Holden" wrote: > Given the radically inefficient representations that XML typically > requires, however, I think that worrying about localhost socket overhead > is unnecessary: if your application was *that* critical you wouldn't be > using XML in the first place. I heard a rumour once that a "hello world" string takes something like 10k bytes in XMLRPC - have never bothered to find out if its BS... - Hendrik From greg at cosc.canterbury.ac.nz Sat Jul 14 02:54:56 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 14 Jul 2007 18:54:56 +1200 Subject: Can I change one line in a file without rewriting the whole thing? In-Reply-To: <1184381184.772946.218220@w3g2000hsg.googlegroups.com> References: <1184381184.772946.218220@w3g2000hsg.googlegroups.com> Message-ID: <5fragoF3drm27U1@mid.individual.net> J. J. Ramsey wrote: > if I can avoid doing what amounts to reading the > whole file into memory, changing the copy in memory, and writing it > all out again. Except in very special circumstances, not really. If you do anything that makes a line longer or shorter, everything after that line in the file needs to be re-written, one way or another. If you're doing this sort of thing a lot, and need it to be faster than reading and rewriting the file, you may need to look into using a more sophisticated format on disk than a plain file. -- Greg From glen.e.mettler at lmco.com Wed Jul 18 09:02:54 2007 From: glen.e.mettler at lmco.com (meg99) Date: Wed, 18 Jul 2007 06:02:54 -0700 Subject: New guy question - user form Message-ID: <1184763774.604632.187310@j4g2000prf.googlegroups.com> I am using a scheduling sw package that uses Python as its scripting language much like Excel uses Visual Basic. I am fluent in VB but I am just beginning in Python. What I need to do is this: I need to create a user form that will contain some predefined data (captured from the scheduling sw database) and some fields that the user will enter. When the user is finished, he will write the data to the database via a command button on the form. I have looked at some of the tutorials and I have a couple of books but I don't see a user form utility like there is in VB. I am using version 1.5.2 (the sw I am using does not now support anything else). Can I do what I have described with what I have? Regards, meg99 From timr at probo.com Mon Jul 16 02:56:28 2007 From: timr at probo.com (Tim Roberts) Date: Mon, 16 Jul 2007 06:56:28 GMT Subject: 2**2**2**2**2 wrong? Bug? References: Message-ID: <0j5m939f0b9enqq2k0f9psistnu11gv2ts@4ax.com> "Jim Langston" wrote: > >Gah! Python goes right to left? Dang, I haven't seen that since APL. No, *exponentiation* in Python goes right to left, as it does in all the languages I've used that support an exponentiation operator. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From walterbyrd at iname.com Wed Jul 4 14:51:25 2007 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 04 Jul 2007 11:51:25 -0700 Subject: Does Python work with QuickBooks SDK? Message-ID: <1183575085.446434.13410@z28g2000prd.googlegroups.com> My guess is that it would, but I can find no mention of python in the intuit developers site. I can find some references to PHP and Perl, but no Python. I looks to me like Intuit develops have a strong preference for visual- basic, then c/c++, then delphi. I find it just a little bit surprising, since Python does work with .Net and all. From exarkun at divmod.com Fri Jul 20 07:01:12 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 20 Jul 2007 07:01:12 -0400 Subject: subprocess (spawned by os.system) inherits open TCP/UDP/IP port In-Reply-To: Message-ID: <20070720110112.4947.1656713081.divmod.quotient.13760@ohm> On Thu, 19 Jul 2007 21:07:55 -0500, alf wrote: > >Hi, > >I need a help with explaining following behavior. Although it is not >python issue per say, python helped me to write sample programs and >originally I encountered the issue using python software. So let's >assume we have two following programs: > > [snip - file descriptors inherited by child process] You can avoid this, if you like. Set FD_CLOEXEC on the socket after you open it, before you call os.system: old = fcntl.fcntl(s.fileno(), fcntl.F_GETFD) fcntl.fcntl(s.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC) Jean-Paul From rcdailey at gmail.com Mon Jul 9 16:46:23 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 09 Jul 2007 20:46:23 -0000 Subject: PyXML not installing? Message-ID: <1184013983.166849.32100@n2g2000hse.googlegroups.com> Hi, I downloaded the PyXML library and I'm attempting to install it by following the README file on Windows XP. I currently have Visual Studio 2005 installed. >From the command line I type: C:\PyXML-0.8.4>python setup.py build running build running build_py running build_ext error: Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py. It gives me the above error message. Any way to fix this? Thanks ahead of time. From http Mon Jul 30 19:39:21 2007 From: http (Paul Rubin) Date: 30 Jul 2007 16:39:21 -0700 Subject: What is the "functional" way of doing this? References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> <1185838434.596591.132640@d30g2000prg.googlegroups.com> Message-ID: <7x3az5wjfa.fsf@ruckus.brouhaha.com> "attn.steven.kuo at gmail.com" writes: > Recursion is common in functional programming: > > def f(n, l=None): > if l == None: > l = [] > if n > 0: > return f(n/26, l + [n%26]) > else: > return l > > print f(1000) Right, this is functional style, but quite painful in Python (no tail recursion, and look at all that list copying). From feli.hp at gmail.com Sun Jul 8 14:18:47 2007 From: feli.hp at gmail.com (feli.hp at gmail.com) Date: Sun, 08 Jul 2007 11:18:47 -0700 Subject: accessing an object instance by only having one of its attribute values Message-ID: <1183918727.033724.213010@22g2000hsm.googlegroups.com> Hello all, Imaybe someone can help me with this question. Is there a direct way of accessing an object instance, if all I know is the value of one of its attributes? The object is part of a list of objects, and I would like to pick the object directly by using this attribute value, instead of going through the list and checking if each objects attribute value is the one I am looking for. Thank you in advance From Thibault.Ketterer at gmail.com Mon Jul 23 03:55:10 2007 From: Thibault.Ketterer at gmail.com (Thibault Ketterer) Date: Mon, 23 Jul 2007 09:55:10 +0200 Subject: Get file owner in Windows Message-ID: Don't know if it's still usefull but it seems that you have to get the sid from a "give sid function" import win32security,pywintypes try: filo = win32security.GetFileSecurity(path, win32security.OWNER_SECURITY_INFORMATION) sid = filo.GetSecurityDescriptorOwner() account, domain, typecode = win32security.LookupAccountSid(None, sid) except pywintypes.error,details: account = domain = "" errcode = details[0] print "error acces:", path print domain + u'\\' + account -- Thibault ketterer From josimeon at gmail.com Sun Jul 22 13:29:37 2007 From: josimeon at gmail.com (John Simeon) Date: Sun, 22 Jul 2007 12:29:37 -0500 Subject: Compiling PythonD using DJGPP Message-ID: <46a38c61$0$16279$88260bb3@free.teranews.com> Hi there. I had an old computer at my disposal and decided to put it to use by setting up a nostalgia project with DOS and Windows for Workgroups 3.11. Now that all of you are back from laughing about the archaicness of the software involved ;-) here is my problem. PythonD is a port of python to DOS. The release used is 2.4.2. I am trying to compile PythonD using DJGPP, which is a port of GCC to DOS. 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? Thanks! -- Posted via a free Usenet account from http://www.teranews.com From goodger at python.org Tue Jul 10 23:13:06 2007 From: goodger at python.org (David Goodger) Date: Tue, 10 Jul 2007 23:13:06 -0400 Subject: PyCon Organizers' Meeting Message-ID: <46944AC2.2080206@python.org> I'd like to hold the inaugural organizers' meeting for PyCon 2008 on Tuesday, July 17, at 2PM Eastern/1PM Central/11AM Pacific (6PM UTC). Further meetings will be every other week. The meetings will be held via Google Talk/Jabber (group chat). We'll use the 'pycon' room on conference.jabber.org. Agenda: * Staff roles * Keynote speakers * PyCon tech * Chicago visit Please send any further agenda items to me, or edit the wiki page: http://wiki.python.org/moin/PyCon2008/OrganizersMeetings See you there! David Goodger PyCon 2008 Chai -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 257 bytes Desc: OpenPGP digital signature URL: From rcdailey at gmail.com Mon Jul 23 14:45:42 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Mon, 23 Jul 2007 18:45:42 -0000 Subject: Confused with csv.reader copies Message-ID: <1185216342.833408.56690@m3g2000hsh.googlegroups.com> First, take a look at my example code: ----------------------------------------------------- import csv def pass1( reader ): print reader.next() print reader.next() def pass2( reader ): print reader.next() print reader.next() reader = csv.reader( open( "C:/IT/Method/SpaceImpact/code/tools/ ProfileViewer/performance_profile.csv", "rb" ) ) pass1( reader ) pass2( reader ) ----------------------------------------------------- The output is as follows: ----------------------------------------------------- ['0', 'root', '00:01:32.793591', '1'] ['1', 'Engine::Tick', '00:00:25.886411', '1851'] ['2', 'Sprite::Tick', '00:00:00.001495', '385'] ['2', 'Entity::Tick', '00:00:00.001485', '45'] ----------------------------------------------------- I expected the output to be this: ----------------------------------------------------- ['0', 'root', '00:01:32.793591', '1'] ['1', 'Engine::Tick', '00:00:25.886411', '1851'] ['0', 'root', '00:01:32.793591', '1'] ['1', 'Engine::Tick', '00:00:25.886411', '1851'] ----------------------------------------------------- My understanding is that objects are passed by reference, meaning there is no hard copy of the data, however the copies passed to functions do not affect the version passed in. In other words, when I call "next" on the reference passed into each function, it should not affect the variable that was originally passed in. I'm attempting to use recursion to build a TreeCtrl in wxPython using this data, and I can't get it to work properly if the variable outside of the function call ends up having its state (e.g., its "next" pointer) modified by passing it into other functions. Any tips on getting this to work? I'm a native C++ programmer still learning Python, so I apologize for any confusion. Thanks. From kai.kuehne at gmail.com Wed Jul 25 21:33:20 2007 From: kai.kuehne at gmail.com (Kai Kuehne) Date: Thu, 26 Jul 2007 03:33:20 +0200 Subject: Keyword argument 'from'; invalid syntax Message-ID: Hi list! I'm using pygmalion (magnolia api access lib) and want to use the following method that it is offering: magnolia.bookmarks_find(person='user', from=some_datetime) As you may noticed, from is a keyword argument and so I get the following error message from python: File "", line 1 magnolia.bookmarks_find(person='user', from=some_datetime) ^ : invalid syntax I have tried to prepare a dict and then passing it to the method afterwards: >>> d = {'person': 'user', 'from': vorgestern} >>> magnolia.bookmarks_find(d) : bookmarks_find() takes exactly 1 argument (2 given) I'm out of ideas so help is greatly appreciated! Thanks Kai From grante at visi.com Sat Jul 7 15:35:33 2007 From: grante at visi.com (Grant Edwards) Date: Sat, 07 Jul 2007 19:35:33 -0000 Subject: Getting the home directory in Python and a bug in os.path.expanduser References: <5aQji.1085$m%.196@newssvr17.news.prodigy.net> <_MRji.11911$K9.9459@bignews6.bellsouth.net> Message-ID: <138vqo5rgt39ob7@corp.supernews.com> On 2007-07-07, Edward Diener wrote: > Thank you for responding. I hope Python will fix this problem. Python: the language that fixes itself! -- Grant Edwards grante Yow! I'm a GENIUS! I want at to dispute sentence visi.com structure with SUSAN SONTAG!! From fdu.xiaojf at gmail.com Mon Jul 16 11:04:29 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Mon, 16 Jul 2007 23:04:29 +0800 Subject: questions about functions inside a function In-Reply-To: References: Message-ID: <469B88FD.4070602@gmail.com> Duncan Booth wrote: > "fdu.xiaojf at gmail.com" wrote: > >> In order to make sure all variables be larger than 0, I tried to created >> constraint function like this: >> >> cons = [] >> for i in range(N): >> c = lambda x: x[i] - 1e-10 >> cons.append(c) >> >> But when functions in cons are evaluated, the value in all functions are >> all the same(N-1, which is the last value of i in the loop). >> >> What I want is, when functions in cons be evaluated, every function >> refers to a different variable in X. > > So pass i in as a default value: > > for i in range(N): > def c(x, i=i): > return x[i] - 1e-10 > cons.append(c) Thanks all of you have read or replied. Both Duncan's and Steven's solution work well. Thanks! I love python, not only because of the language itself, and also the so kind community! Xiao Jianfeng From ahlongxp at gmail.com Sun Jul 8 07:06:29 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Sun, 08 Jul 2007 11:06:29 -0000 Subject: socket.makefile() buggy? Message-ID: <1183892789.434028.15370@x35g2000prf.googlegroups.com> socket.makefile() may lose data when "connection reset by peer". and socket.recv() will never lose the data. change the "1" to "0" in the client code to see the difference. confirmed on both windows and linux. so I guess there is a problem with makefile(). # Echo server program import socket HOST = '' # Symbolic name meaning the local host PORT = 50007 # Arbitrary non-privileged port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((HOST, PORT)) s.listen(1) while(1): conn, addr = s.accept() print 'Connected by', addr conn.settimeout(1) toread = 99 retrytime = 0 reads = 0 while reads < toread and retrytime < 10: try: data = conn.recv(min(32,toread-reads)) if not data: continue print data reads += len(data) except: retrytime += 1 print "timeout %d" % retrytime continue #conn.shutdown(socket.SHUT_RD)#no more read if reads == toread: conn.send("OK") else: conn.send("NOT OK") conn.close() # Echo client program import socket HOST = 'localhost' # The remote host PORT = 50007 # The same port as used by the server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) for i in range(12): print "time %d" % i try: s.send('0123456789') except socket.error, e: print "socket error:", e break #data = s.recv(1024) #print "data %d" %i, data #s.shutdown(socket.SHUT_WR)#no more write ''' try changing 1 to 0. ''' if 1: data=s.recv(1024) else: rf = s.makefile("rb") data = rf.read() rf.close() s.close() print 'Received', repr(data) From deets at nospam.web.de Wed Jul 18 06:17:59 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 18 Jul 2007 12:17:59 +0200 Subject: Single-stepping through a python script References: Message-ID: <5g67mnF3e03apU1@mid.uni-berlin.de> Craig Howard wrote: > >>Craig Howard schrieb: > >> Hello All: > >> > >> Is is possible to compile a code object and single-step through its > >> execution? > > >import pdb; pdb.set_trace() > > > >Look up the pdb module documentation. > > > >Diez > > Sorry, I didn't give enough detail. Is it possible to single-step > through a > code object without using pdb? (Pdb uses the console which is not > what I want.) Well, what do you want? How do you suppose to perform any interaction with a running process if not through a window? Diez From eddie at holyrood.ed.ac.uk Tue Jul 24 14:36:24 2007 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Tue, 24 Jul 2007 18:36:24 +0000 (UTC) Subject: Can a low-level programmer learn OOP? References: <7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com> <1185204512.255392.105820@r34g2000hsd.googlegroups.com> <1185224690.523486.108680@g4g2000hsf.googlegroups.com> Message-ID: Paul McGuire writes: >On Jul 23, 12:43 pm, ed... at holyrood.ed.ac.uk (Eddie Corns) wrote: >> Paul McGuire writes: >> >On Jul 23, 5:53 am, ed... at holyrood.ed.ac.uk (Eddie Corns) wrote: >> >> Wolfgang Strobl writes: >> >> >few of James Gimple's snippets from "Algorithms in SNOBOL4" >> >> >(->http://www.snobol4.org/) as an exercise using that library might help >> >> >to get a better appreciation. Perhaps I'll try, eventually ... >> >> >> I never noticed them or the PDF of the book there before. Some Friday >> >> afternoon reading for sure. >> >> >> Personally I hope to get more to time to look at a combination of Lua and >> >> PEGs (http://en.wikipedia.org/wiki/Parsing_expression_grammar) for my parsing >> >> needs. >> >> >> Eddie >> >If you get a chance to look at pyparsing, I'd be interested in your >> >comments. The PEG page and the SNOBOL implementation have many >> >similar concepts with pyparsing (or is it the other way around?). >> >> It's on my list of things to get round to. >> >> I think what I'm really after though is a parsing DSL. I only did only one >> fairly small project in SNOBOL but I was impressed at the ease with which I >> could express the problem (some googling suggested that many end users found >> the same). I guess I want SNOBOL embedded in a modern language with scoping >> etc. Python is antithetical to (this class of) DSLs (IMHO) :( >> >> Probably what I really need is parser combinators in Haskell or maybe camlp4 >> or some such exotica but unfortunately I've never heard of them. >> >> Eddie- Hide quoted text - >> >> - Show quoted text - >I have had pyparsing users refer to pyparsing as an in-Python DSL, and >others make comparisons between pyparsing and Parsec (monadic >combinator in Haskell). I'm not sure why you would say this approach >is antithetical to Python - the builtin support for operator >overloading, __call__, __len__, __nonzero__(soon to be __bool__), >__set/getattr__, etc. permit you to impart quite a bit of expressive >behavior to your parsing classes. What I tried to do with pyparsing >was to emulate Python's builtin container classes and object instances >with the results that get returned from invoking a parser, so that the >after-parsing work would feel natural to established Python users. I don't dispute it is _a_ DSL nor even that it's a very powerful way to do parsing (in case anyone was wondering). But my intuition tells me that it ought to be possible to close the remaining gap and I'm trying to understand how that could be done and that's the bit I suspect might require a higher class of DSL (ie macros). Of course my intuition never fails but sometimes reality distorts so as to make me look wrong. The plan is to apply pyparsing to some real project and hopefully gain a better understanding. I have in mind parsing Cisco config files as a first trial. As to when I get time... You see I could just sit down and work out how to solve the problem (eg the config files) using pyparsing or whatever and move on but I'm sure you of all people know why that's not enough! >If you want to just see some existing BNF's implemented in pyparsing, >you can view them online at the pyparsing wiki. Here are some >representative examples: >http://pyparsing.wikispaces.com/space/showimage/simpleSQL.py >http://pyparsing.wikispaces.com/space/showimage/fourFn.py >http://pyparsing.wikispaces.com/space/showimage/jsonParser.py >-- Paul I appreciate the input and hopefully one day I'll be posting some questions on the wiki. Cheers, Eddie From johnmasters at oxtedonline.net Thu Jul 26 17:08:07 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Thu, 26 Jul 2007 22:08:07 +0100 Subject: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> Message-ID: <20070726210807.GB5147@spookie1.spookiegate> On 16:33 Thu 26 Jul , brad wrote: > Martha_Jones at tx.net wrote: > > 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 > > Out of the pan and into the fire. :) Welcome to the world of Ph.D's in > Computer Science. You think the Perl guys have attitude, just wait and > see what you're in for over here. I think you'll find attitudes in any > programming language... just different types. May God have mercy on your > soul! You'll be making a similar announcement in a few weeks when you > switch to Ruby :) The cold, cruel theoretical, lofty Python will > mercilessly crush you :) > > I'm just joking, OK. As a complete amateur in the world of programming (barring 25 years programming machine tools in the aerospace industry) I would like to point out that the more arcane the ['language', 'operating system', 'application'] the more unfriendly the community. Python is a revelation to me as a language that grows with the ability of the programmer, which creates a multi-level community not too centered on one-upmanship to nurture new talent. Regards, John -- War is God's way of teaching Americans geography Ambrose Bierce (1842 - 1914) From kbk at shore.net Mon Jul 9 21:33:54 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Mon, 9 Jul 2007 21:33:54 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200707100133.l6A1Xsld009031@hampton.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 392 open ( +7) / 3792 closed ( +2) / 4184 total ( +9) Bugs : 1042 open (+13) / 6757 closed (+13) / 7799 total (+26) RFE : 263 open ( +1) / 292 closed ( +1) / 555 total ( +2) New / Reopened Patches ______________________ "%d" format handling for long values (2007-06-25) http://python.org/sf/1742669 opened by Gabriel Genellina Read Write lock (2007-06-27) http://python.org/sf/1744382 opened by Yaakov Nemoy Improve exception pickling support (2007-06-27) http://python.org/sf/1744398 opened by Eric Huss Patch for feat. 713877 Expose callbackAPI in readline module (2007-06-27) http://python.org/sf/1744456 opened by strank IPv6 Interface naming/indexing functions (2007-07-02) http://python.org/sf/1746656 opened by Michael Meier Limiting data copy in xmlrpclib (2007-07-04) http://python.org/sf/1747670 opened by Gael Le Mignot Extra optional argument to os.path.expandvars (2007-07-06) http://python.org/sf/1748960 opened by Geoffrey Bache New byte packing format for the struct module (2007-07-07) http://python.org/sf/1749662 opened by Robert Zeh itertools.getitem() (2007-07-08) http://python.org/sf/1749857 opened by Walter D?rwald Patches Closed ______________ Fix for duplicate "preferences" menu-OS X (2007-04-03) http://python.org/sf/1693258 closed by ronaldoussoren Mac OS X: libtool (2007-03-03) http://python.org/sf/1673122 closed by ronaldoussoren New / Reopened Bugs ___________________ Incorrect docs for optparse OptionParser add_help_option (2007-06-23) http://python.org/sf/1742164 opened by Forest Wilkinson ZipFile.writestr writes incorrect extended local headers (2007-06-23) http://python.org/sf/1742205 opened by alexis Documentation for BaseHTTPServer.HTTPServer (2007-06-25) http://python.org/sf/1742837 opened by Brandon Mintern Pickling of exceptions broken (2007-06-25) http://python.org/sf/1742889 opened by Jim Fulton shlex handles 'None' poorly (2007-06-25) CLOSED http://python.org/sf/1742901 opened by Seth Vidal can't run single lamba funcs as unittest (2007-06-25) http://python.org/sf/1742940 opened by timmeh conditional expressions vs. () and * in call arguments. (2007-06-26) CLOSED http://python.org/sf/1743665 opened by Mike Meyer Some incorrect national characters (Polish) in unicodedata (2007-06-26) CLOSED http://python.org/sf/1743795 opened by admindomeny Examples dropped from PDF version of docs (2007-06-26) http://python.org/sf/1743846 opened by Terry Carroll cvs.get_dialect() return a class object (2007-06-28) http://python.org/sf/1744580 opened by Christian Kristukat Newline skipped in "for line in file" (2007-06-28) http://python.org/sf/1744752 opened by Rune Devik DoS smtpd vulnerability (2007-06-28) http://python.org/sf/1745035 opened by billiejoex 2.5.1 curses panel segfault in new_panel on aix 5.3 (2007-06-29) http://python.org/sf/1745108 opened by Mattias Wadenstein pdtri gives wrong results (2007-06-29) CLOSED http://python.org/sf/1745178 opened by Nikke Knatterton Filename providing cross platform capability (2007-06-29) CLOSED http://python.org/sf/1745533 reopened by loewis Filename providing cross platform capability (2007-06-29) CLOSED http://python.org/sf/1745533 opened by Damian Bad attributes/data handling in SGMLib (2007-06-30) http://python.org/sf/1745761 opened by Alvaro Lopez class mutex doesn't do anything atomically (2007-07-01) http://python.org/sf/1746071 opened by David Benbennick long.__str__ is quadratic time (2007-07-01) http://python.org/sf/1746088 opened by David Benbennick AMD64 installer does not place python25.dll in system dir (2007-07-02) http://python.org/sf/1746880 opened by Roger Upole chown broken on 64bit (2007-07-04) http://python.org/sf/1747858 opened by Neal D. Becker Module-level stack scopes have incorrect bindings. (2007-07-04) http://python.org/sf/1748015 opened by Nefarious CodeMonkey, Jr. inspect.getargspec fails on built-in or slot wrapper methods (2007-07-04) http://python.org/sf/1748064 opened by Michael A. Hawker str.join() intercepts UnicodeDecodeError raised by iterator (2007-07-05) CLOSED http://python.org/sf/1748292 opened by Christoph Zwerschke imaplib cannot handle mailboxes with ACL: lrs (2007-07-07) http://python.org/sf/1749512 opened by Florian Friesdorf PLATFORM macro in PC/pyconfig.h already defined by Apache (2007-07-07) http://python.org/sf/1749567 opened by Adal Chiriliuc expanduser("~") on Windows looks for HOME first (2007-07-07) http://python.org/sf/1749583 opened by Edward Diener os.getlogin should use the DISPLAY and not the tty (2007-07-08) http://python.org/sf/1750013 opened by Serge Noiraud Python 2.5+ skips while statements in debuggers (2007-07-08) http://python.org/sf/1750076 opened by Chris Lasher Bugs Closed ___________ Odd UDP problems in socket library (2007-06-22) http://python.org/sf/1741898 deleted by bluej774 shlex handles 'None' poorly (2007-06-25) http://python.org/sf/1742901 closed by gbrandl python: Modules/gcmodule.c:240: update_refs: Assertion `gc-> (2007-06-20) http://python.org/sf/1740599 closed by stuffduff shutil.move doesn't work when only case changes (2007-06-16) http://python.org/sf/1738441 closed by ggambett conditional expressions vs. () and * in call arguments. (2007-06-26) http://python.org/sf/1743665 closed by gbrandl Some incorrect national characters (Polish) in unicodedata (2007-06-26) http://python.org/sf/1743795 closed by loewis pdtri gives wrong results (2007-06-29) http://python.org/sf/1745178 closed by gbrandl Filename providing cross platform capability (2007-06-29) http://python.org/sf/1745533 closed by loewis Filename providing cross platform capability (2007-06-29) http://python.org/sf/1745533 closed by atagar str.join() intercepts UnicodeDecodeError raised by iterator (2007-07-05) http://python.org/sf/1748292 closed by lemburg Tkinter is not working on trunk (2.6) (2007-06-09) http://python.org/sf/1733943 closed by kbk logging module formatter problem with %(filename)s (2006-06-19) http://python.org/sf/1508369 closed by ronaldoussoren Mac Universal Build of Python confuses distutils (2006-07-28) http://python.org/sf/1530142 closed by ronaldoussoren Mac build fails if not building universal due to libtool (2007-06-12) http://python.org/sf/1736103 closed by jackjansen Status bar on OSX garbled (2007-01-04) http://python.org/sf/1627543 closed by ronaldoussoren New / Reopened RFE __________________ please add wsgi to SimpleXMLRPCServer (2007-06-30) http://python.org/sf/1745722 opened by Helmut Grohne RFE Closed __________ MacPython ignores user-installed Tcl/Tk (2006-09-21) http://python.org/sf/1563046 closed by ronaldoussoren From see_website at mindprod.com.invalid Sun Jul 1 11:37:44 2007 From: see_website at mindprod.com.invalid (Roedy Green) Date: Sun, 01 Jul 2007 15:37:44 GMT Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> Message-ID: On Tue, 26 Jun 2007 13:04:50 +0100, Martin Gregorie wrote, quoted or indirectly quoted someone who said : >TAI? Care to provide a reference? see http://mindprod.com/jgloss/tai.html -- Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Jul 18 09:29:21 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 18 Jul 2007 15:29:21 +0200 Subject: Discover instance variables References: <1184606748.599294.293570@n60g2000hse.googlegroups.com> <1184618541.269717.30580@n2g2000hse.googlegroups.com> Message-ID: <5g6ithF35grihU1@mid.individual.net> JonathanB wrote: > So given that example, is there a clean way to get this output: > > Data for Earth: > Name = Earth > WTN = 5.0 > Ag = 0 > Na = 0 > ... > ... > Notes = None Sure, save the __init__ parameters explicitly in a dict. self.data = {"Name": name, "WTN": WTN, "Ag": Ag, ... } To display them, you can iterate through the dict: print "Data for Earth:" for field, content in self.data.items(): print "%s = %r" % field, content Hope that helps. Regards, Bj?rn -- BOFH excuse #188: ..disk or the processor is on fire. From daniel at zelisko.net Tue Jul 3 13:58:34 2007 From: daniel at zelisko.net (Drex) Date: Tue, 03 Jul 2007 10:58:34 -0700 Subject: how to send files via bluetooth with python to a mobile In-Reply-To: <1183357391.239520.220490@q69g2000hsb.googlegroups.com> References: <1183294323.556314.293860@m36g2000hse.googlegroups.com> <1183305873.736724.116680@c77g2000hse.googlegroups.com> <1183306850.712226.313800@m36g2000hse.googlegroups.com> <1183310919.771396.268760@q69g2000hsb.googlegroups.com> <5eq94iF3a5b8bU1@mid.uni-berlin.de> <46880a0b$0$37195$4fafbaef@reader3.news.tin.it> <5eqg94F39cdomU1@mid.uni-berlin.de> <1183357391.239520.220490@q69g2000hsb.googlegroups.com> Message-ID: <1183485514.510961.128610@i13g2000prf.googlegroups.com> Hi, I tried the example from the site http://dev.zuckschwerdt.org/openobex/wiki/ObexFtpExampleClientPython but I am getting the following error: /home/daniel/projekty/_moje/python/send_txt_to_mobile.py Traceback (most recent call last): File "/home/daniel/projekty/_moje/python/send_txt_to_mobile.py", line 5, in devs = cli.discover(); File "/usr/local/lib/python2.5/site-packages/obexftp/__init__.py", line 37, in __getattr__ = lambda self, name: _swig_getattr(self, client, name) File "/usr/local/lib/python2.5/site-packages/obexftp/__init__.py", line 21, in _swig_getattr raise AttributeError,name AttributeError: discover on this line: devs = cli.discover() any idea what might cause it? thanks in advance dz From bdesth.quelquechose at free.quelquepart.fr Sun Jul 22 19:01:11 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 23 Jul 2007 01:01:11 +0200 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185473668.099991.240670@19g2000hsx.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> <46a7b908$0$32130$426a34cc@news.free.fr> <1185453726.559470.122480@x40g2000prg.googlegroups.com> <1185473668.099991.240670@19g2000hsx.googlegroups.com> Message-ID: <46a8fdc1$0$4193$426a74cc@news.free.fr> SamFeltus a ?crit : > PHP is just a more inclusive community. The PHP community is more > concerned with the casual user and the end user. This is PHP's core > strength, and one of Python's core weaknesses. The Python community > would be wise to adopt PHP's concern for the end user. This assertion is at least debatable. It's true that Python is not as easy to get started withn as it was some 7 years ago, and it's true that some of use here are probably paying less and less attention to FAQs - but what, they are FAQs, so it should be easy to find some answers. Still, this NG and the overall Python community are amongst the most tolerant and newbie-friendly around. Even some of the greatest masters here are spending time answering to 101 questions on a regular basis. > That being said, I don't think you will find PHP easier than Python. > I think the reverse is true, except in the simplest cases. Mmm... I certainly do find python easier, but I'm obviously biased since I had time to learn it and know most of the gotchas. The problem might be very different for newcomers, specially for the 'programming-illiterate' ones. I surely spend less time checking the doc with Python than with PHP - thanks to good design, good naming, consistency, REPL and in the worst interactive doc, all things missing in PHP. OTHO, PHP is so basically braindead that it doesn't requires anyone to be able to cope with the higher-level abstractions that make Python so powerful. From naga86 at gmail.com Tue Jul 31 00:57:17 2007 From: naga86 at gmail.com (Nagarajan) Date: Mon, 30 Jul 2007 21:57:17 -0700 Subject: Reading a two-column file into an array? In-Reply-To: References: Message-ID: <1185857837.610635.206270@e9g2000prf.googlegroups.com> On Jul 31, 9:03 am, Gilles Ganault wrote: > Hello > > I'm sure there's a much easier way to read a two-column, CSV file into > an array, but I haven't found it in Google. > > Should I use the Array module instead? > > ========= > a = [] > i = 0 > > #itemitem > p = re.compile("^(.+)\t(.+)$") > > for line in textlines: > m = p.search(line) > if m: > a[i,0] = m.group(1) > a[i,1] = m.group(2) > i = i + 1 > > for i in a.count: > for j in 2: > print a[i,j] > ======= > > Thank you. a = [] import csv reader = csv.reader(open("filename", "r"), delimiter='\t' ) for row in reader: a.append( row ) ---------------------------- I don't think you can have multidimensional arrays. Did you test you program? It did not work for me. I think mine would suit your requirements as the output is a list of lists. From surkumarm at gmail.com Wed Jul 25 11:46:10 2007 From: surkumarm at gmail.com (Sachin) Date: Wed, 25 Jul 2007 15:46:10 -0000 Subject: This One is ULTIMATE. (Dont' Miss) Message-ID: <1185378370.231394.31010@l70g2000hse.googlegroups.com> Hi Everyone, http://surkumarm.googlepages.com/home I found a cool Websites which can be a great resource to making easy money for Home Moms, kids, Students and other people who are looking for making some easy Money Online. This website talks about programmes launched by Giant companies like Amazon, Google and E-bay etc. and there is no participatioin fee. It provides great information about how you can make great money Online. Of course it won't come in the first day but as you start understanding how these programmes work, the potential for money making will be limitless. Here is the link and it has changed my life. I hope it does the same for you. :) http://surkumarm.googlepages.com/home From andre.roberge at gmail.com Mon Jul 30 08:53:36 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Mon, 30 Jul 2007 12:53:36 -0000 Subject: Detecting __future__ features In-Reply-To: References: Message-ID: <1185800016.950517.43240@g4g2000hsf.googlegroups.com> On Jul 30, 9:39 am, Neil Cerutti wrote: > On 2007-07-30, Steven D'Aprano > > wrote: > > How would one tell at runtime if a particular feature has been > > enabled by the "from __future__ import thing" statement? > > I don't understand the qualification, "at runtime," you're > making. What's wrong with just importing what you want and using > it? If it's already been enabled, no harm will come from the > import statement. > I'm not the OP, so perhaps I am missing his intent. However, I can see a good reason for asking this question. I seem to recall that the "from __future__ import" statement can only be done at the beginning of a script. What if you are designing a module meant to be imported, and used by other programs over which you have no control? You can't use "from __future__ import" in your module. So, you may have to find a way to figure out what's been done. (the example given with the division operator is a good one). Andr? > -- > Neil Cerutti > Will the highways on the Internet become more few? --George W. Bush From gagsl-py2 at yahoo.com.ar Wed Jul 25 15:48:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 25 Jul 2007 16:48:05 -0300 Subject: adding a docstring to an instancemethod References: <1185361537.733690.238280@k79g2000hse.googlegroups.com> Message-ID: En Wed, 25 Jul 2007 08:05:37 -0300, jelle escribi?: > I'm working on documenting wrapped C++ methods. > The thing is that I'd like to add docstrings to a method, but python > won't allow me to: > TypeError: attribute '__doc__' of 'instancemethod' objects is not > writable Set the __doc__ on the *function* from which you build the instance method. -- Gabriel Genellina From donn at u.washington.edu Wed Jul 11 19:09:02 2007 From: donn at u.washington.edu (Donn Cave) Date: Wed, 11 Jul 2007 16:09:02 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: In article , Steve Holden wrote: > Paul Rubin wrote: > > Steven D'Aprano writes: > >> As far as I can see, the only difference is that the list comp variable > >> isn't explicitly created with a statement of the form "name = value". Why > >> is that a problem? > > > > I don't know that listcomp vars are worse problem than other vars; > > however there is an easy workaround for the listcomp vars so I use it. > > If there was a way to restrict the scope of other local vars (I gave > > examples from other languages of how this can be done), I'd use that too. Someday we will look at "variables" like we look at goto. > Maybe we just have different styles, and I naturally tend to write in > smaller scopes than you do. I've wondered if programmers might differ a lot in how much they dread errors, or how they react to different kinds of errors. For example, do you feel a pang of remorse when your program dies with a traceback - I mean, what a horrible way to die? Do you resent the compiler's reprimands about your code errors, or nagging about warnings? Maybe the language implementation's job has as much to do with working around our feelings as anything else. Donn Cave, donn at u.washington.edu From timid.Gentoo at gmail.com Thu Jul 5 15:40:45 2007 From: timid.Gentoo at gmail.com (_spitFIRE) Date: Thu, 05 Jul 2007 19:40:45 -0000 Subject: SMTP server w/o using Twisted framework In-Reply-To: References: <1183661809.613856.312100@57g2000hsv.googlegroups.com> Message-ID: <1183664445.020890.226520@c77g2000hse.googlegroups.com> On Jul 5, 2:21 pm, Jean-Paul Calderone wrote: > You need to do a DNS MX lookup. There's nothing in the Python stdlib > which provides this functionality. There are several libraries available > which do this, though (Twisted among them ;). You can probably find them > with a little googling. Beyond that, the rules for processing MX records > are simple and it's not much work to pick the right host once you can do > the MX lookups. > > Jean-Paul Thanks for the pointer. However, as I said currently, I can't use anything other than the standard libraries. From josiah.carlson at sbcglobal.net Fri Jul 6 01:19:39 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Thu, 05 Jul 2007 22:19:39 -0700 Subject: Interfacing python program to C++ program instance In-Reply-To: <_Dhji.1190$Jw2.323@newsfe04.lga> References: <_Dhji.1190$Jw2.323@newsfe04.lga> Message-ID: Jim Langston wrote: > Windows. Situation: Using a Python program called OpenRPG. I have a program > that displays form data (a character sheet) in C++. I am able in the C++ > program to build a string and copy it into the clipboard, then paste it into > the input in the running Python program. If I remember correctly, OpenRPG uses wxPython for it's GUI. wxPython offers fairly easy access to the clipboard contents, so it could check the clipboard for the kind of data it wants. > I would like to somehow automate this, that is, have the python instance > communicate with the C++ instance and vice versa. I'm still trying to think > of a way to do this. There seems to be a number of options, but I'm not > sure which one is best, or there is a better one. > > 1. Write a new C++ program/library with extern C that Python could call. > This interface program would open up some shared memory that the C++ > application would also open up, and python and C++ could communicate that > way. Python writing requests to the memory, C++ responding with responses. mmap is the standard "shared memory communication" mechanism available on pretty much all platforms of note (Windows, Linux, OSX, BSD, Solaris, BeOS, etc.) > 2. Have the C++ program interface directly into the python form, reading > directly from controls. C++ could write to the input box with reponses. If OpenRPG uses any custom controls (which are very easy to write with wxPython), this won't be easy. Also, controlling an application that wasn't designed for such control can be a beast. > 3. Have Python write a small file with the request to the HD. Have the C++ > program intermittedly check for the presense of this file. If it exists, it > would open the file, read the request, write a response file, then delete > the file Python wrote. This can work, but is unnecessary. See mmap, socket, etc. > 4. Find out if python can directly, somehow, open up shared memory and do > the same as 1 without the need for the extern C interface program. import mmap > 5. Something else I'm not thinking of but you know. sockets. In particular, XML-RPC for the call/return using structured data in XML format. There exists XML-RPC server and client libraries in Python, and XML-RPC server and client libraries exist for just about every language worth discussing. Alternatively, you can pass your queries/string directly via sockets (rather than the clipboard). - Josiah From ervinramonllari at gmail.com Fri Jul 20 12:51:27 2007 From: ervinramonllari at gmail.com (ervin ramonllari) Date: Fri, 20 Jul 2007 18:51:27 +0200 Subject: Data type conversion Message-ID: <9f2909fa0707200951s6edc9b6m173e02290a4cb18a@mail.gmail.com> Thank you very much, It was a very helpful tool -------------- next part -------------- An HTML attachment was scrubbed... URL: From ninja.krmenadl at nes.com Wed Jul 4 16:47:43 2007 From: ninja.krmenadl at nes.com (Boris Ozegovic) Date: Wed, 4 Jul 2007 22:47:43 +0200 Subject: AIML, Python, Java Message-ID: Hi I have a chatterbot written in AIML. I am using PyAIML, and HTTP server as a mediator between user and PyAIML. Server calls PyAIML, and sends the result string to the sensor network which is written in Java; and in the end, server returns value from Java method. Can I somehow call Java methods inside Python code, or I must use Jython? Can I use PyAIML in Jython? -- Ne dajte da nas la?ljivac Bandi? truje: http://cnn.blog.hr/arhiva-2007-06.html#1622776372 From mail at microcorp.co.za Tue Jul 17 02:22:51 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 17 Jul 2007 08:22:51 +0200 Subject: Can a low-level programmer learn OOP? References: <469bce45$0$14054$426a74cc@news.free.fr> Message-ID: <019b01c7c83d$1f0db220$03000080@hendrik> "Bruno Desthuilliers" wrote: >My my my... Would you believe that my coworkers do consider me like an >old sage because I started programming in 1990 with HyperTalk on Mac >Classic !-) > >I suddenly feel 20 again ! Woo !-) *hands him a straw boater and a cane* ok youngster - lets see you strut your stuff... ; - ) From infocat at earthlink.net Tue Jul 3 22:49:10 2007 From: infocat at earthlink.net (Frank Swarbrick) Date: Tue, 03 Jul 2007 20:49:10 -0600 Subject: ActivePython Message-ID: <5f0g54F396io7U1@mid.individual.net> Why might one choose to use ActivePython instead of using the free CPython? From carsten at uniqsys.com Wed Jul 25 14:40:27 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 25 Jul 2007 14:40:27 -0400 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185385374.866372.198520@x35g2000prf.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> Message-ID: <1185388827.4432.34.camel@dot.uniqsys.com> On Wed, 2007-07-25 at 10:42 -0700, walterbyrd wrote: > "Once you start down the Dark path, forever will it dominate your > desiny. Consume you, it will." > - Yoda > > I'm fairly new to web-development, and I'm trying out different > technologies. Some people wonder why PHP is so popular, when the > language is flawed in so many ways. To me, it's obvious: it's because > it's much easier to get started with PHP, and once somebody gets > started with a particular language, that person is likely to stay with > that language. That's a major reason, yes. > Before you can even get started with Python web-development, you have > to understand this entire alphabit soup of: CGI, FASTCGI, MOD_PYTHON, > FLUP, WSGI, PASTE, etc. For me, configuring fastcgi has been the most > difficult part of getting django to work. PHP developers don't have to > bother with anything like that. With PHP, you just throw some code in > the middle of your html file. I agree that there is a confusing number of choices, but you don't have to understand them all to get started. You just need a pointer in the right direction. If you like PHP's way of plopping code into your HTML, take a look at mod_python.psp. If you want to keep your logic and your presentation separate, go with CherryPy and basically any template language you like. > Also, PHP, and PHP frameworks, are supported everywhere. If you going > to use a PHP MVC framework, like codeignitor, you would have a hard > time finding a hoster that didn't support it - all you need is php4 > and mysql. Dollar-hosting, for $10 a year, should work just fine with > codeignitor. With codeignitor, just copy your files to whatever host, > and that's it, you're done. > > By contrast, the most popular Python frameworks have sky-high system > requirements. Take a look at the requirements and/or recomendations > for popular Python frameworks like Django, TurboGears, or CherryPy: > Apache 2.0, mod_python (latest version), fastcgi (at least), command > line access, PostgreSQL. And a lot of low-cost hosters don't support > Python at all. The comparison is not fair on many levels. PHP is not a framework like Django or TG. You get a lot more stuff with Django or TG, so of course the requirements are higher. Seriously, take a closer look at CherryPy. With CherryPy, you don't even need Apache since it provides its own web server. The hosting problem is a vicious cycle. PHP hosting is easier to find because PHP is more popular, and PHP is more popular (partly) because hosting is easier to find. > Don't get me wrong: I am not saying that PHP is better than Python for > web-development. But, I sometimes think that Python could learn a few > things from PHP. What exactly could Python learn from PHP? PHP is a one-trick pony. It was designed for web applications. People claim they write desktop applications in PHP, but I don't believe them. Python is more powerful and offers a lot more choices. In order for Python to become more like PHP, somebody would have to make One True Way of developing web applications in Python, and that's never going to happen. Just my two cents, -- Carsten Haese http://informixdb.sourceforge.net From exarkun at divmod.com Thu Jul 19 10:13:47 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 19 Jul 2007 10:13:47 -0400 Subject: How do you debug when a unittest.TestCase fails? In-Reply-To: <32e43bb70707190625u4fba3fafg45d7856556ea1844@mail.gmail.com> Message-ID: <20070719141347.4947.884519103.divmod.quotient.13389@ohm> On Thu, 19 Jul 2007 09:25:50 -0400, "Emin.shopper Martinian.shopper" wrote: >After poking around the unittest source code, the best solution I could come >up with was to do >>>>import unittest; unittest.TestCase.run = lambda self,*args,**kw: >unittest.TestCase.debug(self) > >before running my tests. That patches things so that I can use pdb.pm() when >a test fails. Still, that seems like an ugly hack and I would think there is >a better solution... trial: http://twistedmatrix.com/trac/wiki/TwistedTrial It's distributed with Twisted: http://twistedmatrix.com/trac/wiki/Downloads I don't use unittest directly very much. I'm only slightly surprised that it is doing something which breaks post-morteming. If you want, you could probably fix it (probably something related to how it handles exceptions from test methods) and contribute a patch to Python. Jean-Paul From deets at nospam.web.de Tue Jul 31 18:04:02 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 01 Aug 2007 00:04:02 +0200 Subject: (May be OT) developing in jython, using in java? In-Reply-To: References: Message-ID: <5h9puqF3j6grcU1@mid.uni-berlin.de> Gerardo Herzig schrieb: > Hi all. I dont know if this is the right place for asking this, but > maybe some of you know where i must go. > The thing is: > > Im writing a very simple class (in python) to access some LDAP server. A > companion will access to the same LDAP server too, but his developing in > java. So i said "ok, wait, i dont think we have to make the exact same > thing twice! Let me see if jython can help us"....I can find (after a > quick review) an answer to this: "Can i, using jython, make a package so > my companion can import that package as a webservice??" > > As im farly new in python, *very* new at Java, and *even newer* at > jython, my brain just said to me "ok, i dont know, i want a beer", so > maybe some of you can gide me to where i must go in order to clarify my > ideas. There is a jython mailing list, which is probably a better place to ask jython-related questions. The problem is that jython essentially brings the syntax of python to the library of Java, plus it tries to wrap as much Python libs using the corresponding Java-libs. But there are gaping holes in that effort due to lacks of the JDK - think of e.g. posix functionalities. And while accessing Java from Jython is a piece of cake, the other way round isn't so easy. For you actual problem I'd say: it's the wrong way - because if you need your LDAP-class from CPython, you won't be able to help the Java-guy, because the libraries for accessing LDAP in Java differ from the one in CPython, and making the Jython class accessible from Java isn't worth the effort. diez From the.mindstorm.mailinglist at gmail.com Mon Jul 9 12:23:00 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Mon, 09 Jul 2007 09:23:00 -0700 Subject: Tool for finding external dependencies In-Reply-To: <1183995767.335243.197190@i38g2000prf.googlegroups.com> References: <1183945183.147231.120180@z28g2000prd.googlegroups.com> <1183990671.337753.106370@k79g2000hse.googlegroups.com> <1183991251.354349.326520@e16g2000pri.googlegroups.com> <1183992896.381070.62280@n60g2000hse.googlegroups.com> <1183995767.335243.197190@i38g2000prf.googlegroups.com> Message-ID: <1183998180.347827.325100@n60g2000hse.googlegroups.com> On Jul 9, 6:42 pm, Rob Cakebread wrote: > On Jul 9, 7:54 am, kyoso... at gmail.com wrote: > > > > > > > mod = modulefinder.ModuleFinder() > > mod.run_script(path/to/python_script.py) > > mod.report() > > > > > > Mike > > Nope. All of those tools and the code above show *all* imports/ > dependencies, which is way too much information. I just need the > 'external' dependencies, like in the example from pylint I pasted > above. If nothing exists I'll just have to figure out how pylint does > it. > Isn't it possible to get from modulefinder what it has found and just filter it out according to your rules? This way you are in control and can deicde what is internal/external. ./alex -- .w( the_mindstorm )p. > I'm working on g-pypi which creates ebuilds for Gentoo Linux. For > packages that use setuptools I can get the dependencies easily enough > because of 'install_requires', but for packages that don't, I need > another way to find them. > > Thanks, > Rob From a.schmolck at gmail.com Wed Jul 11 15:05:09 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Wed, 11 Jul 2007 20:05:09 +0100 Subject: Tuple vs List: Whats the difference? References: <1184177195.569916.184770@22g2000hsm.googlegroups.com> Message-ID: Shafik writes: > Hello folks, > > I am an experienced programmer, but very new to python (2 days). I > wanted to ask: what exactly is the difference between a tuple and a > list? I'm sure there are some, but I can't seem to find a situation > where I can use one but not the other. Try mutating the tuple or using the list as a hashkey. 'as From shabda.raaj at gmail.com Mon Jul 16 08:10:01 2007 From: shabda.raaj at gmail.com (shabda raaj) Date: Mon, 16 Jul 2007 17:40:01 +0530 Subject: Implementaion of random.shuffle Message-ID: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> I was going through the docs for module-random And I came through this, *shuffle*( x[, random]) Shuffle the sequence x in place. The optional argument random is a 0-argument function returning a random float in [0.0, 1.0); by default, this is the function random(). Note that for even rather small len(x), the total number of permutations of x is larger than the period of most random number generators; this implies that most permutations of a long sequence can never be generated. Why would we need to generate the total number of permutations for the list while trying to shuffle it? Should not we just use a knuth shufflewhich does not require us to generate the total number of permutations. As long as len(x) is smaller than period of random number generator, a permutation can be generated. A quick first draft of implemetation might be, import random def shuffle(list_): for i in range(len(list_)): j = random.randint(i, len(list_)-1) list_[i], list_[j] = list_[j], list_[i] if __name__ == '__main__': a = range(100) shuffle(a) print a This is my first post to the list, I am not sure if this is the correct place to ask these questions. Please advise if this is not the correct place. --Shabda -------------- next part -------------- An HTML attachment was scrubbed... URL: From memracom at yahoo.com Sun Jul 22 16:52:54 2007 From: memracom at yahoo.com (memracom at yahoo.com) Date: Sun, 22 Jul 2007 13:52:54 -0700 Subject: CSV without first line? In-Reply-To: References: Message-ID: <1185137574.183261.58930@n60g2000hse.googlegroups.com> On 15 Jul, 04:30, "Sebastian Bassi" wrote: > Hi, > > In my CSV file, the first line has the name of the variables. So the > data I want to parse resides from line 2 up to the end. Here is what I > do: > > import csv > lines=csv.reader(open("MYFILE")) > lines.next() #this is just to avoid the first line > for line in lines: > DATA PARSING > > This works fine. But I don't like to do "lines.next()" just to get rid > of the first line. So I wonder if the reader function on the csv > module has something that could let me parse the file from the second > line (w/o doing that lines.next()). There is nothing better than the way you are doing it now. Your code is explicit so that everyone reading it can see that you skip exactly one line at the beginning. Imagine that one day someone presents you with a CSV file containing two header rows? You can easily handle this by writing: lines.next() # and skip the second line too but any other magic method that you can find, might not work. From steve at REMOVE.THIS.cybersource.com.au Mon Jul 9 19:35:57 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 10 Jul 2007 09:35:57 +1000 Subject: Comparing modified elements in Sets References: <1184011034.839268.116730@r34g2000hsd.googlegroups.com> Message-ID: On Mon, 09 Jul 2007 19:57:14 +0000, ChrisEdgemon wrote: > I've got a set with contents like: [filename1.mp3, filename2.mp3, > filename3.mp3, ...] > I've got another set with contents like [filename1.ogg, > filename3.ogg, ...] > And another set with contents like [filename1, filename 2, ...] > > I'd like to be able to compare set 1 with set 2 and have it match > filename1 and filename3, or compare set 1 with 3 and get back > filename1, filename2. etc. > > Is there a way for me to do this inside the compare function, rather > than having to make duplicate copies of each set? What compare function are you talking about? Unless you have truly astronomical numbers of unique filenames (and remember that what's big to you is probably not big to Python), the easiest way is to make a copy of each set with the file extensions stripped off the file names. Use os.path.splitext() for that. -- Steven. From musiccomposition at gmail.com Wed Jul 18 12:38:38 2007 From: musiccomposition at gmail.com (Benjamin) Date: Wed, 18 Jul 2007 09:38:38 -0700 Subject: wxPython, searching, and threads Message-ID: <1184776718.313539.92360@z28g2000prd.googlegroups.com> Hello! I am writing a search engine with wxPython as the GUI. As the search thread returns items, it adds them to a Queue which is picked up by the main GUI thread calling itself recursively with wx.CallAfter. These are then added to a ListCtrl. This works fine for small searches, but with larger and longer searchs the GUI is clogged and won't respond. I suspect (I may be wrong) that there are so many results being sent to the ListCtrl that the event loop doesn't have time to respond to events. I've tried buffering the results before sending them to the GIU, but that doesn't help at all. Please advise. From james.harris.1 at googlemail.com Thu Jul 5 16:07:55 2007 From: james.harris.1 at googlemail.com (James Harris) Date: Thu, 05 Jul 2007 13:07:55 -0700 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: <1183666075.705846.283660@c77g2000hse.googlegroups.com> On 5 Jul, 08:46, Dennis Lee Bieber wrote: > On Wed, 04 Jul 2007 22:12:46 -0400, Roy Smith declaimed > the following in comp.lang.python: > > > Astronomers use Julian Date (http://en.wikipedia.org/wiki/Julian_date) for > > calculations like this. It's a widely used format and highly portable. > > I'm sure there are libraries to deal with it in all the languages you > > mention (and more). Ask on sci.astro for more information. > > But do you also need to account for > Besselian or Julian centuries (Astronomy used to use B1900 as a > computational epoch, but now uses J2000. A Julian century is 36525 days, > Besselian century was 36524.22 days. Whew! It was for reasons such as this that I suggested treating a day (i.e. a /nominal/ 24-hour period) as the primary unit. The Gregorian switch to Julian, for example, missed out a bunch of days to adjust the calendars of Christendom but they had to be whole numbers of days. In terms of real people (about the level I need) once a dividing line has been chosen between one day and the next it becomes a reference point. Incidentally I have chosen to store /average/ values in the application so if the sample period is 10 seconds and the count increases by 45 I will store 4.5. This is plottable directly and I could even allow an 11 second sample when a leap second is added (if I needed that detail). Is your Julian century a bit long, on average, 2000, 2400, 2800 etc having 28 days in Feb? From this at is.invalid Tue Jul 17 14:11:27 2007 From: this at is.invalid (ddtl) Date: Tue, 17 Jul 2007 21:11:27 +0300 Subject: Interpreting non-ascii characters. Message-ID: Hello everybody, I want to create a script which reads files in a current directory and renames them according to some scheme. The file names are in Russian - sometimes the names encoded as win-1251, sometimes as koi8-r etc. I want to read in file name and convert it to list for further processing. The problem is that Python treats non-ascii characters as multibyte characters - for example, hex code for "Small Character A" in koi8-r is 0xc1, but Python interprets it as a sequence of \xd0, \xb1 bytes. What can I do so that Python interprets non-ascii characters correctly? From bignose+hates-spam at benfinney.id.au Wed Jul 25 22:53:36 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Jul 2007 12:53:36 +1000 Subject: idiom for RE matching References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> <1185157313.356112.159020@z24g2000prh.googlegroups.com> <2f6dnUlUxd2_7TjbnZ2dnUVZ_qy3nZ2d@comcast.com> Message-ID: <87hcnrj2of.fsf@benfinney.id.au> Gordon Airporte writes: > The actual code uses the proper 'if foo in line or if bar in line:' > form. >>> line = "spam eggs ham" >>> foo = "spam" >>> bar = "sausage" >>> if foo in line or if bar in line: File "", line 1 if foo in line or if bar in line: ^ SyntaxError: invalid syntax Not that I want to pick on you; I just don't want something wrong labelled as "proper" to go unchallenged in the archives :-) -- \ "Never do anything against conscience even if the state demands | `\ it." -- Albert Einstein | _o__) | Ben Finney From tjreedy at udel.edu Fri Jul 27 16:50:49 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Jul 2007 16:50:49 -0400 Subject: zip() function troubles References: <1185492336.850090.279190@b79g2000hse.googlegroups.com><1185560330.252916.307390@j4g2000prf.googlegroups.com> <1185565236.726558.265200@r34g2000hsd.googlegroups.com> Message-ID: "Istvan Albert" wrote in message news:1185565236.726558.265200 at r34g2000hsd.googlegroups.com... | On Jul 27, 2:18 pm, Raymond Hettinger wrote: | | >> What was really surprising is that it works | >> with no issues up until 1 million items" | | later editing made the sentence more difficult to read | I should have said: "What was really surprising is that zip works | with no issues up until 1 million items" | | It was the zip function (and the garbage collection that it repeatedly | triggers) that cause the problem It is not the zip function that caused a problem. It was the creation of so many tuples without any deletions. The list comp example I gave does the same thing and has the same problem. Nothing to do with zipping per se. tjr From marcot at tabini.ca Mon Jul 9 10:14:34 2007 From: marcot at tabini.ca (Marco Tabini) Date: Mon, 9 Jul 2007 10:14:34 -0400 Subject: ANN: new Python magazine looking for authors Message-ID: Hello? I am happy to announce the launch of Python Magazine [1], a magazine dedicated entirely to programming with Python and related technologies. PyMag will be published starting in October and will be available in both print and PDF format. Currently, we are looking for authors [2] and for suggestions on topics that you would like covered. We also offering a special deal on subscription pre-orders [3], including a contest to win a new MacBook. Thanks! Marco Tabini [1] http://www.pythonmagazine.com [2] http://www.pythonmagazine.com/c/p/write_for_us [3] http://www.pythonmagazine.com/c/subscribe -- Marco Tabini php|architect / Python Magazine -------------- next part -------------- An HTML attachment was scrubbed... URL: From hniksic at xemacs.org Mon Jul 16 14:56:26 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 16 Jul 2007 20:56:26 +0200 Subject: Accessing Python variables in an extension module References: <1184553584.757696.92630@g4g2000hsf.googlegroups.com> <1i1b7zw.64m7g071sk32N%aleax@mac.com> <1184591293.938223.105800@o61g2000hsh.googlegroups.com> Message-ID: <87ps2sgoth.fsf@mulj.homelinux.net> MD writes: > 2) Is there anyway to find the type of the object in C using something > like a switch statement? I was looking for something like this > switch type(object) { > STRING: "This is a string object"; > break; > INTEGER: "This is an integer object"; > break; > BOOLEAN: "This is a boolean object"; > ......... > ......... > } Not switch, but the closest you'll get is: if (object->ob_type == PyString_Type) { ... string } else if (object->ob_type == PyInt_Type) { ... int } else if (object->ob_type == PyBool_Type) { ... bool } > I don't want to run all the C Py***_Check functions on the object. Py*_Check are not expensive if the object really is of the target type. They are necessary to support subtyping correctly. From horpner at yahoo.com Tue Jul 24 14:33:04 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 24 Jul 2007 18:33:04 GMT Subject: datetime.time() class - How to pass it a time string? References: <1185297087.998644.53940@r34g2000hsd.googlegroups.com> Message-ID: On 2007-07-24, Robert Dailey wrote: > Hi, > > I have a string in the following format: > > "00:00:25.886411" > > I would like to pass this string into the datetime.time() class > and have it parse the string and use the values. However, the > __init__() method only takes integers (which means I'd be > forced to parse the string myself). Does anyone know of a way I > can make it use the string? Thanks. Consult the documentation about time.strptime (to start) and then datetime.strptime (which refers back to the time.strptime docs, in a rather unfortunate manner). -- Neil Cerutti From ahlongxp at gmail.com Mon Jul 9 03:21:29 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Mon, 09 Jul 2007 07:21:29 -0000 Subject: socket: connection reset by server before client gets response In-Reply-To: References: <1183819907.249945.239700@o11g2000prd.googlegroups.com> <1183900086.021428.83580@e9g2000prf.googlegroups.com> Message-ID: <1183965689.330543.202900@z28g2000prd.googlegroups.com> > It's a pleasure. > > Sometimes I think that all would be programmers should be > forced to write a "Hello World" to transmit out of a serial port > in assembler on hardware that carries no OS - just to teach > them about interrupts and time. > > I would require them to hand assemble the code too, to make > them appreciate what a compiler or an interpreter does. > Then there will be more crocodiles than programmers. > And if you fail the test, you get taken out and fed to the > sacred crocodiles. > > - Hendrik > > -- > For training with a bite, enrol now in Heavy Henry's > Wholesome Hackadamy for Precocious Programmers I feel a little embarrassed now. -- ahlongxp Software College,Northeastern University,China ahlongxp at gmail.com http://www.herofit.cn From nagle at animats.com Fri Jul 13 00:04:30 2007 From: nagle at animats.com (John Nagle) Date: Fri, 13 Jul 2007 04:04:30 GMT Subject: access to the namespace of a function from within its invocation In-Reply-To: References: Message-ID: Poor Yorick wrote: > In the example below, the attribute "data" is added to a function > object. There are these things called "classes" which might be useful in this situation. Python has some gratitious semantics that come with implementations in which everything is a dictionary. Don't get carried away. John Nagle From vedrandekovic at v-programs.com Tue Jul 31 06:09:54 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Tue, 31 Jul 2007 03:09:54 -0700 Subject: simple string backspace question In-Reply-To: <1i246s3.vl3okdq1tdw2N%raims@dot.com> References: <1185875052.153091.23300@19g2000hsx.googlegroups.com> <1185876068.755101.316320@b79g2000hse.googlegroups.com> <1i246s3.vl3okdq1tdw2N%raims@dot.com> Message-ID: <1185876594.444535.69470@22g2000hsm.googlegroups.com> On 31 srp, 12:03, ra... at dot.com (Lawrence Oluyede) wrote: > wrote: > > If you mean on operating system then unfortunately Windows XP. > > I don't know for sure but maybe it doesn't support all ASCII escapes > codes. > > Why do you care about \b anyway :-) ? > > -- > 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 Hi, I need this inevitable for my "programming language", for code indentation. I don't know how to write script with module tokenize for code indentation. Regards, Vedran From http Sun Jul 8 02:27:08 2007 From: http (Paul Rubin) Date: 07 Jul 2007 23:27:08 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: Message-ID: <7xejjjjtqb.fsf@ruckus.brouhaha.com> "Hamilton, William " writes: > > Why on earth would anyone prefer taking a failure in the field over > > having a static type check make that particular failure impossible? > > Because static typechecking won't make that particular failure > "impossible," but instead just change it from a type error into a data > error that may or may not be harder to identify. If your program gets a > piece of data that breaks it, you'll get a failure in the field. Static > typechecking won't prevent that. I'm not doing a good job explaining that regexp example. Static checking a la Haskell and ML avoids these problems by: 1) noticing through case analysis that you actually handle the error return (except it looks like you have to use a separate tool for this in Haskell, sigh); and 2) (in Haskell) using monadic types to propagate match results from one operation to another, automatically taking care of turning a match failure in a chain of operations into a failure of the whole chain. In Python it's all too common to say g1 = re.match(pattern, string) a = g2.group(0) g2 = re.match(template % a, other_string) result = g2.group(1) or stuff like that, without bothering to check for match failures, just because of Python's inconvenient syntax. This article explaining Haskell's Maybe typeclass (what you'd use instead of returning None in a Python function) may be of interest: http://blogs.nubgames.com/code/?cat=2 From carsten at uniqsys.com Tue Jul 31 08:49:26 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 31 Jul 2007 08:49:26 -0400 Subject: Pysqlite storing file as blob example In-Reply-To: <1185866033.407894.237840@r34g2000hsd.googlegroups.com> References: <1185841540.275571.161640@g4g2000hsf.googlegroups.com> <1185866033.407894.237840@r34g2000hsd.googlegroups.com> Message-ID: <1185886166.3370.10.camel@dot.uniqsys.com> On Tue, 2007-07-31 at 00:13 -0700, 7stud wrote: > On Jul 30, 6:25 pm, rustyhow... at gmail.com wrote: > > I'm trying to store binary data in a sqlite database and call into the > > db using pysqlite 3. > > What I've got so far is this: > > > > import sqlite > > con = sqlite.connect(DB_PATH) > > cur = con.cursor() > > query = """create table t1( > > ID INTEGER PRIMARY KEY, > > data BLOB );""" > > cur.execute(query) > > con.commit() > > b = buffer('/path/to/binary/file') > > buffer() ? Using buffer is not in itself wrong, as some DB-API modules, including sqlite3, do use buffer objects to encapsulate binary data. However, the encapsulation should be called in a portable way by using the standard Binary factory function: b = sqlite3.Binary(contents). What is wrong, though, is passing the filename into it instead of the contents. This is in addition to the wrong execute call and using the wrong version of the sqlite module, as I pointed out in my previous reply. -- Carsten Haese http://informixdb.sourceforge.net From S.Mientki-nospam at mailbox.kun.nl Wed Jul 18 13:55:05 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 18 Jul 2007 19:55:05 +0200 Subject: help with create menu in wxpython In-Reply-To: <1184780361.171375.133400@j4g2000prf.googlegroups.com> References: <1184780361.171375.133400@j4g2000prf.googlegroups.com> Message-ID: <6016c$469e529a$d443bb3a$21714@news.speedlinq.nl> better ask in the wx discussion group: wxPython-users at lists.wxwidgets.org cheers, Stef Mientki From vedrandekovic at v-programs.com Sat Jul 28 15:03:55 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Sat, 28 Jul 2007 12:03:55 -0700 Subject: a simple string question In-Reply-To: References: <1185549793.114644.62170@k79g2000hse.googlegroups.com> <1185558406.916313.32980@r34g2000hsd.googlegroups.com> <1185589263.743811.204040@x40g2000prg.googlegroups.com> <1185599148.583067.42910@d30g2000prg.googlegroups.com> <1185613816.996100.323090@r34g2000hsd.googlegroups.com> Message-ID: <1185649435.428734.100450@g4g2000hsf.googlegroups.com> On 28 srp, 14:15, Steve Holden wrote: > vedrandeko... at v-programs.com wrote: > > On 28 srp, 07:05, Zentrader wrote: > >>>> vedrandeko... at v-programs.com wrote: > >>>>> NEW TEXT : "Hello world;\nHello:\n\t\t\n\n\n\n\n\nHello2" > >> If you are doing all of this to format the output into columns, > >> Python's print() or write() will do this, and is easier as well. Some > >> more info on what you want to do will clear things up. > > > Hi, > > > That is confusing me too, so now I will try explain it more.This is > > text before "translation": > > Let me explain you with python code. I want to this "function" act > > code indentation > > >>>> Short_Text="n=90; if n==90:print 'ok'" > > Then now I must write that function for detect ";" and ":", and if > > that function detect ";" then it appends "\n" before ";" but > > if detect ":" then it appends "\n\t\t\t\t\t\t\t\t" > >>>> Short_text_after_translation="n=90;\nif n==90:\n\t\t\t\t\t\t\t\tprint 'ok" > > ...And now when we run this code with exec this must look like: > > > n=90; > > if n==90: > > print 'ok' > > > I think this will be enough for help. > > OK, but you don't want that many tab characters if you can the code to > look like you show it. It's not, anyway, a good idea to use tabs to > indent code. > > I suspect what you need is to split the code on semicolons first, then > re-form lines with colons in them. Some simple code to do this would > look *something* like what follows. This will handle a little more than > you wanted. > > >>> Short_Text="n=90; if n==90:print 'ok'" > >>> compound_lines = Short_Text.split(";") > >>> for line in compound_lines: > ... line = line.replace(":", ":\n ") > ... print line > ... > n=90 > if n==90: > print 'ok' > >>> > > Note there are issues here that I haven't addressed. The first is that > leading spaces on the second statement need to be removed, and the > second is that this only works at the outermost level of indentation. > For example, if you want to end up translating function definitions with > if statements inside them correctly you will need to handle multiple > levels of indentation. There are other problems, like semicolons and > colons inside string constants should be ignored, but the only way to > get over those will be to parse the program text according to some > grammar rather than using ad-hoc methods such as the above. > > I hope I have finally been of some assistance ... please reply via the > newsgroup, not in personal email. > > 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 Steve! When first version of this software emerge (after competition) you will get your full version for free. Once again thanks! Regards, Vedran From mmara at fibertel.com.ar Tue Jul 3 18:50:28 2007 From: mmara at fibertel.com.ar (Mariano Mara) Date: Tue, 03 Jul 2007 19:50:28 -0300 Subject: Ask for a password with OptParse Message-ID: <468AD2B4.6030005@fibertel.com.ar> Hi everyone. I'm building a script with optparse. One of the parameters will be a password. How can I code the optparse to accept/handle/format the password so that the user does not have to write it in plain/visible text in the terminal? TIA, Mariano. From goon12 at gmail.com Wed Jul 18 08:45:33 2007 From: goon12 at gmail.com (Joe Riopel) Date: Wed, 18 Jul 2007 08:45:33 -0400 Subject: Copy List In-Reply-To: <6a2ccd190707180544k4909ad3enc6a962917a26f43d@mail.gmail.com> References: <-29831789359750479@unknownmsgid> <6a2ccd190707180544k4909ad3enc6a962917a26f43d@mail.gmail.com> Message-ID: <6a2ccd190707180545m2da72493y38dd8cac8ff32095@mail.gmail.com> I forgot to mention that you can go here for a little more of an explanation: http://diveintopython.org/native_data_types/mapping_lists.html From doulos05 at gmail.com Mon Jul 16 16:42:21 2007 From: doulos05 at gmail.com (JonathanB) Date: Mon, 16 Jul 2007 13:42:21 -0700 Subject: Discover instance variables In-Reply-To: References: <1184606748.599294.293570@n60g2000hse.googlegroups.com> Message-ID: <1184618541.269717.30580@n2g2000hse.googlegroups.com> > > class Foo(): > > self.a = "bar" > > self.z = "test" > > self.var = 2 > > That's unlikely to work, though: the code is in the context of the > class, not one of its methods, so unless you happen to be declaring a > class inside another class's method it's unlikely that there's going to > be a "self" around when those three lines execute. Ah, I see. Trouble is I write most of my code on a computer that doesn't have python (shared computer and I don't have permissions to install). So I code it here, email it to myself, and test it at home. I had my debugged code at home so I couldn't post a working example. Here's working example. class World(): def __init__(self, name, WTN, Ag, Na, Ex, In, Ni, Al, Port, Type, Dia, Grav, Atmosphere, Hyd, Climate, Pop, Gov, CR, TL, Wealth, Trade=None, notes=None): self.name = name self.WTN = WTN self.Ag = Ag self.Na = Na self.Ex = Ex self.In = In self.Ni = Ni self.Al = Al self.Port = Port self.Trade = Trade self.Type = Type self.Dia = Dia self.Grav = Grav self.Atmosphere = Atmosphere self.Hyd = Hyd self.Climate = Climate self.Pop = Pop self.Gov = Gov self.CR = CR self.TL = TL self.Wealth = Wealth self.notes = notes The code to execute this is: def world_info(): # code to prompt for each variable world = World(name, WTN, Ag, Na, Ex, In, Ni, Al, Port, Type, Dia, Grav, Atmosphere, Hyd, Climate, Pop, Gov, CR, TL, Wealth) So given that example, is there a clean way to get this output: Data for Earth: Name = Earth WTN = 5.0 Ag = 0 Na = 0 ... ... Notes = None > [name for name in dir(x) if not callable(name) and not > name.startswith("__")] That does looks almost exactly like what I want I think (I'm still learning to read code to learn what it does, but from what it looks like this does a list comprehension that removes everything callable and that starts with "__") > [name for name in dir(x) if not callable(name) and not > name.startswith("__")] > > might come close - I presume you don't want __doc__ and the like. > From westymatt at gmail.com Fri Jul 13 17:08:07 2007 From: westymatt at gmail.com (matt westerburg) Date: Fri, 13 Jul 2007 16:08:07 -0500 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: <4b490f2f0707131408l10f3665ahd4d62952ac2b0f26@mail.gmail.com> I also come from a low level background (assembly and c) and I struggled with object oriented programming. People talk about procedural languages or designs and object oriented languages or designs. But after the interpreter or compiler runs the byte or machine code is procedural always. Object oriented code changes the structure of how the code is designed. Its merely a convenient way to logically group similar functions and variables. This is done in C via header and implementation files. Classes provide a simple syntax normally for associating many variables and functions inside which generally achieve a common goal. This class becomes an object that is manipulatable. For example one might want to make a class to centralize their file operations in a particular program. For instance a logger class for keeping track of execution. class logger: file = None def __init__(self): #code first executed on instantiation of the object #you must make an instance of a class otherwise its a template file = open('programx.log', 'w') def write_to_log(self, message): #self is the instance of the class you made its used to internally reference those variables contained within # self.file.write(message) def close_log(self): self.file.close() The class allows for internal referencing of variables so that the variables are global to all methods or functions. Like the for example the file handle to write to. OOP is merely an organizational structure that can only be grasped appropriately by repeated use. -------------- next part -------------- An HTML attachment was scrubbed... URL: From stefan.behnel-n05pAM at web.de Tue Jul 10 03:25:30 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 10 Jul 2007 09:25:30 +0200 Subject: Error when trying to write unicode xml to zipfile In-Reply-To: References: <1184022684.557693.111890@n60g2000hse.googlegroups.com> Message-ID: <4693346A.4030707@web.de> Gabriel Genellina wrote: > En Mon, 09 Jul 2007 20:11:24 -0300, Martin > escribi?: > >> I get below error when trying to write unicode xml to a zipfile. >> >> zip.writestr('content.xml', content.toxml()) >> File "/usr/lib/python2.4/zipfile.py", line 460, in writestr >> zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum >> UnicodeEncodeError: 'ascii' codec can't encode character u'\u25cf' in >> position 2848: ordinal not in range(128) >> >> Any ideas? > > Encode before writing. Assuming you want to use utf-8: > zip.writestr('content.xml', content.toxml().encode('utf-8')) Unless, obviously, you were serialising to a non-utf8 encoding. But since the "toxml()" method seems to return unicode here (which sounds surprising), I expect it a) to provide no XML declaration at all or b) to be broken anyway. Stefan From nogradi at gmail.com Fri Jul 13 08:07:42 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 13 Jul 2007 14:07:42 +0200 Subject: how to call bluebit... In-Reply-To: <11575281.post@talk.nabble.com> References: <11575281.post@talk.nabble.com> Message-ID: <5f56302b0707130507g1529513bo99ac829a72da6f4b@mail.gmail.com> > how to import bluebit matrik calculator that result of singular value > decomposition (SVD) in python programming.. I'm not really sure I understand you but you might want to check out scipy: http://scipy.org/ HTH, Daniel From steve at holdenweb.com Fri Jul 13 22:05:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Jul 2007 22:05:41 -0400 Subject: permission denied in shutil.copyfile In-Reply-To: References: <1184338589.129432.178560@w3g2000hsg.googlegroups.com> <14A2A120D369B6469BB154B2D2DC34D20855ACB9@EXCHVS01.ad.sfwmd.gov> Message-ID: Gabriel Genellina wrote: > En Fri, 13 Jul 2007 12:10:20 -0300, Ahmed, Shakir > escribi?: > >> Is there any way to copy a file from src to dst if the dst is >> exclusively open by other users. >> >> I am using >> >> src = 'c:\mydata\data\*.mdb' >> dst = 'v:\data\all\*.mdb' >> >> shutil.copyfile(src,dst) >> >> but getting error message permission denied. > > 1) try with a local copy too, and you'll notice an error too - it's > unrelated to other users holding the file open. > 2) use either r'c:\mydata\data' or 'c:\\mydata\\data\' > 3) shutil.copyfile copies ONE FILE at a time. > 4) use glob.glob to find the desired set of files to be copied; and > perhaps you'll find copy2 more convenient. > > the error is probably due to the unescaped backslash in teh destination string - "\a" >>> dst = 'v:\data\all\*.mdb' >>> dst 'v:\\data\x07ll\\*.mdb' >>> use dst = r'v:\data\all\*.mdb' to avoid that problem, and learn how to use raw string literals. I am also not sure that you can use wildcards n the destination like you can on the Windows command-line copy command, so you may just need to give the path to the destination directory. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From danaraicute20 at gmail.com Fri Jul 27 15:29:30 2007 From: danaraicute20 at gmail.com (Dan C) Date: Fri, 27 Jul 2007 12:29:30 -0700 Subject: =?utf-8?B?4pa6V2F0Y2ggRlJFRSBTYXRlbGxpdGUgVFYgb24geW91ciBQQyBvciBMYXB0b3Dil4Q=?= Message-ID: <1185564570.629705.233980@i38g2000prf.googlegroups.com> Instantly Turn your Computer into a Super TV ? Watch all your favorite shows on your Computer & TV! ? Channels you can?t get any other place in the U.S.A! ? Watch from anywhere in the world! ? Save 1000's of $$$ over many years on cable and satellite bills ? INSTANT DOWNLOAD ? And much, much more! For More Details: http://freetvonpc.50webs.com/ From gagsl-py2 at yahoo.com.ar Sun Jul 15 00:23:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 15 Jul 2007 01:23:51 -0300 Subject: Marshalling big objects References: <20070714230421.213010@gmx.net> Message-ID: En Sat, 14 Jul 2007 20:04:21 -0300, Orlando D?hring escribi?: > I want to marshal objects: > > - http://docs.python.org/lib/module-marshal.html > where I have problems with a bigger objects, e.g. Any specific reason you use this module? As a general purpose serializer, use pickle (or cPickle) instead. -- Gabriel Genellina From mattheww at chiark.greenend.org.uk Thu Jul 12 15:42:41 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 12 Jul 2007 20:42:41 +0100 (BST) Subject: os.wait() losing child? References: <87bqehg5v1.fsf@mulj.homelinux.net> Message-ID: <5Vl*meAPr@news.chiark.greenend.org.uk> Jason Zheng wrote: >Hrvoje Niksic wrote: >> Actually, it's not that bad. _cleanup only polls the instances that >> are no longer referenced by user code, but still running. If you hang >> on to Popen instances, they won't be added to _active, and __init__ >> won't reap them (_active is only populated from Popen.__del__). > Perhaps that's the difference between Python 2.4 and 2.5. In 2.4, > Popen's __init__ always appends self to _active: Yes, that changed between 2.4 and 2.5. Note that if you take a copy of 2.5's subprocess.py, it ought to work fine with 2.4. -M- From no at no.no Fri Jul 13 01:10:17 2007 From: no at no.no (Daniel) Date: Fri, 13 Jul 2007 08:10:17 +0300 Subject: Getting values out of a CSV References: <1184295593.638409.22910@22g2000hsm.googlegroups.com> Message-ID: On Fri, 13 Jul 2007 05:59:53 +0300, wrote: > > How do I access the value in the second row in the first position of a > CSV? Or the 3rd row, in the fifth position? > > a,b,c,d,e,f,g,h,i > j,k,l,m,n,o,p,q,r > r,s,t,v,w,x,y,z > > I'd want to get at "j" and "w". I know I can do > > import csv > reader = csv.reader(open("some.csv", "rb")) > for row in reader: > print row[0] > > to get the first value in EVERY row, but I don't want that. Thanks for > the help. > data = [row for row in csv.reader(open('some.csv', 'rb')) then you can access like so: >>> data[1][4] 'n' >>> data[0][0] 'a' >>> data[2][0] 'r' -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From steve at holdenweb.com Tue Jul 10 22:19:56 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Jul 2007 22:19:56 -0400 Subject: Best architecture for proxy? In-Reply-To: <5ficu5F3cram2U4@mid.individual.net> References: <1184076639.815417.48390@g4g2000hsf.googlegroups.com> <5ficu5F3cram2U4@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Andrew Warkentin wrote: > >> I am going to write a general-purpose modular proxy in Python. It >> will consist of a simple core and several modules for things like >> filtering and caching. I am not sure whether it is better to use >> multithreading, or to use an event-driven networking library like >> Twisted or Medusa/ Asyncore. Which would be the better >> architecture to use? > > I'd definitely use an event-driven approach with Twisted. > > Generally, multithreading is less performant than multiplexing. High > performance servers mostly use a combination of both, though. > Converselt I'd recommend Medusa - not necessarily because it's "better", but becuase I know it better. There's also a nice general-purpose proxy program (though I'd be surprised if Twisted didn't also have one). 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 steven at REMOVE.THIS.cybersource.com.au Mon Jul 16 22:51:13 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 17 Jul 2007 02:51:13 GMT Subject: Implementaion of random.shuffle References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> <87d4ys9z46.fsf@mulj.homelinux.net> Message-ID: On Mon, 16 Jul 2007 16:55:53 +0200, Hrvoje Niksic wrote: > 2**19937 being a really huge number, it's impossible to exhaust the > Mersenne twister by running it in sequence. "Impossible"? Surely this will do it: for n in xrange(2**19937 + 1): random.random() Admittedly, if each call to random() took a picosecond, it would still take 1e5982 centuries to run through the lot. You might want to go make a coffee or something while you're waiting... -- Steven. From nicolasg at gmail.com Mon Jul 23 12:52:54 2007 From: nicolasg at gmail.com (NicolasG) Date: Mon, 23 Jul 2007 16:52:54 -0000 Subject: Where do they tech Python officialy ? Message-ID: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> Hi, I want to be a professional python programmer, unfortunately I'm working on technical support and don't have the time/patience to start making projects my self. I tried to apply to some Python positions but 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.. I'm planning to save some money and attend a course in any of the universities that teach hard core Python. Does some one have any suggestions on which University to attend ? Alternatives solutions are welcome.. Regards, Nicolas G. From bignose+hates-spam at benfinney.id.au Wed Jul 25 21:00:04 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Jul 2007 11:00:04 +1000 Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> Message-ID: <87ps2ghtd7.fsf@benfinney.id.au> "mensanator at aol.com" writes: > On Jul 24, 6:08 pm, Steven D'Aprano > wrote: > > Python already does: > > "hello-" "world" => "hello-world" > > > > Propose: > > 123 456 789 => 123456789 > > 123.456 789 => 123.456789 > > So, spaces will no longer be delimiters? I don't see how you get that conclusion from Steven's proposal. If the latter implied that "spaces will no longer be delimiters", then surely the former must also imply that. The former already exists, spaces are still delimiters when syntax allows, so your conclusion is baseless. -- \ "I got food poisoning today. I don't know when I'll use it." | `\ -- Steven Wright | _o__) | Ben Finney From http Sun Jul 8 22:41:25 2007 From: http (Paul Rubin) Date: 08 Jul 2007 19:41:25 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <5engo8F38jdgaU1@mid.uni-berlin.de> <4686b9b0$0$27140$426a74cc@news.free.fr> <5epe7aF39ugprU1@mid.uni-berlin.de> Message-ID: <7xir8us3hm.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > > Which implies that even in ADA, runtime type errors are in fact > > expected - else there would be no handler for such a case. > > Well, yes, runtime errors occur - in statically typed languages as > well. That's essentially the halting-problem. Well, no, it's quite possible for a language to reject every program that has any possibility of throwing a runtime type error. The halting problem implies that no algorithm can tell EXACTLY which programs throw errors and which do not. So the language cannot accept all programs that are free of runtime type errors and reject all programs that definitely have runtime type errors, with no uncertain cases. But it's fine for a language to reject uncertain cases and accept only those which it can rigorously demonstrate have no type errors. From paul at subsignal.org Thu Jul 26 04:09:42 2007 From: paul at subsignal.org (paul) Date: Thu, 26 Jul 2007 10:09:42 +0200 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185388827.4432.34.camel@dot.uniqsys.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185388827.4432.34.camel@dot.uniqsys.com> Message-ID: Carsten Haese schrieb: >> Also, PHP, and PHP frameworks, are supported everywhere. If you going >> to use a PHP MVC framework, like codeignitor, you would have a hard >> time finding a hoster that didn't support it - all you need is php4 >> and mysql. Dollar-hosting, for $10 a year, should work just fine with >> codeignitor. With codeignitor, just copy your files to whatever host, >> and that's it, you're done. >> >> By contrast, the most popular Python frameworks have sky-high system >> requirements. Take a look at the requirements and/or recomendations >> for popular Python frameworks like Django, TurboGears, or CherryPy: >> Apache 2.0, mod_python (latest version), fastcgi (at least), command >> line access, PostgreSQL. And a lot of low-cost hosters don't support >> Python at all. > > The comparison is not fair on many levels. PHP is not a framework like > Django or TG. You get a lot more stuff with Django or TG, so of course > the requirements are higher. Wait a minute, did he write "Also, PHP and PHP frameworks are supported everywhere..."? And he is right, you can drop symphony or cakePHP in your webroot and it will work, period. > > Seriously, take a closer look at CherryPy. With CherryPy, you don't even > need Apache since it provides its own web server. So how do you run this in production? There's only one port 80, you'd need e.g. mod_proxy + CherryPy on a high port as a long running process. That's just not possible in most shared hosting envs, plus you'd have to monitor cherrypy and whatnot. Don't get me wrong, I'm not defending PHP but from a deployment POV python is definitely more complex. cheers Paul From axjacob at comcast.net Fri Jul 6 02:44:20 2007 From: axjacob at comcast.net (axjacob at comcast.net) Date: Fri, 06 Jul 2007 06:44:20 +0000 Subject: Htmllib help Message-ID: <070620070644.2754.468DE4C400077E4F00000AC222007348300D010C0E06A10407020E@comcast.net> Thank you. Thats right I don't need the output any where so I don't need to use the writer. I can remove it wowever will the formater work since it needs writer? Maybe I can use the Null writer? -------------- Original message ---------------------- From: "Gabriel Genellina" > En Thu, 05 Jul 2007 20:23:08 -0300, escribi?: > > > I am using html and formater as shown below. They are used as part of a > > larger program. > > > > Even though I don't use any print statements, the htmllib seems to be > > throwing parts of the html page on to the standard out(my screen in this > > case). Is there a way to disable the output? > > > > import htmllib > > w = formatter.DumbWriter() > > Change the above line. From http://docs.python.org/lib/writer-impls.html: > "class DumbWriter([file[, maxcol = 72]]) > Simple writer class which writes output on the file object passed in as > file or, if file is omitted, on standard output." > > (From your code fragment it appears that you are not interested in any > output - in that case you don't need the writer at all. And maybe you can > use another parser, like HTMLParser.HTMLParser, so I'd ask why do you use > a writer in the first place?) > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list From aisaac at american.edu Thu Jul 5 13:06:28 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 05 Jul 2007 17:06:28 GMT Subject: disappearing documentation of `coerce` In-Reply-To: References: Message-ID: > On 2007-07-05, Alan Isaac wrote: >>Once upon a time, `coerce` was documented >>with the other built-ins. Neil Cerutti wrote: > It's now documented in Library Reference 2.2 Non-essential > Built-in Functions. > Apparently it is no longer needed or useful, but only kept for > backward compatibility. Thanks. I now see that it is going away: http://www.python.org/dev/peps/pep-3100/ Cheers, Alan Isaac From gherron at islandtraining.com Sat Jul 28 18:41:56 2007 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 28 Jul 2007 15:41:56 -0700 Subject: this must be a stupid question ... In-Reply-To: <849ad$46abb218$d443bb3a$21452@news.speedlinq.nl> References: <849ad$46abb218$d443bb3a$21452@news.speedlinq.nl> Message-ID: <46ABC634.7040308@islandtraining.com> Stef Mientki wrote: > but I can;t find the answer ;-) > > As searching for the '$' sign doesn't work well in the help files, > I can not find out, where is the '$' sign used for. > > If I try to use it in names, > I get a compiler error, > so it probably has some special meaning. > > thanks, > Stef Mientki > The $ is not used in any Python syntax. Neither in variable names nor any syntactical construct. Of course, like any character, it can be used in strings. (And some packages, like re, will make special use of a $ in a string.) Gary Herron From mail at microcorp.co.za Mon Jul 9 02:09:18 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 9 Jul 2007 08:09:18 +0200 Subject: Where is the syntax for the dict() constructor ?! (OT) References: <468D1D9D.6060002@gmail.com><468D3445.2060408@gmail.com><1183675552.466967.136360@i13g2000prf.googlegroups.com><5f6fo1F3b25tsU1@mid.uni-berlin.de><5f8rrpF3c8qopU1@mid.uni-berlin.de> <1183853628.296224.107400@i13g2000prf.googlegroups.com><00bc01c7c13f$573770a0$03000080@hendrik> Message-ID: <003801c7c1ef$afcf6e60$03000080@hendrik> "Steve Holden" wrote: > Would we do that with esteeth? Ok Steve you've got me - my dictionary goes from estate to esteem to ester... The US spelling of "esthete" may have a bearing... - Hendrik From wolf_tracks at invalid.com Mon Jul 16 09:44:22 2007 From: wolf_tracks at invalid.com (W. Watson) Date: Mon, 16 Jul 2007 13:44:22 GMT Subject: Python and Tkinter Primer/Tutorial? In-Reply-To: <1184525138.178668.274570@22g2000hsm.googlegroups.com> References: <1184525138.178668.274570@22g2000hsm.googlegroups.com> Message-ID: Thanks for the tips to the posters above. Wow, the Grayson book is $98 on Amazon. I think I'll see if I can get a library loan! Midway on the NMT page, they fleetingly mention Lutz, but give no reference on it. From Amazon: Learning Python, Second Edition [ILLUSTRATED] (Paperback) by Mark Lutz (Author), David Ascher (Author) BartlebyScrivener wrote: > On Jul 15, 9:46 am, "W. Watson" wrote: >> Is there a primer out there on these two items? I have the Python tutorial, >> but would like either a Tkinter tutorial/primer to supplement it, or a >> primer/tutorial that addresses both. > > http://www.freenetpages.co.uk/hp/alan.gauld/tutgui.htm > > rd > -- Wayne Watson (Nevada City, CA) Web Page: From deets at nospam.web.de Sun Jul 29 09:20:32 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 29 Jul 2007 15:20:32 +0200 Subject: encode/decode misunderstanding In-Reply-To: References: Message-ID: <5h3ih4F3il4p1U1@mid.uni-berlin.de> Tim Arnold schrieb: > Hi, I'm beginning to understand the encode/decode string methods, but I'd > like confirmation that I'm still thinking in the right direction: > > I have a file of latin1 encoded text. Let's say I put one line of that file > into a string variable 'tocline', as follows: > tocline = 'Ficha Datos de p\xe9rdida AND acci\xf3n' > > import codecs > tocFile = codecs.open('mytoc.htm','wb',encoding='utf8',errors='replace') > tocline = tocline.decode('latin1','replace') > tocFile.write(tocline) > tocFile.close() > > What I think is that tocFile is wrapped to insure that anything written to > it is in utf8 > I decode the latin1 string into python's internal unicode encoding and that > gets written out as utf8. > > Questions: > what exactly is the tocline when it's read in with that \xe9 and \xed in the > string? A latin1 encoded string? Yes. A simple, pure byte-string, that happens to contain bytes which under the latin1-encoding are "correct". > Is my method the right way to write such a line out to a file with utf8 > encoding? Yes. > If I read in the latin1 file using > codecs.open(filename,encoding='latin1') and write out the utf8 file by > opening with > codecs.open(othername,encoding='utf8'), would I no longer have a problem -- > I could just read in latin1 and write out utf8 with no more worries about > encoding? As long as you don't mix bytestrings and only use unicode-objects, you should be fine, yes. Diez From maxkhesin at gmail.com Mon Jul 16 14:59:58 2007 From: maxkhesin at gmail.com (xamdam) Date: Mon, 16 Jul 2007 18:59:58 -0000 Subject: zipfile 2GB problems? In-Reply-To: References: <1184474112.081258.111490@n60g2000hse.googlegroups.com> <1184525970.082235.238200@q75g2000hsh.googlegroups.com> <1184528949.751377.5620@g4g2000hsf.googlegroups.com> Message-ID: <1184612398.359979.28900@d55g2000hsg.googlegroups.com> On Jul 15, 5:39 pm, Steve Holden wrote: > xamdam wrote: > >>> Additional info: my file is from a data provider, do not know what > >>> they used to compress it. Previous files worked ok, this one is the > >>> 1st over 2GB. Winzip has no problem with it. > >> It could be you are using a Python with an in-built limit of 2GB on file > >> size. What happens if you open the file, seek past the 2GB point and > >> then try and read data? > > > Steve, > > I used is_zipfile function, which from does exactly that from a quick > > read - goes to the end, reads expected string. It worked fine. Tried > > regular Windows 2.4.4 and 2.5.1, same result. > > Fine, if it isn't file size limitations I suspect you need to post some > code and a traceback so we can get better insight into exactly what the > problem is. > It's failing in the ZipFile constructor, which ends up throwing zipfile(2.4.3).py:291> raise BadZipfile, "Bad magic number for file header" From siona at chiark.greenend.org.uk Thu Jul 19 11:22:11 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 19 Jul 2007 16:22:11 +0100 (BST) Subject: Interpreting os.lstat() References: <1184806559.224636.266500@e9g2000prf.googlegroups.com> Message-ID: Adrian Petrescu wrote: >>>> print os.stat.__doc__ >stat(path) -> stat result > >Perform a stat system call on the given path. > >I checked the online Python documentation at http://python.org/doc/1.5.2/lib/module-stat.html Someone else has already pointed out that this is hopelessly out of date. Even if you are constrained to using 1.5.2, the current documentation at least tells you what the elements of the tuple are. >but it just says to "consult the documentation for your system.". At >this point I'm guessing that os.lstat is nothing more than a wrapper >for some Linux system call, so I looked up the results of running >'stat' on the same file, [ ... ] (a) Running 'stat' is *not the same* as a system call. (b) "Consult[ing] the documentation" may be more productive than running random(ish) programs. You should find $ man 2 stat informative. -- \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 rkmr.em at gmail.com Mon Jul 9 15:09:45 2007 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Mon, 9 Jul 2007 12:09:45 -0700 Subject: sending fastcgi requests Message-ID: I have a python fastcgi app. Is there any library in python that I can use to send a FASTCGI request to the fastcgi app? thanks -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten at uniqsys.com Wed Jul 25 15:15:26 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 25 Jul 2007 15:15:26 -0400 Subject: is_iterable function. In-Reply-To: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> Message-ID: <1185390926.4432.40.camel@dot.uniqsys.com> On Wed, 2007-07-25 at 11:58 -0700, danmcleran at yahoo.com wrote: > You can use the built-in dir() function to determine whether or not > the __iter__ method exists: > > class Iterable(object): > def __iter__(self): > pass > > class NotIterable(object): > pass > > def is_iterable(thing): > return '__iter__' in dir(thing) > > print 'list is iterable = ', is_iterable(list()) > print 'int is iterable = ', is_iterable(10) > print 'float is iterable = ', is_iterable(1.2) > print 'dict is iterable = ', is_iterable(dict()) > print 'Iterable is iterable = ', is_iterable(Iterable()) > print 'NotIterable is iterable = ', is_iterable(NotIterable()) > > Results: > list is iterable = True > int is iterable = False > float is iterable = False > dict is iterable = True > Iterable is iterable = True > NotIterable is iterable = False Testing for __iter__ alone is not enough: >>> class X(object): ... def __getitem__(self,i): ... if i<10: return i ... else: raise IndexError, i ... >>> x = X() >>> is_iterable(x) False >>> iter(x) >>> for i in x: print i ... 0 1 2 3 4 5 6 7 8 9 No __iter__ in sight, but the object is iterable. -- Carsten Haese http://informixdb.sourceforge.net From zyzhu2000 at gmail.com Thu Jul 26 21:06:23 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 27 Jul 2007 01:06:23 -0000 Subject: Another C API Question Message-ID: <1185498383.333248.225360@19g2000hsx.googlegroups.com> Hi, I run into another C API question. What is the simplest way to convert an PyObject into a double? For example, I have PyObject *obj; I know obj is a number, but I do not know the exact type. How can I convert it to double without writing a giant switch() that exhausts every single type of number? Thanks, beginner From hniksic at xemacs.org Fri Jul 20 11:17:12 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 20 Jul 2007 17:17:12 +0200 Subject: subprocess (spawned by os.system) inherits open TCP/UDP/IP port References: Message-ID: <87abtrqf47.fsf@mulj.homelinux.net> alf writes: > still would like to find out why it is happening (now FD_CLOEXEC > narrowed may yahooing/googling searches). While realize that file > descriptors are shared by forked processes it is still weird why the > port moves to the child process once parent gets killed. what it the > parent got multiple subprocesses. Netstat probably shows only one of the processes that hold to the port, possibly the one with the lowest PID (the parent). > Plus it is kind of unintuitive os.system does not protect from such > behavoir which is for me more an equivalent of like issuing a ne > wcommand/ starting a process from the shell. It is considered a feature that fork/exec'ed programs inherit file descriptors -- that's how stdin and stdout get inherited all the time. It doesn't occur often with network connections because shells rarely have reason to open them. From marduk at nbk.hopto.org Thu Jul 19 11:41:41 2007 From: marduk at nbk.hopto.org (marduk) Date: Thu, 19 Jul 2007 10:41:41 -0500 Subject: A way to re-organize a list In-Reply-To: <1184857535.033057.49150@m3g2000hsh.googlegroups.com> References: <1184857535.033057.49150@m3g2000hsh.googlegroups.com> Message-ID: <1184859701.18550.3.camel@blackwidow.nbk> On Thu, 2007-07-19 at 15:05 +0000, 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)] > ] > ] One way of doing it: def group_by(i, my_list): d = {} for t in my_list: d[t[i]] = d.get(t[i], []) + [t] return d.values() From steve at holdenweb.com Fri Jul 13 08:07:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Jul 2007 08:07:24 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1184292588.754789.265720@22g2000hsm.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373419.522607.14500@g4g2000hsf.googlegroups.com> <1182374902.920671.171900@k79g2000hse.googlegroups.com> <85ir9ifgtx.fsf@lola.goethe.zz> <1182376044.852820.261530@n2g2000hse.googlegroups.com> <87myy1gqwk.fsf@catnip.gol.com> <1184292588.754789.265720@22g2000hsm.googlegroups.com> Message-ID: Twisted wrote: [on 7/7/07]: I don't know, but it sure as hell isn't emacs. Then, more recently: > On Jul 12, 7:10 pm, Miles Bader wrote: >> Twisted writes: >>> I won't dignify your insulting twaddle and random ad-hominem verbiage >>> with any more responses after this one. Something with actual logical >>> argumentation to rebut may be another matter of course. >> Er, why don't you just answer his question (what version)? He's asking >> for actual information, which will help us understand what you are >> (trying) to to say. >> >> If you continue to just make vague and unsupported (and rather hostile) >> assertions, without examples, version numbers, or other concrete >> information, do you expect anybody will continue listening to you? > > Some people can't let sleeping dogs lie I guess. > That would be yourself you are describing, I presume? > I can't remember the specific version after all these years. It may > have been 18 or 19 point something. As for "concrete information" this > thread is littered with fairly specific anecdotes. I know, I know; > anecdotes aren't really proof of anything. Got any better suggestions? > HCI stuff is a bit slippery to try to hang a rigorous theory and > quantitative facts upon. For most people, a crappy interface isn't > something they can precisely define, but they know it when they see it > (or at least try to use it). > If your usage of emacs has to be qualified by "after all these years" then you should not have made pejorative remarks about it without expecting others whose experience is more recent to correct (or at ;east disagree with) you. Or do you just like the sound of your fingers on the keyboard? ;-) 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 Thu Jul 26 19:44:27 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 27 Jul 2007 09:44:27 +1000 Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> <87ps2ghtd7.fsf@benfinney.id.au> <1185412639.075218.186290@z24g2000prh.googlegroups.com> <1185426066.162458.187050@z28g2000prd.googlegroups.com> <87zm1jhecf.fsf@benfinney.id.au> <1185472946.945512.249830@w3g2000hsg.googlegroups.com> Message-ID: <87vec6hgro.fsf@benfinney.id.au> "mensanator at aol.com" writes: > So, just as > > >>> int('123' '456') > 123456 > > is not an error, the proposal is that > > >>> a = 123 456 > SyntaxError: invalid syntax > > will not be an error either. More directly: Just as these three statements create the same literal value: >>> 'abc' 'def' 'abcdef' >>> 'ab' 'cd' 'ef' 'abcdef' >>> 'abcdef' 'abcdef' the proposal is that these three statements create the same literal value: >>> 12 345.678 90 12345.67890 >>> 12 3456.78 90 12345.67890 >>> 12345.67890 12345.67890 and not be a syntax error. > Yet, > > >>> a = int('123 456') > Traceback (most recent call last): > File "", line 1, in > a = int('123 456') > ValueError: invalid literal for int() with base 10: '123 456' > > will still be an error. Since that value, '123 456', is one that is rejected by the 'int' constructor. Nothing to do with this proposal. > Just trying to be clear on this. Wouldn't want that syntax behavior > to carry over into run-time. The distinction you need to be clear on is between the Python syntax for writing literal values in code (which is proposed to change by this), and the behaviour of operations on arbitrary values at runtime (which is outside the scope of this proposal). -- \ "I bought a dog the other day. I named him Stay. It's fun to | `\ call him. 'Come here, Stay! Come here, Stay!' He went insane. | _o__) Now he just ignores me and keeps typing." -- Steven Wright | Ben Finney From stephenhorne100 at aol.com Fri Jul 27 09:52:04 2007 From: stephenhorne100 at aol.com (Ninereeds) Date: Fri, 27 Jul 2007 06:52:04 -0700 Subject: Compile python with Mingw In-Reply-To: References: <1185533861.522783.268580@o61g2000hsh.googlegroups.com> Message-ID: <1185544324.792702.29050@q75g2000hsh.googlegroups.com> Steve Holden wrote: > You are wrong about the compatibility. You can't compile a library with > VC 2005 and run it with a Python compiled with VC 2003. OK, my bad - sorry about that red herring. From gagsl-py2 at yahoo.com.ar Thu Jul 5 20:48:34 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Jul 2007 21:48:34 -0300 Subject: (EMBEDDING) Can't get python error message References: <1183636077.260642.31760@q69g2000hsb.googlegroups.com> Message-ID: En Thu, 05 Jul 2007 08:47:57 -0300, escribi?: > I run this string to produce a error "x+1" > > PyRun_SimpleStringFlags() return -1, so that i know this is a script > with error inside... > > but now - how can i get error message? Simply, you can't. From http://docs.python.org/api/veryhigh.html: "If there was an error, there is no way to get the exception information." Use another function instead, like PyRun_StringFlags() -- Gabriel Genellina From bj_666 at gmx.net Sun Jul 29 15:53:55 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 29 Jul 2007 19:53:55 GMT Subject: Hex editor display - can this be more pythonic? References: Message-ID: <5h49ijF3iormrU1@mid.uni-berlin.de> On Sun, 29 Jul 2007 12:24:56 -0700, CC wrote: > ln = '\x00\x01\xFF 456\x0889abcde~' > import sys > for c in ln: > sys.stdout.write( '%.2X ' % ord(c) ) > > or this: > > sys.stdout.write( ' '.join( ['%.2X' % ord(c) for c in ln] ) + ' ' ) > > Either of these produces the desired output: > > 00 01 FF 20 34 35 36 08 38 39 61 62 63 64 65 7E > > I find the former more readable and simpler. The latter however has a > slight advantage in not putting a space at the end unless I really want > it. But which is more pythonic? I would use the second with fewer spaces, a longer name for `ln` and in recent Python versions with a generator expression instead of the list comprehension: sys.stdout.write(' '.join('%0X' % ord(c) for c in line)) > The next step consists of printing out the ASCII printable characters. > I have devised the following silliness: > > printable = ' > 1!2 at 3#4$5%6^7&8*9(0)aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ\ > `~-_=+\\|[{]};:\'",<.>/?' I'd use `string.printable` and remove the "invisible" characters like '\n' or '\t'. > for c in ln: > if c in printable: sys.stdout.write(c) > else: sys.stdout.write('.') > > print > > Which when following the list comprehension based code above, produces > the desired output: > > 00 01 FF 20 34 35 36 08 38 39 61 62 63 64 65 7E ... 456.89abcde~ > > I had considered using the .translate() method of strings, however this > would require a larger translation table than my printable string. The translation table can be created once and should be faster. > I'd like to display the non-printable characters differently, since they > can't be distinguished from genuine period '.' characters. Thus, I may > use ANSI escape sequences like: > > for c in ln: > if c in printable: sys.stdout.write(c) > else: > sys.stdout.write('\x1B[31m.') > sys.stdout.write('\x1B[0m') > > print `re.sub()` might be an option here. > I'm also toying with the idea of showing hex bytes together with their > ASCII representations, since I've often found it a chore to figure out > which hex byte to change if I wanted to edit a certain ASCII char. Thus, > I might display data something like this: > > 00(\0) 01() FF() 20( ) 34(4) 35(5) 36(6) 08(\b) 38(8) 39(9) 61(a) 62(b) > 63(c) 64(d) 65(e) 7E(~) > > Where printing chars are shown in parenthesis, characters with Python > escape sequences will be shown as their escapes in parens., while > non-printing chars with no escapes will be shown with nothing in parens. For escaping: In [90]: '\n'.encode('string-escape') Out[90]: '\\n' Ciao, Marc 'BlackJack' Rintsch From aidechamp at yahoo.it Tue Jul 10 09:18:00 2007 From: aidechamp at yahoo.it (aidechamp at yahoo.it) Date: Tue, 10 Jul 2007 06:18:00 -0700 Subject: Get a filename list of a web site In-Reply-To: <1184070085.921709.219020@r34g2000hsd.googlegroups.com> References: <1184058732.163303.96300@q75g2000hsh.googlegroups.com> <1184070085.921709.219020@r34g2000hsd.googlegroups.com> Message-ID: <1184073480.953485.12180@d55g2000hsg.googlegroups.com> Thanks, faulkner, years ago I used on Windows Teleport, which had the possibilty to download only the file list. I hoped that in Linux with the aid of python & wget.... From http Thu Jul 12 15:13:23 2007 From: http (Paul Rubin) Date: 12 Jul 2007 12:13:23 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <468565a0$0$3686$426a74cc@news.free.fr> <7xvecumrte.fsf@ruckus.brouhaha.com> <1i13w96.kyyobph71qxrN%aleax@mac.com> <7xwsx63we6.fsf@ruckus.brouhaha.com> <878x9llv5x.fsf@benfinney.id.au> Message-ID: <7xbqeh5tbg.fsf@ruckus.brouhaha.com> "Chris Mellon" writes: > You can't prove a program to be correct, in the sense that it's proven > to do what it's supposed to do and only what it's supposed to do. You > can prove type-correctness, and the debate is really over the extent > that a type-correct program is also behavior-correct. But every mathematical theorem corresponds to a type, so if you can formalize an argument that your code has a certain behavior, then a type checker can statically verify it. There are starting to be programming languages with embedded proof assistants, like Concoqtion (google for it). Of course you can only prove formal properties of programs, which says nothing about whether the application is doing the right thing for what the user needs. However, you're still way ahead of the game if you have a machine-checked mathematical proof that (say) your multi-threaded program never deadlocks or clobbers data through race conditions, instead of merely a bunch of test runs in which you didn't observe deadlock or clobbered data. Similarly for things like floating-point arithmetic, Intel and AMD now use formal verification on their designs, apparently unlike in the days of the notorious original Pentium FDIV implementation, which passed billions of test vectors and then shipped with an error. Larger applications like the Javacard bytecode interpreter have been certified for various properties and pretty soon we may start seeing certified compilers and OS kernels. Things have come a long way since the 1970's. > Personally, I remain unconvinced, but am open to evidence - I've only > heard anecdotes which are readily discounted by other anecdotes. I > absolutely do not believe that pure functional style programming, > where we shun variables, is the best model for computing, either now > or in the future. I wonder if you looked at the Tim Sweeney presentation that I linked to a few times upthread. From tismer at stackless.com Mon Jul 9 05:23:25 2007 From: tismer at stackless.com (Christian Tismer) Date: Mon, 9 Jul 2007 12:23:25 +0300 Subject: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc) In-Reply-To: <1183939608.088756.178320@m37g2000prh.googlegroups.com> References: <1183939608.088756.178320@m37g2000prh.googlegroups.com> Message-ID: <930AD71E-5173-4C0B-9C32-436A768D1CA5@stackless.com> Hi there, > > i hope someone here can help me. > > basically, me and my friend have a summer project. > > in this project, we need something that would basically function as a > blender. we know we'll need to buy a motor that spins, but what we're > having trouble with is figuring out how to program it. we want to be > able to control the speed of the motor. how would we accomplish this? > > i'm new to all of this, so i'm having a hard time wrapping my mind > around how it'd be possible to program one of those things :\ > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then > turn the other direction. > > would you program it the same way you would on a personal computer > (via c, python, etc)? I did something comparable to that some time ago. This was a car simulation, for testing an electronic trip recorder. This simulation had a model for the whole car, its devices, driver who inserts his card, starter who makes the voltage break in, the gear shift, motion sensor and lots of other stuff. This system was written using Stackless Python, which allows you to use a quite intuitive and efficient programming model for this. I would like to come back to this after EuroPython and the sprints are over. cheers - chris -- Christian Tismer :^) tismerysoft GmbH : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9A : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 802 86 56 mobile +49 173 24 18 776 fax +49 30 80 90 57 05 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten at uniqsys.com Sun Jul 22 11:36:15 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 22 Jul 2007 11:36:15 -0400 Subject: split on NO-BREAK SPACE In-Reply-To: References: Message-ID: <1185118575.3159.10.camel@localhost.localdomain> On Sun, 2007-07-22 at 17:15 +0200, Peter Kleiweg wrote: > Is this a bug or a feature? > > > Python 2.4.4 (#1, Oct 19 2006, 11:55:22) > [GCC 2.95.3 20010315 (SuSE)] on linux2 > > >>> a = 'a b c\240d e' > >>> a > 'a b c\xa0d e' > >>> a.split() > ['a', 'b', 'c\xa0d', 'e'] > >>> a = a.decode('latin-1') > >>> a > u'a b c\xa0d e' > >>> a.split() > [u'a', u'b', u'c', u'd', u'e'] It's a feature. See help(str.split): "If sep is not specified or is None, any whitespace string is a separator." -- Carsten Haese http://informixdb.sourceforge.net From aleax at mac.com Tue Jul 31 11:52:26 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 31 Jul 2007 08:52:26 -0700 Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> <1185425463.796350.128550@i13g2000prf.googlegroups.com> Message-ID: <1i23xoy.19j2liaw22exuN%aleax@mac.com> mensanator at aol.com wrote: > code files? What's the regular expression for > locating a number with an arbitrary number of digits > seperated into an arbitrary number of blocks of an > arbitray number of digits with an arbitrary number > of whitespace characters between each block? For a decimal integer (or octal) number, I'd use something similar to: r'\d[\d\s]+' This also gets trailing whitespace, but that shouldn't be much of a problem in most practical cases. Of course, just like today, it becomes a bit hairier if you also want to find hex, oct (to be 0o777 in the future), other future notations such as binary, floats, complex numbers, &c:-) -- but the simple fact that a [\d\s] is accepted where today only a \d would be, per se, would not contribute to that hair in any significant way, it seems to me. Alex From sjmachin at lexicon.net Sun Jul 22 02:46:08 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 21 Jul 2007 23:46:08 -0700 Subject: converting 64-bit fixed-point to float In-Reply-To: <1i1m3fr.1xtv09p19whv9uN%johnmfisher@comcast.net> References: <1i1k9cc.1hyy4zm1ybovgwN%johnmfisher@comcast.net> <1185040832.243875.48420@e16g2000pri.googlegroups.com> <1i1m3fr.1xtv09p19whv9uN%johnmfisher@comcast.net> Message-ID: <1185086768.664538.273160@g12g2000prg.googlegroups.com> On Jul 22, 10:34 am, johnmfis... at comcast.net (John Fisher) wrote: > attn.steven.... at gmail.com wrote: > > On Jul 20, 5:59 pm, johnmfis... at comcast.net (John Fisher) wrote: > > > Hi Group, > > > > troubles with converting signed 32.32, little-endian, 2's complement > > > back to floating point. I have been trying to brew it myself. I am > > > running Python 2.5 on a Mac. Here is the C-code I have been trying to > > > leverage: > > > > double FPuint8ArrayToFPDouble(uint8 *buffer, int startIndex) > > > { > > > uint32 resultDec = 0; > > > uint32 resultWh = 0; > > > int i; > > > > for(i = 0; i < 4; i++) > > > { > > > resultDec += (uint32)buffer[startIndex + i] * pow(2, (i*8)); > > > resultWh += (uint32)buffer[startIndex + i + 4] * pow(2, (i*8)); > > > } > > > > return ( (double)((int)resultWh) + (double)(resultDec)/4294967296.0 ); > > > > } > > > There are a few problem spots in that C code. I tend to > > think that it "works" because you're on a system that has > > 4-byte int and CHAR_BIT == 8. When the most-significant-bit (MSB) > > of resultWh is 1, then casting to int makes that a negative > > value (i.e., MSB == the sign bit). > > > I presume that somewhere you include (from C99) > > and that uint32 is really uint32_t, etc. For that to be > > portable, you should probably cast to int32_t? > > > #include > > #include > > #include > > > double arr2dbl (uint8_t *buffer, int startIndex) > > { > > uint32_t decimal = 0; > > uint32_t whole = 0; > > size_t i; > > for (i = 0; i < 4; ++i) > > { > > decimal += (buffer[startIndex + i] << (i*8)); > > whole += (buffer[startIndex + i + 4] << (i*8)); > > } > > return (int32_t)whole + (decimal/(UINT32_MAX+1.0)); > > } > > > int main (void) > > { > > uint8_t arr[7][8] = { > > {0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff}, > > {0, 0, 0, 0, 0, 0, 0, 0}, > > {51, 51, 51, 51, 0, 0, 0, 0}, > > {0, 0, 0, 0, 1, 0, 0, 0}, > > {0, 0, 0, 0, 2, 0, 0, 0}, > > {102, 102, 102, 38, 42, 1, 0, 0 }, > > {205, 204, 204, 204, 0xff, 0xff, 0xff, 0xff}}; > > size_t i; > > double result; > > for (i = 0; i < sizeof arr/sizeof arr[0]; ++i) > > { > > result = arr2dbl(arr[i], 0); > > printf("%f\n", result); > > } > > return 0; > > } > > > > Here is my version in Python, with some test code built in: > > > > from ctypes import * > > > > def conv64(input): > > > input1=[0]*8 > > > input1[0]=c_ushort(input[0]) > > > input1[1]=c_ushort(input[1]) > > > input1[2]=c_ushort(input[2]) > > > input1[3]=c_ushort(input[3]) > > > input1[4]=c_ushort(input[4]) > > > input1[5]=c_ushort(input[5]) > > > input1[6]=c_ushort(input[6]) > > > input1[7]=c_ushort(input[7]) > > > #print input1[0].value, > > > input1[1].value,input1[2].value,input1[3].value > > > #print > > > input1[4].value,input1[5].value,input1[6].value,input1[7].value > > > #print > > > resultDec=c_ulong(0) > > > resultWh=c_ulong(0) > > > for i in range(4): > > > dec_c=c_ulong(input1[i].value) > > > Wh_c=c_ulong(input1[i+4].value) > > > resultDec.value=resultDec.value+dec_c.value*2**(i*8) > > > resultWh.value=resultWh.value+Wh_c.value*2**(i*8) > > > conval=float(int(resultWh.value))+float(resultDec.value)/4294967296.0 > > > #print conval > > > return conval > > > #tabs got messed up bringing this into MacSoup > > > (snipped) > > > > Finally, here is the output I get from my code: > > > > output should be -1 is 4294967296.0 > > > output should be 0 is 0.0 > > > output should be 0.2 is 0.199999999953 > > > output should be 1 is 1.0 > > > output should be 2 is 2.0 > > > output should be 298.15 is 298.15 > > > output should be -0.2 is 4294967295.8 > > > > Thanks for any light you can shed on my ignorance. > > > > wave_man > > > This is my translation: > > > from ctypes import * > > > def conv64(input): > > input1 = [c_uint8(item) for item in input] > > dec = c_uint32(0) > > whl = c_uint32(0) > > for i in xrange(4): > > dec.value += (input1[i].value << (i*8)) > > whl.value += (input1[i+4].value << (i*8)) > > cast_whl_to_int = c_int32(whl.value) > > return float(cast_whl_to_int.value + dec.value/4294967296.0) > > > for arr in [[0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff], > > [0, 0, 0, 0, 0, 0, 0, 0], > > [51, 51, 51, 51, 0, 0, 0, 0], > > [0, 0, 0, 0, 1, 0, 0, 0], > > [0, 0, 0, 0, 2, 0, 0, 0], > > [102, 102, 102, 38, 42, 1, 0, 0], > > [205,204,204,204,255,255,255,255]]: > > print "%f" % conv64(arr) > > > However, I've not looked deeply into ctypes so I > > don't know if c_int32 is really C's int, or int32_t, or ??? > > > -- > > Hope this helps, > > Steven > > Actually this was very helpful, thanks. > Holy code bloat, Batman! The following appears to give the same results as Steven's code ... def conv64jm(input): # Assuming input is an array of unsigned 8-bit ints. # If it were a string, the first step could be omitted. input1 = struct.pack('8B', *input) # alternative: map(chr, input) return struct.unpack(" References: Message-ID: <1184821914.710510.189270@d30g2000prg.googlegroups.com> On Jul 17, 4:13?pm, "Dee Asbury" wrote: > In multiplying a value of xe^-325 with ye^-4, Python is returning zero. How > do I get it to give me back my tiny value? Use the right tool for the right job. >>> import gmpy >>> help(gmpy.mpf) Help on built-in function mpf in module gmpy: mpf(...) mpf(n): builds an mpf object with a numeric value n (n may be any Python number, or an mpz, mpq, or mpf object) and a default precision (in bits) depending on the nature of n mpf(n,bits=0): as above, but with the specified number of bits (0 means to use default precision, as above) mpf(s,bits=0,base=10): builds an mpf object from a string s made up of digits in the given base, possibly with fraction-part (with period as a separator) and/or exponent-part (with exponent marker 'e' for base<=10, else '@'). If base=256, s must be a gmpy.mpf portable binary representation as built by the function gmpy.fbinary (and the .binary method of mpf objects). The resulting mpf object is built with a default precision (in bits) if bits is 0 or absent, else with the specified number of bits. >>> a = gmpy.mpf('3e-325') >>> a mpf('3.e-325') >>> b = gmpy.mpf('2e-4') >>> b mpf('2.e-4') >>> a*b mpf('6.e-329') > > Thanks! > Dee > > "The most exciting phrase to hear in science, the one that > heralds new discoveries, is not 'Eureka!' but 'That's funny...'" > > - Isaac Asimov From stesch at no-spoon.de Sat Jul 28 14:06:23 2007 From: stesch at no-spoon.de (Stefan Scholl) Date: Sat, 28 Jul 2007 20:06:23 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> <0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de> <0T49iehiIt1hNv8%stesch@parsec.no-spoon.de> <46AB8194.2060906@web.de> Message-ID: <0T49il77ItapNv8%stesch@parsec.no-spoon.de> Stefan Behnel wrote: > Stefan Scholl wrote: >> But the style of the answers makes me wonder if I should report >> the bug in xml.sax (or its documentation) or just ignore it. > > Note that PyXML is no longer actively maintained, so it's unlikely that Too bad it can still be found in at least 80 % of all XML examples. I should burn the XML chapter of the cookbook. By the way: Thanks for the tip regarding LXML. I'll try to remember it for the next project. > reporting the bug would get you a version that raises an exception when > passing a unicode string *independent of the Python version*. > > Besides, the bug has been fixed in Python 2.5 already. Just checked on a system without PyXML: xml/sax/__init__.py defines parseString() and uses cStringIO (when available). Python 2.5.1 -- Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/ From steve at REMOVE.THIS.cybersource.com.au Sun Jul 8 06:49:32 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 08 Jul 2007 20:49:32 +1000 Subject: optparse commandline References: <1183888769.130421.245250@x35g2000prf.googlegroups.com> Message-ID: On Sun, 08 Jul 2007 09:59:29 +0000, vvikram wrote: > > I want to call some function from my program and just pass it a > commandline. It should parse the commandline and return back a list of > parsed arguments (just like the sys.argv list) > > Example: > foo.parse_cmdline("/usr/bin/foorun -v -d -h") > ==> ['/usr/bin/foorun', '-v', '-d','-h'] > > Any suggestions on how to do this are appreciated. def parse_cmdline(s): """Split a command line string s into words.""" import shlex return shlex.split(s) -- Steven. From vedrandekovic at v-programs.com Sun Jul 15 10:25:19 2007 From: vedrandekovic at v-programs.com (...:::JA:::...) Date: Sun, 15 Jul 2007 16:25:19 +0200 Subject: building directpython application with py2exe Message-ID: Hello, I have problem with building directpython ( .exe ) application , actually when I finish building application and when I run it, in log file I get an error: Traceback (most recent call last): File "sampleMeshAnim.py", line 16, in ? ImportError: No module named d3d I was copy d3d.py and d3d.pyd files to same directory of builded directpython application, but I stll get the same error. Regards, Vedran __________________________________________________________________ Vedran veki ICQ#: 264412055 Current ICQ status: + More ways to contact me Get ICQ! __________________________________________________________________ From nogradi at gmail.com Wed Jul 25 15:44:39 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 25 Jul 2007 21:44:39 +0200 Subject: first, second, etc line of text file Message-ID: <5f56302b0707251244p24080f1ct87a5f459cb175dae@mail.gmail.com> A very simple question: I currently use a cumbersome-looking way of getting the first, second, etc. line of a text file: for i, line in enumerate( open( textfile ) ): if i == 0: print 'First line is: ' + line elif i == 1: print 'Second line is: ' + line ....... ....... I thought about f = open( textfile ) and then f[0], f[1], etc but that throws a TypeError: 'file' object is unsubscriptable. Is there a simpler way? From exarkun at divmod.com Tue Jul 31 07:44:42 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 31 Jul 2007 07:44:42 -0400 Subject: interaction of 'with' and 'yield' In-Reply-To: Message-ID: <20070731114442.4947.261446605.divmod.quotient.16960@ohm> On Tue, 31 Jul 2007 07:34:09 -0400, Neal Becker wrote: >I'm wondering if a generator that is within a 'with' scope exits the 'with' >when it encounters 'yield'. > >I would like to use a generator to implement RAII without having to >syntactically enclose the code in the 'with' scope, and I am hoping that >the the yield does not exit the 'with' scope and release the resource. It doesn't. Keep in mind that if the generator isn't resumed or garbage collected, the cleanup with never run, though. Jean-Paul From bdesth.quelquechose at free.quelquepart.fr Thu Jul 5 00:24:40 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 05 Jul 2007 06:24:40 +0200 Subject: CGI vs WSGI In-Reply-To: <1183553365.160758.29320@q75g2000hsh.googlegroups.com> References: <1183553365.160758.29320@q75g2000hsh.googlegroups.com> Message-ID: <468c01e3$0$30808$426a74cc@news.free.fr> tuom.larsen at gmail.com a ?crit : > Dear all, > > what is the difference? Middleware? > > I'm wondering because the only variables I ever needed were PATH_INFO, > REQUEST_METHOD, QUERY_STRING and maybe one more, all of which should > be available from CGI, too. > > Thanks. > WSGI is intented as a gateway between a web server and a long-running python application. Which means you don't have to launch a new Python interpreter, import libs, parse config, connect to the database etc etc for each and every request. Also, it's (IMHO) much more usable than CGI. From nick at craig-wood.com Sun Jul 1 04:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sun, 01 Jul 2007 03:30:04 -0500 Subject: How to close a program I execute with subprocess.Popen? References: <1183124181.318726.200620@m36g2000hse.googlegroups.com> Message-ID: A.T.Hofkamp wrote: > In principle, you should only kill your own child processes, your child process > should handle its own childs (your grant child processes). SIGTERM is one way. > Another solution often adopted is to close the stdin of the child. That is a good idea. You could also make the parent a process group leader and kill the process group. You'll get the kill signal too which you'll need to ignore. That is how the shell keeps track of things IIRC. Read man setpgid, getpgid should be helful. There are equivalent commands in os, ie os.setpgid and os.getpgid. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From ladaan at iptel.org Wed Jul 11 15:08:32 2007 From: ladaan at iptel.org (Ladislav Andel) Date: Wed, 11 Jul 2007 21:08:32 +0200 Subject: lists and dictionaries Message-ID: <46952AB0.9040902@iptel.org> Hi, I have a list of dictionaries. e.g. [{'index': 0, 'transport': 'udp', 'service_domain': 'dp0.example.com'}, {'index': 1, 'transport': 'udp', 'service_domain': 'dp1.example.com'}, {'index': 0, 'transport': 'tcp', 'service_domain': 'dp0.example.com'}, {'index': 1, 'transport': 'tcp', 'service_domain': 'dp1.example.com'}] how could I make a new list of dictionaries which would look like: [{'transports': ['udp','tcp'], 'service_domain': 'dp0.example.com'}, {'transports': ['udp','tcp'], 'service_domain': 'dp1.example.com'}] Could you help me, please? Lada From edreamleo at charter.net Mon Jul 30 12:00:14 2007 From: edreamleo at charter.net (Edward K Ream) Date: Mon, 30 Jul 2007 11:00:14 -0500 Subject: Bug? exec converts '\n' to newline in docstrings!? References: Message-ID: > The problem is because you are trying to represent a Python program as a Python string literal, and doing it incorrectly. Yes, that is exactly the problem. Thanks to all who replied. Changing changing '\n' to '\\n' fixed the problem. Edward -------------------------------------------------------------------- Edward K. Ream email: edreamleo at yahoo.com Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From jjramsey at pobox.com Fri Jul 13 22:46:24 2007 From: jjramsey at pobox.com (J. J. Ramsey) Date: Fri, 13 Jul 2007 19:46:24 -0700 Subject: Can I change one line in a file without rewriting the whole thing? Message-ID: <1184381184.772946.218220@w3g2000hsg.googlegroups.com> In Perl, there is a module called "Tie::File". What it does is tie a list to each line of a file. Change the list, and the file is automatically changed, and on top of this, only the bits of the file that need to be changed are written to disk. At least, that's the general idea. I was wondering if something roughly similar could be done in Python, or at the very least, if I can avoid doing what amounts to reading the whole file into memory, changing the copy in memory, and writing it all out again. From horpner at yahoo.com Tue Jul 3 09:01:09 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 03 Jul 2007 13:01:09 GMT Subject: Pretty Scheme, ??? Python References: <46895e12$0$5078$ba4acef3@news.orange.fr> <_Ddii.36114$G23.10348@newsreading01.news.tds.net> <1183418938.911025.55340@w5g2000hsg.googlegroups.com> Message-ID: On 2007-07-02, Paul McGuire wrote: > On Jul 2, 3:56 pm, Neil Cerutti wrote: > from pyparsing import * It's always good when your messages start like that. ;) > """ > Ok, here is the step-by-step, beginning with your posted BNF. > (Based on your test cases, I think the '{}'s are really > supposed to be '()'s.) Yeah, the Scheme version of WAE uses curlies in examples just so it looks slightly different from Scheme, although since the Scheme version is built on the Scheme read function, it actually accepts several different kinds of delimiters. Python didn't need to do that, I thought. My first impulse when programming this exercise was to ape the Scheme strategy, going with a syntax analogous to Python's, using Python's code or AST modules. But it turns out I'm not a clever enough language designer. Moreover, the fun of the book I mentioned is in designing the semantics of the programs. The book basically punts parsing, leaving it up to the 'read' function. So basically, Python gets up to speed (except for the define-type and type-case macros) simply by implementing a read with enough functionality for each mini-langauge. > ; ::= > ; > ; | { + } > ; | { - } > ; | {with { } } > ; | > > The most basic building blocks in pyparsing are Literal and > Word. With these, you compose "compound" elements using And and > MatchFirst, which are bound to the operators '+' and '|' (on > occasion, Or is required, bound to operator '^', but not for > this simple parser). Since you have a recursive grammar, you > will also need Forward. Whitespace is skipped implicitly. > > Only slightly more advanced is the Group class, which will > impart hierarchy and structure to the results - otherwise, > everything just comes out as one flat list of tokens. You may > be able to remove these in the final parser, depending on your > results after steps 1 and 2 in the "left for the student" part > below, but they are here to help show structure of the parsed > tokens. > > As convenience functions go, I think the most common are oneOf > and delimitedList. oneOf might be useful here if you want to > express id as a single-char variable; otherwise, just use > Word(alphas). > > At this point you should be able to write a parser for this WAE > grammar. Like the following 9-liner: > """ > > LPAR = Literal("(").suppress() > RPAR = Literal(")").suppress() > > wae = Forward() > num = Word(nums) > id = oneOf( list(alphas) ) The above shadows 'id'; I suppose 'ident' would be better. > addwae = Group( LPAR + "+" + wae + wae + RPAR ) > subwae = Group( LPAR + "-" + wae + wae + RPAR ) > withwae = Group( LPAR + "with" + LPAR + id + wae + RPAR + wae + RPAR ) > > wae << (addwae | subwae | withwae | num | id) > > tests = """\ > 3 > (+ 3 4) > (with (x (+ 5 5)) (+ x x))""".splitlines() > > for t in tests: > print t > waeTree = wae.parseString(t) > print waeTree.asList() > print > > """ > If you extract and run this script, here are the results: > 3 > ['3'] > > (+ 3 4) > [['+', '3', '4']] > > (with (x (+ 5 5)) (+ x x)) > [['with', 'x', ['+', '5', '5'], ['+', 'x', 'x']]] How can I make it barf for testcases like '(+ 2 3))'? It doesn't seem to expect an Eof. > Left as an exercise for the student: > 1. Define classes NumWAE, IdWAE, AddWAE, SubWAE, and WithWAE whose > __init__ methods take a ParseResults object named tokens (which you > can treat as a list of tokens), and each with a calc() method to > evaluate them accordingly. > 2. Hook each class to the appropriate WAE class using setParseAction. > Hint: here is one done for you: num.setParseAction(NumWAE) > 3. Modify the test loop to insert an evaluation of the parsed tree. I use doctest, so it looks quite different. On the other hand, it actually checks that the results are correct. ;) > Extra credit: why is id last in the set of alternatives defined > for the wae expression? I'm not sure. When I moved it to first all my valid tests still passed, but one of the deliberately erroneous ones caused a different exception, e.g., '(+ 2)'. Writing my own parser does make error handling more predictable, but probably PyParsing can be configured to do what I want. My AST's from the first version of the program translated easily into your program, with almost no muss or fuss. The muss is that, since all the __init__ functions now expect a token list instead of named arguments, they are now cryptic, and creating AST's manually became annoying. The fuss is that I do have to create one in With's calc function. It should be unnecessary for the AST objects to be so dependent upon the grammar to work correctly. I suppose a solution would be to add another layer of abstraction in between. Read it and weep. The program hasn't changed much. It's still uglier than the Scheme. Attached at the end is my original sexp and WAE parser, for comparison with the PyParsing portion of the program. This time I've included all the tests, but no other useful docstrings. """ A PyParsing solution for WAE, composed by Paul MaGuire, with semantics by Neil. >>> parse('3') >>> parse('(+ 3 45)') > >>> parse('(with (x (+ 5 5)) (+ x x))') > >> >>> parse('3').calc() 3 >>> parse('(+ 2)') Traceback (most recent call last): ... ParseException: Expected "(" (at char 4), (line:1, col:5) >>> parse('(+ 3 45)').calc() 48 >>> parse('(- 3 2)').calc() 1 >>> parse('(- (+ 8 4) 4)').calc() 8 >>> parse('(with (x (+ 5 5)) (+ x x))').calc() 20 >>> parse('(with (x 5) (+ 2 x))').calc() 7 >>> parse('(with (x x) x)').calc() Traceback (most recent call last): ... SyntaxError: Free identifier """ import operator from pyparsing import * class Num(object): def __init__(self, tokens): self.number = int(tokens[0]) def __repr__(self): return '' % self.number def subst(self, sub_id, value): return self def calc(self): return self.number class Id(object): def __init__(self, tokens): self.name = tokens[0] def __repr__(self): return '' % self.name def __eq__(self, an_id): return an_id.name == self.name def subst(self, sub_id, value): if sub_id == self: return value else: return self def calc(self): raise SyntaxError('Free identifier') class BinOp(object): def __init__(self, tokens): self.op, self.name = {'+': (operator.add, 'Add'), '-': (operator.sub, 'Sub')}[tokens[0][0]] self.lhs = tokens[0][1] self.rhs = tokens[0][2] def __repr__(self): return '<%s %r %r>' % (self.name, self.lhs, self.rhs) def subst(self, sub_id, value): self.lhs = self.lhs.subst(sub_id, value) self.rhs = self.rhs.subst(sub_id, value) return self def calc(self): return self.op(self.lhs.calc(), self.rhs.calc()) class With(object): def __init__(self, tokens): self.bound_id = tokens[0][1] self.named_expr = tokens[0][2] self.bound_body = tokens[0][3] def __repr__(self): return '' % (self.bound_id, self.named_expr, self.bound_body) def subst(self, sub_id, value): self.named_expr = self.named_expr.subst(sub_id, value) if sub_id != self.bound_id: self.bound_body = self.bound_body.subst(sub_id, value) return self def calc(self): tokens = [self.named_expr.calc()] return self.bound_body.subst(self.bound_id, Num(tokens)).calc() LPAR = Literal("(").suppress() RPAR = Literal(")").suppress() wae = Forward() num = Word(nums).setParseAction(Num) ident = Word(alphas).setParseAction(Id) addwae = Group( LPAR + "+" + wae + wae + RPAR ).setParseAction(BinOp) subwae = Group( LPAR + "-" + wae + wae + RPAR ).setParseAction(BinOp) withwae = Group( LPAR + "with" + LPAR + ident + wae + RPAR + wae + RPAR ).setParseAction(With) wae << (addwae | subwae | withwae | num | ident) def parse(s): return wae.parseString(s).asList()[0] if __name__ == '__main__': import doctest doctest.testmod() Below is my simple sexp parser and wae adapter (most tests and some docs removed for brevity). The hand-written scanner is a result of the horrible performance and readability of the regex-based scanners I experimented with. """ sexp.py A compiler of s-expressions into tuples. Functions provided: read(sexp) Convert a Python str that represents one s-expression into a tuple. For example, >>> read('(+ 4 5)') ('+', 4, 5) >>> read('(+ 4 5 (- 8))') ('+', 4, 5, ('-', 8)) Only s-expressions, symbols, and integers are recognized. Only one expression may appear in the string. Trailing characters result in an exception. >>> read('(first experssion) (second expression)') Traceback (most recent call last): ... ParseError: Expected EOF, got ( EBNF: goal -> [ ] EOF sexp -> '(' { } ')' expr -> | INTEGER |SYMBOL """ def read(sexp): """ Read an s-expression (in the form of a string), and return a list representing its parse tree. >>> read('') >>> read('400') 400 This parser readly only one expression at a time, unlike a scheme reader. >>> read('23 skidoo') Traceback (most recent call last): ... ParseError: Expected EOF, got SYMBOL >>> read('()') () >>> read('(()') Traceback (most recent call last): ... ParseError: Expected ), got EOF >>> read('(+ 4 5)') ('+', 4, 5) """ return Parser(scan(sexp)).parse() class ParseError(SyntaxError): pass class Parser(object): """ Parser for simple s-expressions. BNF: goal ::= EOF opt_expr ::= opt_expr ::= ~ expr ::= expr ::= INTEGER expr ::= SYMBOL sexp ::= '(' ')' opt_expr_list ::= opt_expr_list ::= ~ expr_list ::= expr_tail ::= expr_tail ::= ~ """ def __init__(self, iterable): iterator = iter(iterable) self.token, self.value = iterator.next() self.next = iterator.next def match(self, want): if want != self.token: raise ParseError("Expected %s, got %s" % (want, self.token)) value = self.value if self.token != 'EOF': self.token, self.value = self.next() return value def parse(self): return self.goal() def goal(self): ast = self.opt_expr() self.match('EOF') return ast def opt_expr(self): if self.token == 'EOF': return None else: return self.expr() def opt_expr_list(self): if self.token in ['(', 'INTEGER', 'SYMBOL']: return self.expr_list() else: return () def expr_list(self): return (self.expr(),) + self.expr_tail() def expr_tail(self): if self.token in ['(', 'INTEGER', 'SYMBOL']: return (self.expr(),) + self.expr_tail() else: return () def expr(self): if self.token == '(': return self.sexp() elif self.token == 'INTEGER': return self.match('INTEGER') elif self.token == 'SYMBOL': return self.match('SYMBOL') def sexp(self): self.match('(') ast = self.opt_expr_list() self.match(')') return ast # EOF is the end of the input stream. # INTEGER is '[0-9]+' # SYMBOL is '[^0-9][^ ]*' def scan(sexp): """ Yield the tokens in sexp, in the order they are encountered. >>> for token in scan('()'): ... print token ('(', '(') (')', ')') ('EOF', 'EOF') >>> for token in scan('(+ 5 3)'): ... print token ('(', '(') ('SYMBOL', '+') ('INTEGER', 5) ('INTEGER', 3) (')', ')') ('EOF', 'EOF') >>> for token in scan('12a'): ... print token Traceback (most recent call last): ... ParseError: Ill-formed INTEGER """ ix = 0 length = len(sexp) while ix < length: if sexp[ix] in '()': yield (sexp[ix], sexp[ix]) ix += 1 elif sexp[ix] in '0123456789': jx = ix+1 while jx < length and sexp[jx] in '0123456789': jx += 1 if jx < length and sexp[jx] not in ' \t\n()': raise ParseError("Ill-formed INTEGER") yield ('INTEGER', int(sexp[ix:jx])) ix = jx elif sexp[ix] not in ' \t\n': jx = ix+1 while jx < length and sexp[jx] not in ' \t\n)(': jx += 1 yield ('SYMBOL', sexp[ix:jx]) ix = jx else: ix += 1 yield ('EOF', 'EOF') if __name__ == '__main__': import doctest doctest.testmod() And finally, the WAE adapter, which is not necessarily required by the PyParsing solution. def parse(expr): """ Compile a string representing an WAE expression into an object that represents the abstract syntax tree of that expression. The AST provides a calc method that returns the result of evaluating the expression. >>> parse('(+ 4 5)') > """ def parse_ast(ast): if isinstance(ast, int): return Num(ast) elif isinstance(ast, str): return Id(ast) elif isinstance(ast, tuple): op = ast[0] if op in ['+', '-'] and len(ast) == 3: if op == '+': return Add(parse_ast(ast[1]), parse_ast(ast[2])) elif op == '-': return Sub(parse_ast(ast[1]), parse_ast(ast[2])) elif op == 'with' and len(ast) == 3 and len(ast[1]) == 2: return With(ast[1][0], parse_ast(ast[1][1]), parse_ast(ast[2])) raise SyntaxError("Ill-formed expression") return parse_ast(sexp.read(expr)) The isinstance calls are quite unfortunate compared to type-case. For example, type-case will signal an error if I haven't handled all possible cases. -- Neil Cerutti From sjmachin at lexicon.net Tue Jul 31 08:17:07 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 31 Jul 2007 05:17:07 -0700 Subject: simple string backspace question In-Reply-To: <1185876068.755101.316320@b79g2000hse.googlegroups.com> References: <1185875052.153091.23300@19g2000hsx.googlegroups.com> <1185876068.755101.316320@b79g2000hse.googlegroups.com> Message-ID: <1185884227.491711.105160@x35g2000prf.googlegroups.com> On Jul 31, 8:01 pm, vedrandeko... at v-programs.com wrote: > On 31 srp, 11:44, vedrandeko... at v-programs.com wrote: > > > Hello, > > > I have one simple string, backspace character question.Here is my > > example: > > > >>> text="Hello\bworld" > > >>> print text > > > "HelloBSworld" > > > Should this character "\b" (backspace) in this text return this: > > "Helloworld"? > > > Regards, > > Vedran > > Hi, > > If you mean on operating system then unfortunately Windows XP. Point (1) Works on Windows XP for me: C:\junk>ver Microsoft Windows XP [Version 5.1.2600] C:\junk>\python25\python Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> text = "Hello\bworld" >>> print text Hellworld >>> or, for mild amusement: >>> import sys, time >>> for x in xrange(100): ... sys.stdout.write("|/-\\"[x & 3] + "\b") ... time.sleep(0.1) ... >>> 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 ... From malaclypse2 at gmail.com Tue Jul 3 23:35:30 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 3 Jul 2007 23:35:30 -0400 Subject: How can i change an Object type ? In-Reply-To: <1183516235.774875.45710@q69g2000hsb.googlegroups.com> References: <1183516235.774875.45710@q69g2000hsb.googlegroups.com> Message-ID: <16651e80707032035l1ad15118o66adb8ab8685c755@mail.gmail.com> On 7/3/07, KuhlmannSascha wrote: > I am focussing on the Playlists of the object UserPlaylist. > (CodeLine: if curPlaylist.Kind == 2:) > After that i should be sure to have a UserPlaylist, but Python stops > with an exception that the requested Attribute "Smart" is not > available It looks like win32com thinks you have a IITPlaylist, and you really have a subclass of that, a IITUserPlaylist. You need to cast it like this: import win32com.client iTunes = win32com.client.gencache.EnsureDispatch('iTunes.Application') playlists = iTunes.LibrarySource.Playlists for playlist in playlists: if playlist.Kind == 2: playlist = win32com.client.CastTo(playlist, 'IITUserPlaylist') print "Name: ", playlist.Name print "Kind: ", playlist.Kind print "Smart: ", playlist.Smart print -- Jerry From lance at augustmail.com Wed Jul 25 21:45:53 2007 From: lance at augustmail.com (Lance Hoffmeyer) Date: Thu, 26 Jul 2007 01:45:53 GMT Subject: win32com ppt embedded object numbers reverting back to original numbers - SOLVED In-Reply-To: References: Message-ID: Hey all, I solved this problem. Here is the final version of this def for anyone who someday may be interested: def attributesbyID(row,base,slideID,spreadsheet): sh = wb.Worksheets (spreadsheet) sh.Select() LIST = xlparams(row, base) ################ POWERPOINT SECTION ###################### for shape in WB.Slides.FindBySlideID(slideID).Shapes: if (shape.Type== 7): for oXLROW,oXLBASE,oXLLASTCOL,oPPTCELL,oPPTHEADERCELL in LIST: oVALUE = sh.Cells(oXLROW,oXLLASTCOL).Value oHEADER = sh.Cells(base-1,oXLLASTCOL).Value + " (n=" + str(int(sh.Cells(oXLBASE,oXLLASTCOL).Value)) + ")" PWB = WB.Slides.FindBySlideID(slideID).Shapes(shape.Name) oGraph = PWB.OLEFormat.Object # oGraph = shape.OLEFormat.Object oGraph.Application.datasheet.Range(oPPTCELL).Value = oVALUE oGraph.Application.datasheet.Range(oPPTHEADERCELL).Value = oHEADER oGraph.Application.datasheet.Font.Bold=False oGraph.Application.Update() oGraph.Application.Quit() del oGraph From captainpoutine at gmail.com Thu Jul 5 14:11:17 2007 From: captainpoutine at gmail.com (Captain Poutine) Date: Thu, 05 Jul 2007 14:11:17 -0400 Subject: Where is the syntax for the dict() constructor ?! In-Reply-To: References: <468D1D9D.6060002@gmail.com> Message-ID: <468D3445.2060408@gmail.com> Neil Cerutti wrote: > On 2007-07-05, Captain Poutine wrote: >> I'm simply trying to read a CSV into a dictionary. >> >> (if it matters, it's ZIP codes and time zones, i.e., >> 35983,CT >> 39161,CT >> 47240,EST >> >> >> >> Apparently the way to do this is: >> >> import csv >> >> dictZipZones = {} >> >> reader = csv.reader(open("some.csv", "rb")) >> for row in reader: >> # Add the row to the dictionary > > In addition to Chris's answer, the csv module can read and write > dictionaries directly. Look up csv.DictReader and csv.DictWriter. > Yes, thanks. I was happy when I saw it at http://www.python.org/doc/2.4/lib/node615.html "Reader objects (DictReader instances and objects returned by the reader() function) have the following public methods: next( ) Return the next row of the reader's iterable object as a list, parsed according to the current dialect." But that's not enough information for me to use. Also, the doc says basically "csv has dialects," but doesn't even enumerate them. Where is the real documentation? Also, when I do a print of row, it comes out as: ['12345', 'ET'] But there are no quotes around the number in the file. Why is Python making it a string? From Brad.Johnson at ballardtech.com Mon Jul 30 18:44:23 2007 From: Brad.Johnson at ballardtech.com (Brad Johnson) Date: Mon, 30 Jul 2007 22:44:23 +0000 (UTC) Subject: Utilizing a raw IDispatch Pointer from Python Message-ID: I have a C++ application that creates a collection of COM objects. I would like to give the Python interpreter access to these interfaces that were created in C++ land. Stated another way, how can I have Python consume a IDispatch pointer from C++ and wrap it with one of those nice Python classes automatically? Thanks in advance. From dittonamed at gmail.com Thu Jul 26 09:41:44 2007 From: dittonamed at gmail.com (dittonamed) Date: Thu, 26 Jul 2007 06:41:44 -0700 Subject: Scope PyQt question Message-ID: <1185457304.755050.308530@z24g2000prh.googlegroups.com> Code pasted below -----> Can anyone out there suggest a way to access the object "p" thats started in playAudio() from inside the stopAudio()? I need the object reference to use QProcess.kill() on it. The code sample is below. Thanks to anyone who helps out =) More comments in the code below ------> from qt import * class Form2(QMainWindow): def __init__(self,parent = None,name = None,fl = 0): QMainWindow.__init__(self,parent,name,fl) self.statusBar() def playAudio(self): p = QProcess(self, 'player') playcmd = '/usr/bin/play' filename = 'song.ogg' p.addArgument(playcmd) p.addArgument(filename) p.start() def stopAudio(self): ''' #This is just to show that i can "see" the object, though i #dont know how to "access" it #the output shows the QProcess object by name... # but how do i reference it?? allobjs = list(QObject.objectTrees()) for obj in allobjs: objName = QObject.name(obj) if objName == 'Form2': print QObject.children(obj) ''' QProcess.kill(NEED THE REFERENCE HERE) From jelleferinga at gmail.com Wed Jul 25 07:05:37 2007 From: jelleferinga at gmail.com (jelle) Date: Wed, 25 Jul 2007 11:05:37 -0000 Subject: adding a docstring to an instancemethod Message-ID: <1185361537.733690.238280@k79g2000hse.googlegroups.com> Hi, I'm working on documenting wrapped C++ methods. The thing is that I'd like to add docstrings to a method, but python won't allow me to: TypeError: attribute '__doc__' of 'instancemethod' objects is not writable What would be an easy way to do so? I'd like to overload the .__doc__, rather than wrapping it in a class. Cheers, -jelle From ahlongxp at gmail.com Mon Jul 9 08:27:27 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Mon, 09 Jul 2007 12:27:27 -0000 Subject: socket: connection reset by server before client gets response In-Reply-To: <1183979009.295965.60230@d55g2000hsg.googlegroups.com> References: <1183819907.249945.239700@o11g2000prd.googlegroups.com> <1183900086.021428.83580@e9g2000prf.googlegroups.com> <1183969844.697022.298650@w3g2000hsg.googlegroups.com> <1183972571.875740.13930@z28g2000prd.googlegroups.com> <1183979009.295965.60230@d55g2000hsg.googlegroups.com> Message-ID: <1183984047.622057.122110@m37g2000prh.googlegroups.com> On Jul 9, 7:03 pm, Adriano Varoli Piazza wrote: > ahlongxp wrote: > > I feel officially offended. > > I didn't intend to offend you, I was joking. I apologise in any case. > There's a few things to be said, though: > > As per your message in another thread, it isn't that you don't express > yourself clearly in English, but that you were too quick to claim a > standard function was buggy without first thinking if your own code > could be buggy instead. That presumption isn't related to the language. > > Second, if you do say that you aren't comfortable in English, try to > assume that people aren't trying to insult you by default. I was > speaking generallyin my message. > > Third, this is usenet. Although probably not in this newsgroup, if you > continue to make the assumptions I and others pointed out, you will > receive this kind of answer. Perhaps with much more insult than right > now. So it is a great idea to grow a thick skin. > > -- > Saludos > Adriano You don't have to apologise. I was joking too. But I know I have to change my way of thinking and questioning. I'll consider more carefully before speaking. I hope I can talk like you very soon. Thanks. -- ahlongxp Software College,Northeastern University,China ahlongxp at gmail.com http://www.herofit.cn From pollastri at iriti.cnr.it Fri Jul 6 04:36:19 2007 From: pollastri at iriti.cnr.it (Fabrizio Pollastri) Date: Fri, 06 Jul 2007 10:36:19 +0200 Subject: Writing a read only attribute Message-ID: <468DFF03.6070602@iriti.cnr.it> My code is the following: from Tkinter import * def tk_dummy_call(*args): return root = Tk() # save call address original_tk_call = root.tk.call # disable tcl command execution (this is the read-only attribute) root.tk.call = tk_dummy_call ... some code ... # restore tcl command execution root.tk.call = original_tk_call My goal is to make instances of Tkinter widgets without the effects of commands directed to the tcl interpreter but preserving all effects at python level. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 13 06:35:58 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 13 Jul 2007 12:35:58 +0200 Subject: bool behavior in Python 3000? In-Reply-To: <1184309140.606670.109950@r34g2000hsd.googlegroups.com> References: <46961f33$0$90263$14726298@news.sunsite.dk> <1184309140.606670.109950@r34g2000hsd.googlegroups.com> Message-ID: <46975564$0$6072$426a74cc@news.free.fr> Miles a ?crit : > On Jul 12, 8:37 pm, Alan Isaac wrote: >> I do not like that bool(False-True) is True. > > I've never seen the "A-B" used to represent "A and not B", nor have I > seen any other operator used for that purpose in boolean algebra, > though my experience is limited. Where have you seen it used? I've personnaly seen the usual arithmatic operators used for boolean algebra in quite a lot of papers covering the topic - but I've always had to translate them to more common boolean ops to understand these papers. > What's wrong with 'and', 'or', and 'not'? I think that redefining *, > +, and - to return booleans would only encourage programmers to use > them as shortcuts for standard boolean operations--I'd hate to see > code like this: >>>> if user.registered * (user.age > 13) - user.banned: ... > OMG ! Lord have mercy ! St Guido, save us ! > I don't mind that arithmatic operations are _possible_ with bools, but > I would strongly prefer to see the boolean keywords used for > operations on booleans. +10 From cbfalconer at yahoo.com Tue Jul 3 19:15:20 2007 From: cbfalconer at yahoo.com (CBFalconer) Date: Tue, 03 Jul 2007 19:15:20 -0400 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> <7x645al8kc.fsf@ruckus.brouhaha.com> <1182894003.920335.317620@a26g2000pre.googlegroups.com> <7x7ipoy6cf.fsf@ruckus.brouhaha.com> <1183041149.275562.114490@o11g2000prd.googlegroups.com> <7xbqethpr8.fsf@ruckus.brouhaha.com> Message-ID: <468AD888.6A023A0E@yahoo.com> "Peter J. Holzer" wrote: > Richard Heathfield wrote: > ... snip ... > >> In that case, the obvious choice is Greenwich Mean Time. :-) > > Hardly. That hasn't been in use for over 35 years (according to > Wikipedia). I am glad to see you depend on absolutely reliable sources. -- cbfalconer at maineline dot net -- Posted via a free Usenet account from http://www.teranews.com From carsten at uniqsys.com Sat Jul 21 22:18:56 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 21 Jul 2007 22:18:56 -0400 Subject: [2.5] Regex doesn't support MULTILINE? In-Reply-To: References: Message-ID: <1185070736.4151.5.camel@localhost.localdomain> On Sun, 2007-07-22 at 04:09 +0200, Gilles Ganault wrote: > Hello > > I'm trying to extract information from a web page using the Re module, That's your problem right there. RE is not the right tool for that job. Use an actual HTML parser such as BeautifulSoup (http://www.crummy.com/software/BeautifulSoup/) and your life will be much easier. HTH, -- Carsten Haese http://informixdb.sourceforge.net From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jul 19 03:40:24 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 19 Jul 2007 09:40:24 +0200 Subject: class C: vs class C(object): In-Reply-To: <1184830266.181714.183320@z24g2000prh.googlegroups.com> References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> Message-ID: <469f1557$0$26759$426a74cc@news.free.fr> nvictor a ?crit : > Hi, > > I'm not an experienced developer, and I came across this statement by > reading a code. I search for explanation, but can't find anything > meaningful. I read the entire document written by python's creator > about the features of version 2.2 The one named unifying types and > classes. But This document only blew my head away. > > I ended here and think somebody can explain me more about this. To make a long story short: Python 2.2 introduced a new object model which is more coherent and more powerful than the original one. The old one was kept so far for compatibility reasons, but there's absolutely no reason to use it no more since "new-style" classes can do anything "Classic" classes did and much more. IOW, don't even bother with old-style classes. From S.Mientki-nospam at mailbox.kun.nl Sat Jul 28 17:22:23 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 28 Jul 2007 23:22:23 +0200 Subject: this must be a stupid question ... Message-ID: <849ad$46abb218$d443bb3a$21452@news.speedlinq.nl> but I can;t find the answer ;-) As searching for the '$' sign doesn't work well in the help files, I can not find out, where is the '$' sign used for. If I try to use it in names, I get a compiler error, so it probably has some special meaning. thanks, Stef Mientki From westymatt at gmail.com Fri Jul 13 17:15:52 2007 From: westymatt at gmail.com (matt westerburg) Date: Fri, 13 Jul 2007 16:15:52 -0500 Subject: Fwd: Can a low-level programmer learn OOP? In-Reply-To: <4b490f2f0707131408l10f3665ahd4d62952ac2b0f26@mail.gmail.com> References: <4b490f2f0707131408l10f3665ahd4d62952ac2b0f26@mail.gmail.com> Message-ID: <4b490f2f0707131415k6060f01cye103b04941439707@mail.gmail.com> I also come from a low level background (assembly and c) and I struggled with object oriented programming. People talk about procedural languages or designs and object oriented languages or designs. But after the interpreter or compiler runs the byte or machine code is procedural always. Object oriented code changes the structure of how the code is designed. Its merely a convenient way to logically group similar functions and variables. This is done in C via header and implementation files. Classes provide a simple syntax normally for associating many variables and functions inside which generally achieve a common goal. This class becomes an object that is manipulatable. For example one might want to make a class to centralize their file operations in a particular program. For instance a logger class for keeping track of execution. class logger: file = None def __init__(self): #code first executed on instantiation of the object #you must make an instance of a class otherwise its a template file = open('programx.log', 'w') def write_to_log(self, message): #self is the instance of the class you made its used to internally reference those variables contained within # self.file.write(message) def close_log(self): self.file.close() The class allows for internal referencing of variables so that the variables are global to all methods or functions. Like the for example the file handle to write to. OOP is merely an organizational structure that can only be grasped appropriately by repeated use. -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Tue Jul 17 08:02:45 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 17 Jul 2007 05:02:45 -0700 Subject: a=0100; print a ; 64 how to reverse this? In-Reply-To: <1184670575.205759.115360@i13g2000prf.googlegroups.com> References: <1184670575.205759.115360@i13g2000prf.googlegroups.com> Message-ID: <1184673765.336181.34320@e16g2000pri.googlegroups.com> On Jul 17, 9:09 pm, mosi wrote: > Problem: > how to get binary from integer and vice versa? > The simplest way I know is: > a = 0100 > a > 64 > > but: > a = 100 (I want binary number) > does not work that way. > > a.__hex__ exists > a.__oct__ exists > > but where is a.__bin__ ??? > > What`s the simplest way to do this? > Thank you very much. Here's a sketch; I'll leave you to fill in the details -- you may wish to guard against interesting input like b < 2. >>> def anybase(n, b, digits='0123456789abcdef'): ... tmp = [] ... while n: ... n, d = divmod(n, b) ... tmp.append(digits[d]) ... return ''.join(reversed(tmp)) ... >>> anybase(1234, 10) '1234' >>> anybase(7, 2) '111' >>> [anybase(64, k) for k in range(2, 17)] ['1000000', '2101', '1000', '224', '144', '121', '100', '71', '64', '59', '54', '4c', '48', '44', '40'] >>> HTH, John From ratchetgrid at googlemail.com Mon Jul 2 20:22:04 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Tue, 3 Jul 2007 01:22:04 +0100 Subject: Programming Idiomatic Code Message-ID: <676224240707021722x4b2cba53o6d9fc77a873dd80a@mail.gmail.com> Hi, I m sorry but I m bored at work (and no ones looking so I can write some Python) and following a job advertisement post,I decided to write the code to do its for the one entitled Ninjas or something like that. I was wondering what could be done to my following code to make it more idiomatic...or whether it was idiomatic and to be honest what idiomatic really means. All comments greatly appreciated and welcomed. Thanks in advance Nathan import urllib2,sys from elementtree.ElementTree import parse base_url = "http://api.etsy.com/feeds/xml_user_details.php?id=" def read_id_file(filename): """ reads a file and generates a list of ids from it""" ids = [ ] try: id_file = open(filename, "r") for l in id_file: ids.append( l.strip("\n") ) id_file.close() except e: print e os._exit(99) return ids def generate_count(id_list): """ takes a list of ids and returns a dictionary of cities with associated counts""" city_count = {} for i in id_list: url = "%s%s" %(base_url,i) req = urllib2.Request(url) try: xml = parse(urllib2.urlopen(url)).getroot() city = xml.findtext('user/city') except e: print e.reason os._exit(99) try: city_count[city] += 1 except: city_count[city] = 1 return city_count if __name__=='__main__': if len(sys.argv) is 1: id_list = [ 42346, 77290, 729 ] else: try: id_list = read_id_file(sys.argv[1]) except e: print e for k, v in generate_count(id_list).items(): print "%s: %i" %(k, v) From josiah.carlson at sbcglobal.net Sat Jul 7 13:27:52 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Sat, 07 Jul 2007 17:27:52 GMT Subject: Auto-parallelizing with decorators? In-Reply-To: References: Message-ID: Kirk Strauser wrote: > In article , > Kirk Strauser wrote: > >> I was thinking about how a lot of Lisp proponents claim that Lisp is >> inherently parallelizable because its functions don't have (or are not >> supposed to have) side effects, and therefore the compiler can easily tell >> which calls may be run in parallel instead of strictly serially. I'm not a >> Lisp expert so I can't say whether that's true or not, but it seems like an >> interesting idea for Python. > > By the way, I uploaded a sample implementation (in Python) of what I had > in mind to http://www.honeypot.net/multi-processing-map-python . Please > let me know what you think of it and whether it seems remotely > interesting or goofy. Try the Processing package available at the Python package index. Create as many processes as you want, then toss the data you want processed into a Queue. Watch magically as your data gets processed. - Josiah From rrenaud at gmail.com Mon Jul 9 20:45:31 2007 From: rrenaud at gmail.com (rrenaud at gmail.com) Date: Tue, 10 Jul 2007 00:45:31 -0000 Subject: Passing a CookieJar instead of a cookieproc to urllib2.build_opener Message-ID: <1184028331.849197.263130@g4g2000hsf.googlegroups.com> urllib2.build_opener happily accepts and ignores a FileCookieJar. I had a bug in my code which looked like urllib2.build_opener(func_returning_cookie_jar()) which should have been urllib2.build_opener(HTTPCookieProcessor(func_returning_cookie_jar()) The problem is that the code ran happily without actually sending the cookie, the CookieJar was just ignored. I think that build_opener should throw an exception when add_handler doesn't actually add. Is this worth filing a bug for, or is it acceptable behavior? From zentraders at gmail.com Sat Jul 21 14:07:23 2007 From: zentraders at gmail.com (Zentrader) Date: Sat, 21 Jul 2007 18:07:23 -0000 Subject: Pythonic way for missing dict keys In-Reply-To: References: Message-ID: <1185041243.323915.161230@x40g2000prg.googlegroups.com> On Jul 21, 7:48 am, Duncan Booth wrote: > "Rustom Mody" wrote: > > Can someone who knows about python internals throw some light on why > >>>> x in dic > > is cheaper than > >>>> dic.has_key(x) > > > ?? > >From the 2.6 PEP #361 (looks like dict.has_key is deprecated) Python 3.0 compatability: ['compatibility'-->someone should use a spell-checker for 'official' releases] - warnings were added for the following builtins which no longer exist in 3.0: apply, callable, coerce, dict.has_key, execfile, reduce, reload From jeff at jmcneil.net Wed Jul 25 14:58:12 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Wed, 25 Jul 2007 14:58:12 -0400 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185385374.866372.198520@x35g2000prf.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> Message-ID: <82d28c40707251158ibae2f9u70889f01ac45a9f6@mail.gmail.com> Unfortunately, I also find that PHP programmers are usually more plentiful than their Python counterparts. When thinking of staffing an organization, it's common to target a skill set that's cheaper to employ and easier to replace down the road if need be. Also, larger hosting shops are hesitant to run things such as TG and Rails that require an additional server process. The name of the game is density. Sure, it may be easy to manage and run a TG project, but it's a pain to set one up on a shared hosting server. Lastly, I personally think it has something to do with the fact that so many of the popular, free, web applications are PHP based. It's easy for the average Web Administrator to get started with your standard PHP package. From there, picking up the language is the next logical step. -Jeff On 7/25/07, walterbyrd wrote: > "Once you start down the Dark path, forever will it dominate your > desiny. Consume you, it will." > - Yoda > > I'm fairly new to web-development, and I'm trying out different > technologies. Some people wonder why PHP is so popular, when the > language is flawed in so many ways. To me, it's obvious: it's because > it's much easier to get started with PHP, and once somebody gets > started with a particular language, that person is likely to stay with > that language. > > Before you can even get started with Python web-development, you have > to understand this entire alphabit soup of: CGI, FASTCGI, MOD_PYTHON, > FLUP, WSGI, PASTE, etc. For me, configuring fastcgi has been the most > difficult part of getting django to work. PHP developers don't have to > bother with anything like that. With PHP, you just throw some code in > the middle of your html file. > > Also, PHP, and PHP frameworks, are supported everywhere. If you going > to use a PHP MVC framework, like codeignitor, you would have a hard > time finding a hoster that didn't support it - all you need is php4 > and mysql. Dollar-hosting, for $10 a year, should work just fine with > codeignitor. With codeignitor, just copy your files to whatever host, > and that's it, you're done. > > By contrast, the most popular Python frameworks have sky-high system > requirements. Take a look at the requirements and/or recomendations > for popular Python frameworks like Django, TurboGears, or CherryPy: > Apache 2.0, mod_python (latest version), fastcgi (at least), command > line access, PostgreSQL. And a lot of low-cost hosters don't support > Python at all. > > Don't get me wrong: I am not saying that PHP is better than Python for > web-development. But, I sometimes think that Python could learn a few > things from PHP. > > All JMHO, of course. > > -- > http://mail.python.org/mailman/listinfo/python-list > From jscrerar at compuserve.com Mon Jul 30 09:59:21 2007 From: jscrerar at compuserve.com (Jim) Date: 30 Jul 2007 06:59:21 -0700 Subject: Making Gridded Widgets Expandable Message-ID: <1185803688.860152.54210@x40g2000prg.googlegroups.com> Hi, I'm looking at page 548 of Programming Python (3rd Edition) by Mark Lutz. The following GUI script works with no problem, i.e., the rows and columns expand: ================================================================= # Gridded Widgets Expandable page 548 from Tkinter import * colors = ["red", "white", "blue"] def gridbox(root): Label(root, text = 'Grid').grid(columnspan = 2) r = 1 for c in colors: l = Label(root, text=c, relief=RIDGE, width=25) e = Entry(root, bg=c, relief=SUNKEN, width=50) l.grid(row=r, column=0, sticky=NSEW) e.grid(row=r, column=1, sticky=NSEW) root.rowconfigure(r, weight=1) r += 1 root.columnconfigure(0, weight=1) root.columnconfigure(1, weight=1) root = Tk() gridbox(Toplevel(root)) Button(root, text="Quit", command=root.quit).grid() mainloop() ================================================================= However, the following GUI script using class does not expand rows and columns: ================================================================= # Gridded Widgets Expandable 2 from Tkinter import * colors = ["red", "white", "blue"] class GUI(Frame): def __init__(self,master): Frame.__init__(self,master) self.grid() self.gridbox() def gridbox(self): Label(self, text = 'Grid').grid(columnspan = 2) r = 1 for c in colors: l = Label(self, text=c, relief=RIDGE, width=25) e = Entry(self, bg=c, relief=SUNKEN, width=50) l.grid(row=r, column=0, sticky=NSEW) e.grid(row=r, column=1, sticky=NSEW) self.rowconfigure(r, weight=1) r += 1 self.columnconfigure(0, weight=1) self.columnconfigure(1, weight=1) root = Tk() root.title("Gridded Widgets Expandable") app = GUI(root) Button(root, text="Quit", command=root.quit).grid() root.mainloop() ================================================================= What am I missing? Thanks, Jim From aleax at mac.com Sat Jul 7 14:30:30 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 7 Jul 2007 11:30:30 -0700 Subject: Unicode problem References: Message-ID: <1i0vp5u.1o9wpvx1avscguN%aleax@mac.com> pabloski at giochinternet.com wrote: ... Ah, I answered you on the Italian NG before seeing you had also posted the same request here. What I proposed there was (untested): import codecs _rimedi = { u'\x2019': "'" } def rimedia(exc): if isinstance(exc, (UnicodeEncodeError, UnicodeTranslateError)): erore = exc.object[exc.start:exc.end] if len(erore)==1 and erore in _rimedi: return _rimedi[erore] raise exc codecs.register_error('rimedia', rimedia) outf = codecs.open('filename.txt', 'w', 'iso-8859-15', errors='rimedia') Alex From dr.death.tm at gmail.com Tue Jul 3 11:51:30 2007 From: dr.death.tm at gmail.com (ddtm) Date: Tue, 03 Jul 2007 15:51:30 -0000 Subject: Python IRC bot using Twisted In-Reply-To: References: <1183470274.113508.308370@n60g2000hse.googlegroups.com> Message-ID: <1183477890.690319.182400@m36g2000hse.googlegroups.com> On 3 , 17:55, Jean-Paul Calderone wrote: > On Tue, 03 Jul 2007 13:44:34 -0000, ddtm wrote: > >On 3 , 16:01, Jean-Paul Calderone wrote: > > [snip] > > >Thank you very much! It's a very useful information. One more > >question: can I cancel the DelayedCall using its ID (it is returned > >from callLater(...)) from another function? In example bot there are > >two functions: > >def joined(self, channel): > > ... > >def privmsg(self, user, channel, msg): > > ... > >For example, I add callLater(...) to joined(...) function and I'd like > >to cancel this in privmsg(...) function. What should I do? > > Yep. The object callLater returns has a `cancel' method (some others, too) > which will prevent the function from being called at the scheduled time. > > Jean-Paul I know what you are talking about, but the question is: How can I cancel scheduled task in function that differs from function where I scheduled the task? Demo bot on Twisted website has a class with a bunch of predefined functions joined(...), privmsg(...) and so on. I can't see any method of communicating these functions. I'm new to Python and to Twisted framework. The task is: to call callLater(...) in joined(...) to cancel the task in privmsg(...) on special condition From rustompmody at gmail.com Fri Jul 20 23:52:32 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Sat, 21 Jul 2007 09:22:32 +0530 Subject: Pythonic way for missing dict keys In-Reply-To: References: Message-ID: Can someone who knows about python internals throw some light on why >>> x in dic is cheaper than >>> dic.has_key(x) ?? From oren.tsur at gmail.com Thu Jul 26 11:05:02 2007 From: oren.tsur at gmail.com (oren.tsur at gmail.com) Date: Thu, 26 Jul 2007 08:05:02 -0700 Subject: Parsing XML with ElementTree (unicode problem?) In-Reply-To: <46A8B0F1.1010405@web.de> References: <1185200976.082516.105420@57g2000hsv.googlegroups.com> <1185279975.254458.7510@57g2000hsv.googlegroups.com> <1185287404.060182.314750@57g2000hsv.googlegroups.com> <46A618E9.6010304@web.de> <1185449094.998635.67870@w3g2000hsg.googlegroups.com> <1185455621.498620.51650@i13g2000prf.googlegroups.com> <1185459815.871401.35320@b79g2000hse.googlegroups.com> <46A8B0F1.1010405@web.de> Message-ID: <1185462302.723199.43430@o61g2000hsh.googlegroups.com> On Jul 26, 4:34 pm, Stefan Behnel wrote: > oren.t... at gmail.com wrote: > > On Jul 26, 3:13 pm, John Machin wrote: > >> On Jul 26, 9:24 pm, oren.t... at gmail.com wrote: > > >>> OK, I solved the problem but I still don't get what went wrong. > >>> Solution - use tree builder in order to create the new xml file > >>> (previously I was "manually" creating it). > >>> I'm still curious so I'm adding a link to a short and very simple > >>> script that gets an xml (containing non ascii chars) from the web and > >>> saves some of the elements to 2 different local xml files - one is > >>> created by XMLWriter and the other is created manually. you could see > >>> that parsing of the first local file is OK while parsing of the > >>> "manually" created xml file fails. obviously I'm doing something wrong > >>> and I'd love to learn what. > >>> the toy script:http://staff.science.uva.nl/~otsur/code/xmlConversions.py > >> Simple file comparison: > > >> File 1: ... Modern Church. <p>The book ... > >> File 2: ... Modern Church.

    The book ... > > >> Firefox: > > >> XML Parsing Error: mismatched tag. Expected:

    . > >> Location: file:///C:/junk/myDeVinciCode166_2.xml > >> Line Number 3, Column 1153: > > >> The...Church.

    The...thrill. > >> ------------------------------------------^ > > > yup, but why does this happen - on the script side - I write the exact > > same strings, of content with supposedly, same encoding, so why the > > encoding is different? > > Read the mail. It's not the encoding, it's the "

    " which does not get > through as a tag in the first file. > > Stefan thanks. I guess it was a dumb question after all. thanks again :) From bignose+hates-spam at benfinney.id.au Thu Jul 19 19:00:57 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 20 Jul 2007 09:00:57 +1000 Subject: Converting between objects References: Message-ID: <87sl7km21i.fsf@benfinney.id.au> "Nathan Harmston" writes: > I have being thinking about this and was wondering with built in types > you can do things like > > float(1) Calls the constructor for the 'float' type, passing the integer 1; the constructor returns a new float object. > str(200) Calls the constructor for the 'str' type, passing the integer 200; the constructor returns a new str object. > is there way I can define conversion functions like this These are not "conversion functions"; they are the constructors of the corresponding types. You can hook into the instance creation by modifying the '__new__' method of the metaclass; but probably the easier way is to hook into the instance initialisation (after it is created) by modifying the '__init__' method of the class. > say i have a class A and a class B > > bobj = B() > aobj = a(bobj) > > in a neater way than just defining a set of methods > > def a(object_to_convert) > # if object_to_convert of type...... > # do some stuff > return A() Rather than this, define '__init__' to do some stuff to 'self', that is, modify attributes of the instance during its initialisation. The '__init__' method is automatically called during object initialisation and receives all the parameters that were passed to the constructor. class B(object): def __init__(self, obj): self.foo = do_stuff(obj) aobj = B(42) -- \ "Pinky, are you pondering what I'm pondering?" "Wuh, I think | `\ so, Brain, but if we didn't have ears, we'd look like weasels." | _o__) -- _Pinky and The Brain_ | Ben Finney From aleax at mac.com Wed Jul 18 22:38:01 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 18 Jul 2007 19:38:01 -0700 Subject: type conversions for comparison operators References: <1184795657.465264.257970@d30g2000prg.googlegroups.com> Message-ID: <1i1gox2.bm4msv4euum1N%aleax@mac.com> Russ wrote: > I recently discovered a bug in one of my programs that surprised me > because I thought Python's dynamic type checking would have > caught it. > > Suppose I have a function that returns an integer, such as > > def numItems: return len(self.items) Syntax errors (you need parentheses before the colon). > Now I want to do a test like this: > > if object.numItems() > 2: Attribute error (unless you've set that numItems "function" to be a _method_ of the class of "object" AND added a "self" argument). > But suppose I mistakenly leave off the parentheses: > > if object.numItems > 2: > > I would have thought that Python would choke on this, but it > doesn't. Apparently, Python converts the operands to a common > type, but that seems risky to me. Is there a good reason for allowing > a function to be compared to an integer? Thanks. It lets you sort a heterogeneous list which may include objects of many types (and no "conversion to a common type" is involved, btw). However, Guido's decided that Python 3.0 will not allow heterogeneous order-comparisons any more (they can't be removed in 2.* without breaking backwards compatibility -- 3.0 is allowed to break backwards compatibility, but 2.* isn't). Alex From bbxx789_05ss at yahoo.com Mon Jul 2 13:12:30 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 02 Jul 2007 10:12:30 -0700 Subject: subprocess -- broken pipe error Message-ID: <1183396350.429008.185200@n2g2000hse.googlegroups.com> Hi, Can someone explain what a broken pipe is? The following produces a broken pipe error: ---------- import subprocess as sub p = sub.Popen(["ls", "-al", "../"], stdin=sub.PIPE, stdout=sub.PIPE) print p.stdout.read() #outputs the files correctly p.stdin.write("ls\n") #IOError: [Errno 32] Broken pipe ----------- From qyetime at hushmail.com Sat Jul 28 17:50:42 2007 From: qyetime at hushmail.com (qyetime at hushmail.com) Date: Sat, 28 Jul 2007 14:50:42 -0700 Subject: http://MoneyCertain.com Message-ID: <1185659442.930599.73130@g4g2000hsf.googlegroups.com> http://MoneyCertain.com From gagsl-py2 at yahoo.com.ar Wed Jul 11 20:21:27 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Jul 2007 21:21:27 -0300 Subject: binascii.unhexlify ... not clear about usage, and output References: <1180511251.625790.280260@h2g2000hsg.googlegroups.com> <1184142108.846958.189080@k79g2000hse.googlegroups.com> <1184175983.898310.321630@q75g2000hsh.googlegroups.com> <5fkmdeF3cu82eU3@mid.uni-berlin.de> <1184186044.390255.20310@k79g2000hse.googlegroups.com> Message-ID: En Wed, 11 Jul 2007 17:34:04 -0300, mensanator at aol.com escribi?: > If only there was a built-in base 2 conversion. No builtin, but you can find uncountable versions if you search this group, or the Python cookbook, or the entire web... -- Gabriel Genellina From nick at craig-wood.com Thu Jul 5 16:30:07 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 05 Jul 2007 15:30:07 -0500 Subject: Callback scoping References: <1183662847.449011.26560@o61g2000hsh.googlegroups.com> Message-ID: Dan wrote: > So, I think I understand what python's scoping is doing in the > following situation: > >>> x = [ lambda: ind for ind in range(10) ] > > But, I'm wondering what is the easiest (and/or most pythonic) way to > get the behavior I want? (If you haven't guessed, I want a list of (no > parameter) functions, each of which returns its index in the list.) This is the traditional way :- >>> x = [ lambda ind=ind: ind for ind in range(10) ] >>> x[0]() 0 >>> x[2]() 2 >>> x[9]() 9 >>> -- Nick Craig-Wood -- http://www.craig-wood.com/nick From manlio_perilloNO at SPAMlibero.it Sun Jul 8 16:34:50 2007 From: manlio_perilloNO at SPAMlibero.it (Manlio Perillo) Date: Sun, 08 Jul 2007 20:34:50 GMT Subject: __unicode__ method for exception object References: <874pkfoj9i.fsf@benfinney.id.au> Message-ID: Il Sun, 08 Jul 2007 10:02:01 +1000, Ben Finney ha scritto: > Manlio Perillo writes: > >> I have just noticed that exception objects does not handle well Unicode >> arguments. > > This error is unrelated to the fact that you created an exception > object. > No, it is related. >> >>> e = RuntimeError(u'?????') >> >>> str(e) >> Traceback (most recent call last): >> File "", line 1, in ? >> UnicodeEncodeError: 'ascii' codec can't encode characters in position > > Your terminal has been detected as using the 'ascii' encoding, so while > that's true no attempt to output non-ASCII characters will work. > > You'll need to change whatever settings are on your terminal emulator so > that it is using an encoding (such as 'utf-8') which can display the > characters you want. This is not a problem with the terminal. And the problem is not with str(e) but with unicode(e). unicode(e) converts the exception argument to an Unicode object, but since no __unicode__ object is defined, it firsts calls the __str__ method (and this, of course, fails, since the default encoding in CPython is us-ascii) and then converts the result to an Unicode object using, again, the default encoding. Regards Manlio Perillo From exarkun at divmod.com Tue Jul 3 12:08:14 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 3 Jul 2007 12:08:14 -0400 Subject: Python IRC bot using Twisted In-Reply-To: <1183477890.690319.182400@m36g2000hse.googlegroups.com> Message-ID: <20070703160814.4947.1499835258.divmod.quotient.6423@ohm> On Tue, 03 Jul 2007 15:51:30 -0000, ddtm wrote: >On 3 , 17:55, Jean-Paul Calderone wrote: >> On Tue, 03 Jul 2007 13:44:34 -0000, ddtm wrote: >> >On 3 , 16:01, Jean-Paul Calderone wrote: >> > [snip] >> >> >Thank you very much! It's a very useful information. One more >> >question: can I cancel the DelayedCall using its ID (it is returned >> >from callLater(...)) from another function? In example bot there are >> >two functions: >> >def joined(self, channel): >> > ... >> >def privmsg(self, user, channel, msg): >> > ... >> >For example, I add callLater(...) to joined(...) function and I'd like >> >to cancel this in privmsg(...) function. What should I do? >> >> Yep. The object callLater returns has a `cancel' method (some others, too) >> which will prevent the function from being called at the scheduled time. >> >> Jean-Paul > >I know what you are talking about, but the question is: How can I >cancel scheduled task in function that differs from >function where I scheduled the task? Demo bot on Twisted website has a >class with a bunch of predefined functions joined(...), privmsg(...) >and so on. I can't see any method of communicating these functions. >I'm new to Python and to Twisted framework. >The task is: >to call callLater(...) in joined(...) >to cancel the task in privmsg(...) on special condition You need to preserve a reference to the object. For example: class IRCBot(Whatever): def joined(...): self.announceJoinedCall = reactor.callLater(...) def privmsg(...): self.announceJoinedCall.cancel() self.announceJoinedCall = None This skips over a bunch of details (what happens on multiple calls to joined, what happens if privmsg is called after announceJoinedCall has run, etc) but I hope it demonstrates the basic idea. Jean-Paul From bdesth.quelquechose at free.quelquepart.fr Thu Jul 12 23:02:28 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 13 Jul 2007 05:02:28 +0200 Subject: Lists in classes In-Reply-To: <1184255240.559017.61330@o61g2000hsh.googlegroups.com> References: <1184253811.052346.220470@22g2000hsm.googlegroups.com> <1184255240.559017.61330@o61g2000hsh.googlegroups.com> Message-ID: <46967a84$0$11778$426a74cc@news.free.fr> Alex Popescu a ?crit : (snip) > > You are defining the list in the class context and so it becomes a > class field/member. 'attribute' is the pythonic term. From martin at v.loewis.de Sun Jul 29 12:41:40 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 29 Jul 2007 18:41:40 +0200 Subject: Compiling 2.5.1 on OpenBSD 4.1 In-Reply-To: References: <46AC1B91.3070706@v.loewis.de> Message-ID: <46ACC344.1020701@v.loewis.de> > Thanks Martin. Did I mention this was OpenBSD 4.1 in the original post? Here's the patch: It may work, but I don't like it. Can you please try this one instead, and report whether it works? Thanks, Martin Index: configure =================================================================== --- configure (Revision 56599) +++ configure (Arbeitskopie) @@ -1388,6 +1388,14 @@ _ACEOF +# OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is +# also defined. This can be overridden by defining _BSD_SOURCE + +cat >>confdefs.h <<\_ACEOF +#define _BSD_SOURCE 1 +_ACEOF + + # The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables # u_int on Irix 5.3. Defining _BSD_TYPES brings it back. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 27 06:15:25 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 27 Jul 2007 12:15:25 +0200 Subject: Filtering content of a text file In-Reply-To: <1185528507.750436.91140@j4g2000prf.googlegroups.com> References: <1185528507.750436.91140@j4g2000prf.googlegroups.com> Message-ID: <46a9c5a5$0$9208$426a34cc@news.free.fr> Ira.Kovac at gmail.com a ?crit : > Hello All, > > I'd greatly appreciate if you can take a look at the task I need help > with. > > It'd be outstanding if someone can provide some sample Python code. No problem. It's 600 euro per day. Do I send you the contract ? > ------------------------------------------------------------------------------- > Problem > ------------------------------------------------------------------------------- > > I am working with 30K+ record datasets in flat file format (.txt) that > look like this: > > //-+alibaba sinage > //-+amra damian//_9 > //-+anix anire//_ > //-+borom > //-+bokima sun drane > //-+ciren > //-+cop calestieon eded > //-+ciciban > //-+drago kimano sole > > > The records start with the same string (in the example //-+) wich is > followed by another string of characters taht's changing from record > to record. > > I am working on one file at the time and for each file I need to be > able to do the following: > > a) By looping thru the file the program should isolate all records > that have letter a following the //-+ > b) The isolated dataset will contain only records that start with //- > +a > c) Save the isolated dataset as flat flat text file named a.txt > d) Repeat a), b) and c) for all letters of english alphabet (a thru z) > and numerical values (0 thru 9) > This really looks like homework, and asking people to do your homework for you is a pretty bad idea. On most newsgroup, the answer would stop here, but c.l.py is a very friendly place, so I'll give you a couple starting points: 1/ for char in "abc": print "char is %s" % char print "//-+%s" % char 2/ for line in open('somefile'): print line 3/ print "//-+alibaba sinage"[4:] 4/ print "//-+alibaba sinage"[4:].startswith('a') 5/ data = [] data.append("//-+alibaba sinage\n") data.append("//-+amra damian//_9\n") print "".join(data) 6/ f = open('someotherfile.txt', 'w') f.write("line1\nline2\nline3\n") f.close() This is all you need to know to complete your task. From Eric_Dexter at msn.com Mon Jul 9 19:30:25 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 09 Jul 2007 16:30:25 -0700 Subject: trouble controlling vim with subprocess on windows machine In-Reply-To: References: <1183970186.663847.4380@o61g2000hsh.googlegroups.com> Message-ID: <1184023825.646120.251060@d55g2000hsg.googlegroups.com> On Jul 9, 11:06 am, Josiah Carlson wrote: > Eric_Dex... at msn.com wrote: > > I am having trouble contolling vim with subprocess on a windows > > machine. It appears that vim comes up on the machine all right and it > > sometimes looks like it is doing the searchs what I am asking it to do > > but when I am asking it to load a file it doesn't do anything. Is > > there something I need to do to push the data through the pipe?? Here > > is a couple different ways I am trying to do it. > > [snip] > > This recipe for asynchronous communication using subprocess could be > used to write an expect-like tool: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 > > It works on both Windows and *nix. > > - Josiah I had the original dir work but when I tried to trade it out with vim it isn't clear how I should call it.. vim filename and it doesn't find filename for some reason. I called it pipe and then inport pipe def load_instrument3(instr_name, csd_name): if sys.platform == 'win32': shell, commands, tail = ('gvim' + csd_name, (csd_name, csd_name), '\r\n') else: shell, commands, tail = ('sh', ('ls', 'echo HELLO WORLD'), '\n') a = pipe.Popen(shell, stdin=pipe.PIPE, stdout=pipe.PIPE) print pipe.recv_some(a), for cmd in commands: pipe.send_all(a, csd_name) print pipe.recv_some(a), pipe.send_all(a, csd_name) print pipe.recv_some(a, e=0) a.wait() From duncan.booth at invalid.invalid Mon Jul 30 03:37:05 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Jul 2007 07:37:05 GMT Subject: Pythonic way for missing dict keys References: <1185041243.323915.161230@x40g2000prg.googlegroups.com> <87lkd0eprj.fsf@pobox.com> Message-ID: Steven D'Aprano wrote: > > Instead of doing: > > > if callable(function): function() > > you should do: > > try: > function() > except TypeError: > pass > > > 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_?) The replacement for callable(x) is simply hasattr(x, '__call__'). Once upon a time it may have been that functions didn't have a __call__ attribute (I haven't checked back on really old Pythons top see if this was the case), but these >> 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(). There are of course several replacements for specialised uses of reduce: sum, any, all. There is no general purpose replacement, but you can write one in a few lines if you really need it. > > It's a shame really. Oh well, maybe it will sneak back in via a > functional module, or itertools, or something. What a waste, what a > waste. I'm sure it will reappear in some other module, but that's the correct place for a little used function, not in builtins. From danb_83 at yahoo.com Thu Jul 26 19:28:27 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Thu, 26 Jul 2007 16:28:27 -0700 Subject: automatic type conversion for comparison operators In-Reply-To: <1185492177.836716.312390@q75g2000hsh.googlegroups.com> References: <1185492177.836716.312390@q75g2000hsh.googlegroups.com> Message-ID: <1185492507.670637.294310@o61g2000hsh.googlegroups.com> On Jul 26, 6:22 pm, Russ wrote: > I posted a message on this several days ago, but it apparently got > lost > in googlespace, so I'll try it again. > > I recently discovered a bug in my code that apparently resulted from > the automatic conversion of a function pointer to an integer. > > Say you have a class member function called getCount(), which > returns an integer. Now suppose you write something like > > if obj.getCount < 3: ... > > This is an error because the parentheses were left off. BTW, are you a former Pascal programmer? > But Python > somehow compares the function pointer with an integer without > complaining. Unless there is a darn good reason for allowing > comparisons of this type (and I can't think of one), I think > Python should flag this as an Exception. IIRC, the reason is for backwards compatibility with a long-obsolete version of Python in which it wasn't possible for __cmp__ to throw an exception. That's not darn good, so this behavior is already slated for removal in version 3.0. From deets at nospam.web.de Wed Jul 25 14:55:40 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 25 Jul 2007 20:55:40 +0200 Subject: code indentation In-Reply-To: <1185387723.155661.311510@b79g2000hse.googlegroups.com> References: <1185297657.186852.136950@k79g2000hse.googlegroups.com> <87lkd5jt83.fsf@benfinney.id.au> <1185357861.989194.117000@r34g2000hsd.googlegroups.com> <1185387723.155661.311510@b79g2000hse.googlegroups.com> Message-ID: <5gpklfF3hlo32U1@mid.uni-berlin.de> > HELLO, > > On this group I ask for serious help and now we talk about > communication. Then I you don't know how to help me then please DON'T > SAY ANYTHING Your lack of command of the python language and programming concepts in general is only excelled by your inabillity to react properly in a community of friendly people that try to point out how to behave as a human being instead of a complete jerk. And given your history of ignorance of sound advice, I think I'm not stressing my crystal ball to much if I predict: you won't receive much more help here. Diez From steven at REMOVE.THIS.cybersource.com.au Wed Jul 11 00:46:40 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 11 Jul 2007 04:46:40 GMT Subject: bool behavior in Python 3000? References: <7xzm23ygft.fsf@ruckus.brouhaha.com> Message-ID: On Tue, 10 Jul 2007 16:41:58 -0700, Paul Rubin wrote: > Steven D'Aprano writes: >> Pretending that False and True are just "magic names" for 0 and 1 might >> be "easier" than real boolean algebra, but that puts the cart before >> the horse. Functionality comes first: Python has lists and dicts and >> sets despite them not being ints, and somehow newcomers cope. I'm sure >> they will cope with False and True not being integers either. > > Are they are aren't they? I'm sorry, I can't parse that sentence. > print 1 in [True] > print 1 == True > print len(set(map(type, [1, 1]))) > print len(set(map(type, [1, True]))) But I guess that you are probably trying to make the point that True and False are instances of a _subtype_ of int rather than ints, under the mistaken idea that this pedantry would matter. (If this is not the case, then I apologize for casting aspersions.) However, you may notice that I said _integers_, which is not the same thing as ints: the Python types int and bool are both implementations of the mathematical "integer" or "whole number". -- Steven. From gherron at islandtraining.com Fri Jul 27 11:56:27 2007 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 27 Jul 2007 08:56:27 -0700 Subject: Imported globals? In-Reply-To: <81803fb516f0f2b111f0654f40adcf9d@tpu.ru> References: <81803fb516f0f2b111f0654f40adcf9d@tpu.ru> Message-ID: <46AA15AB.3050006@islandtraining.com> Valentina Vaneeva wrote: > Hi, > > I'm new to Python and I've found something in its interpreter that I > don't quite understand, and I don't really know how to correctly > formulate a search query. Here's the question. > > If we have a file module_a.py with the following content: > > | #!/usr/bin/env python > | > | value = 'initial' > | > | def change_value(): > | global value > | value = 'changed' > > and a file module_b.py: > > | #!/usr/bin/env python > | > | from module_a import value, change_value > | > | change_value() > | print value > > Then, if we run module_b.py, it will print "initial". However, if one > adds to the end of module_a.py this line: > > | change_value() > > The script module_b.py will print "changed". > > It seems that in the first case change_value() called in module_b.py > ignores the global statement. Is it so? Why? What happens in the second > case? I really don't get it. > In Python, there are not any truly "global" variables as you're thinking of them. Instead, each module has it's own global space. You are tripping over the fact that module_a and module_b have their own separate global spaces. The variable "value" is global in module_a, and "change_value" will always refer to that variable. However, in module_b, when you from module_a import value, change_value you have created two new variables global to module_b that references values from the other module. Now running change_value (which changes "value" in module_a has no affect on the version of "value" in module_b. Your print is then printing value from module_b -- the unchanged version. If you truly want to examine value in module_a, the you have to access it as import module_a module_a.change_value() print module_a.value You can do both import module_a from module_a import change_value but that's probably confusing and generally considered a bad idea. Ideas: 1 If you want module_a to manage such a global variable, you could include functions for getting, and setting it, as well as your function for changing it's value. 2. You could also dispense with use of global values -- various OOP techniques could help there. Gary Herron > Thanks! > > Cheers, > Valia > > From rustompmody at gmail.com Fri Jul 20 03:42:11 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Fri, 20 Jul 2007 13:12:11 +0530 Subject: Pickled objects over the network In-Reply-To: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com> References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com> Message-ID: Thats just what I was saying: If the IPC issues have been solved on your own terms but the data-serialization -- what you call making strings -- are not so satisfactory, you could use yaml (with safe_load) as a replacement for pickle and continue to use networking and IPC as you are currently doing. As I understand it the drop-in replacement for pickle is syck or pysyck which uses yaml internally. Ive not yet grokked what exactly is the relation between yaml and syck. Just to give a sense of the difference between yaml and pickle: >>> from pickle import dumps >>> from yaml import dump >>> l=[1,2,{'color':'blue', 'height': 5}] >>> print dump(l) - 1 - 2 - {color: blue, height: 5} >>> print dumps(l) (lp0 I1 aI2 a(dp1 S'color' p2 S'blue' p3 sS'height' p4 I5 sa. On 7/20/07, Walker Lindley wrote: > Right, I could use Pyro, but I don't need RPC, I just wanted an easy way to > send objects across the network. I'm sure both Pyro and Yami can do that and > I may end up using one of them. For the initial version pickle will work > because we have the networking issues figured out with it, just not the > security problem. So we may end up just sending strings back and forth that > will let us fill out an object's member variables on the other end. It's > much less cool, but it seems like it'd be more secure. > > > -Walker > > > On 7/19/07, Rustom Mody wrote: > > > > Irmen de Jong wrote > > > In what way would Pyro be overkill where Yaml (also a module that you > need > > > to install separately) wouldn't be? > > > > Sure they are the same to install and sure pyro can do the job (pyro > > is a nice package). > > > > But I got the impression that the questioner wanted to do the > > networking stuff himself at a low level (using sockets) and the data > > management using some available library -- pickle. > > > > Since pickle has problems > > -- does not interface well with networking > > -- security issues > > -- has an xml option that according to the docs is an order of magnitude > slower > > > > I thought I would point out yaml (with safe-load) which sits somewhere > > inbetween the xml-pickle and the default pickle. > > > > I should also mention here that I find yaml is much more known and > > used in the ruby and perl world than in the python world. This is > > unfortunate considering that both ruby and perl have a traditional > > syntax (begin end, { } etc ). On the other hand, python and yaml have > > similar modern syntactic structures -- structure follows indentation > > -- and are therefore well matched to each other. > > > > So in summary the 'competition' is not between yaml and pyro -- pyro > > could easily have a pickle-using-yaml option -- but between yaml and > > xml. > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > > > -- > 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. > -- > http://mail.python.org/mailman/listinfo/python-list > From nick at craig-wood.com Mon Jul 9 06:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 09 Jul 2007 05:30:04 -0500 Subject: trouble controlling vim with subprocess on windows machine References: <1183970186.663847.4380@o61g2000hsh.googlegroups.com> Message-ID: Eric_Dexter at msn.com wrote: > I am having trouble contolling vim with subprocess on a windows > machine. It appears that vim comes up on the machine all right and it > sometimes looks like it is doing the searchs what I am asking it to do > but when I am asking it to load a file it doesn't do anything. Is > there something I need to do to push the data through the pipe?? Here > is a couple different ways I am trying to do it. For controlling an interactive program subprocess isn't the right tool. Subprocess only really does one way communication - it isn't good at conversations. I'd suggest pexpect but it doesn't work on windows. You appear to be doing stuff with csound. There are several python modules out there which interface with csound - did you investigate those? -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 13 06:28:31 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 13 Jul 2007 12:28:31 +0200 Subject: bool behavior in Python 3000? In-Reply-To: References: Message-ID: <469753a5$0$26916$426a74cc@news.free.fr> Steven D'Aprano a ?crit : (snip) > It makes more sense to explicitly cast bools to ints s/cast bools to ints/build ints from bools/ AFAICT, there's no such thing as typecast in Python. From parvini_navid at yahoo.com Tue Jul 10 03:05:35 2007 From: parvini_navid at yahoo.com (Navid Parvini) Date: Tue, 10 Jul 2007 00:05:35 -0700 (PDT) Subject: standalone executables Message-ID: <450843.98906.qm@web54503.mail.re2.yahoo.com> Dear All, I need a reference to get all the programs which used to package Python programs into standalone executables files. Would you help me? Thank you in advance. Navid --------------------------------- Park yourself in front of a world of choices in alternative vehicles. Visit the Yahoo! Auto Green Center. -------------- next part -------------- An HTML attachment was scrubbed... URL: From glen.e.mettler at lmco.com Thu Jul 12 17:55:59 2007 From: glen.e.mettler at lmco.com (meg99) Date: Thu, 12 Jul 2007 14:55:59 -0700 Subject: New guy help with setup In-Reply-To: References: <1184275051.504507.116080@57g2000hsv.googlegroups.com> <1184275783.250640.327630@g4g2000hsf.googlegroups.com> Message-ID: <1184277359.397821.265290@m3g2000hsh.googlegroups.com> On Jul 12, 4:35 pm, Paul McNett wrote: > meg99 wrote: > > On Jul 12, 4:24 pm, Paul McNett wrote: > >> meg99 wrote: > >>> I just downloaded 2.5 and read the readme file. It says "Before you > >>> can build Python, you must first confiigure it....Start by running the > >>> script "./configure". > >>> I can't find "./configure" > >>> I am running Windows XP SP2 > >> You downloaded the wrong file. You want the Windows Installer:http://python.org/ftp/python/2.5.1/python-2.5.1.msi > > My applogies - I did download and install 2.5.1 > > In that case, open up your command window (Start|Run "cmd" ). > > Type 'python' at the c:\ prompt. > > Or, Start|All Programs|Python 2.5|IDLE > > Enjoy! > > -- > pkm ~http://paulmcnett.com I opened the command window and typed 'python' got 'not recognized as a command' went to the python25 folder and typed 'python' got the >>> prompt typed './configure' got 'no Python documentation found for './configure' meg99 From steve at holdenweb.com Mon Jul 2 18:12:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Jul 2007 18:12:25 -0400 Subject: subprocess -- broken pipe error In-Reply-To: <1183408472.222538.206800@57g2000hsv.googlegroups.com> References: <1183396350.429008.185200@n2g2000hse.googlegroups.com> <1183397577.959518.264230@g4g2000hsf.googlegroups.com> <1183403782.214378.270510@m36g2000hse.googlegroups.com> <1183408472.222538.206800@57g2000hsv.googlegroups.com> Message-ID: 7stud wrote: > On Jul 2, 2:12 pm, Steve Holden wrote: >> a) Who told you pipes should be unbuffered by default, and b) what difference >> does that make anyway? >> > > a) The docs. > > b) If the pipes were buffered then writing a small amount of data like > "text3" to the pipe would cause the other side to hang forever thereby > providing a possible explanation for the results. > >>> It just hangs, and then when I hit Ctrl+C and look in the file, the >>> data isn't in there. >> Of course it does, for the reasons mentioned above. file.read() only >> returns when it has consumed *all* the data from the file (which means >> the write must close the file for the reader to be able to return). >> > > That doesn't seem like a very good explanation, since the only thing > written to the file(i.e. stdin) was "text3", and the write() was > unbuffered, so the read() could consume all the data without the > write() closing the file--there was no more data. > [sigh]. So please explain how the receiving process mysteriously manages to look inside your producer process to know that it is never going to produce any more data. Let's (briefly) look at the docs for read(): """ read( [size]) Read at most size bytes from the file (less if the read hits EOF before obtaining size bytes). If the size argument is negative or omitted, read all data until EOF is reached. ... """ I believe you omitted the argument. As I have explained, the read() call therefore waits until the writer has closed the file. Which is what makes the EOF indication appear. And please stop dragging buffering into this as a red herring. You do know what buffering *is*, I take it? The read() call buffers even an unbuffered source, by definition. 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 alexandre.ferrieux at gmail.com Mon Jul 23 03:59:49 2007 From: alexandre.ferrieux at gmail.com (Alexandre Ferrieux) Date: Mon, 23 Jul 2007 00:59:49 -0700 Subject: Lazy "for line in f" ? In-Reply-To: <7xbqe3efm5.fsf@ruckus.brouhaha.com> References: <1185120650.412694.314280@o61g2000hsh.googlegroups.com> <1185143634.778056.227720@g4g2000hsf.googlegroups.com> <1185173778.656660.195650@n60g2000hse.googlegroups.com> <7xbqe3efm5.fsf@ruckus.brouhaha.com> Message-ID: <1185177589.837857.105390@r34g2000hsd.googlegroups.com> On Jul 23, 9:36 am, Paul Rubin wrote: > Alexandre Ferrieux writes: > > So I'll reiterate the question: *why* does the Python library add that > > extra layer of (hard-headed) buffering on top of stdio's ? > > readline? I know readline() doesn't have this problem. I'm asking why the file iterator does. -Alex From willmaier at ml1.net Thu Jul 19 05:36:56 2007 From: willmaier at ml1.net (Will Maier) Date: Thu, 19 Jul 2007 04:36:56 -0500 Subject: Log Memory Usage In-Reply-To: <20070719093556.GO12728@lass.lfod.us> References: <20070719093556.GO12728@lass.lfod.us> Message-ID: <20070719093656.GP12728@lass.lfod.us> On Thu, Jul 19, 2007 at 04:35:56AM -0500, Will Maier wrote: > On Thu, Jul 19, 2007 at 09:52:36AM +0100, Robert Rawlins - Think Blue wrote: > > I have a scheduled event which occurs every minute, i just need a > > code solution to give me the systems current memory consumptions > > details, is there perhaps something in the os module? > > I don't know of anything in the standard library that does this sort > of thing. Instead, you'll probably need to rely on your system's > tools. sysstat is available on Linux and provides the sar(1) command > for examining logs of various system attributes. The tool to use > depends on the system you're running. The other obvious approach would be to profile[0] your Python application. [0] http://docs.python.org/lib/profile.html -- [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] From hari.siri74 at gmail.com Wed Jul 11 20:35:28 2007 From: hari.siri74 at gmail.com (hari.siri74 at gmail.com) Date: Thu, 12 Jul 2007 00:35:28 -0000 Subject: socket programming related. In-Reply-To: <1184200362.261465.125810@w3g2000hsg.googlegroups.com> References: <1184200362.261465.125810@w3g2000hsg.googlegroups.com> Message-ID: <1184200528.163653.143670@m3g2000hsh.googlegroups.com> On Jul 11, 7:32 pm, hari.sir... at gmail.com wrote: > I have just started working in network programming using python. > written code for socket connection between client and server. Client > sent data to server for server processing (also server echoing back > rcvd data to client). When there is ("if no data": break ) no data > from client then the while loops break in server. The server program > process recvd data and my requirement is to send back the *results* to > client program for user sake. I did many trials but no use, as these > socket calls are blocking, i could not make my req. I just need to add a line. The while loop in server breaks when the sockObj.close() happens in client program indicating there is no data from client. From rrr at ronadam.com Fri Jul 20 11:35:51 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 20 Jul 2007 10:35:51 -0500 Subject: Break up list into groups In-Reply-To: <1184859881.860066.198940@e16g2000pri.googlegroups.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> <1184694533.380918.169640@m37g2000prh.googlegroups.com> <469D09CC.3080402@ronadam.com> <9e95df10707171408k2dfc8e08wd4056b80fcbe309b@mail.gmail.com> <1184859881.860066.198940@e16g2000pri.googlegroups.com> Message-ID: <46A0D657.9030306@ronadam.com> Matimus wrote: > Excellent work! One more modification and I get below 10us/pass: > > def getgroups(seq): > groups = [] > push = groups.append > iseq = iter(xrange(len(seq))) > for start in iseq: > if seq[start] & 0x80: > for stop in iseq: > if seq[stop] & 0x80: > push(seq[start:stop]) > start = stop > push(seq[start:]) > return groups > > -Matt Looks good to me. :-) So a generator versions would be... (not tested) def getgroups(seq): iseq = iter(xrange(len(seq))) for start in iseq: if seq[start] & 0x80: for stop in iseq: if seq[stop] & 0x80: yield seq[start:stop] start = stop yield seq[start:] (I also wanted to compare this to Georges solution, maybe later.) Now if there is some way to generalize this so it can be used in a broader range of situations without loosing too much of it's efficiency. Of course then maybe group by would be better. Cheers, Ron From mensanator at aol.com Sat Jul 14 21:12:07 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sat, 14 Jul 2007 18:12:07 -0700 Subject: Fastest way to convert a byte of integer into a list In-Reply-To: <1184453355.853001.5510@57g2000hsv.googlegroups.com> References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> <1184321842.921823.317470@k79g2000hse.googlegroups.com> <1184359588.648337.24830@m3g2000hsh.googlegroups.com> <1184453355.853001.5510@57g2000hsv.googlegroups.com> Message-ID: <1184461927.888285.47100@k79g2000hse.googlegroups.com> On Jul 14, 5:49?pm, Paul McGuire wrote: > On Jul 13, 3:46 pm, "mensana... at aol.com" wrote: > > > > > > > On Jul 13, 5:17 am, Paul McGuire wrote: > > > > On Jul 12, 5:34 pm, Godzilla wrote: > > > > > Hello, > > > > > I'm trying to find a way to convert an integer (8-bits long for > > > > starters) and converting them to a list, e.g.: > > > > > num = 255 > > > > numList = [1,1,1,1,1,1,1,1] > > > > > with the first element of the list being the least significant, so > > > > that i can keep appending to that list without having to worry about > > > > the size of the integer. I need to do this because some of the > > > > function call can return a 2 lots of 32-bit numbers. I have to find a > > > > way to transport this in a list... or is there a better way? > > > > Standing on the shoulders of previous posters, I put this together. > > > > -- Paul > > > But aren't we moving backwards? The OP did ask for the fastest way. > > > I put this together (from other posters and my own): > > > import gmpy > > import time > > > y = 2**177149 - 1 > > > # init list of tuples by byte > > bytebits = lambda num : [num >> i & 1 for i in range(8)] > > bytes = [ tuple(bytebits(i)) for i in range(256) ] > > # use bytes lookup to get bits in a 32-bit integer > > bits = lambda num : sum((bytes[num >> i & 255] for i in range(0,32,8)), > > ()) > > # use base-2 log to find how many bits in an integer of arbitrary > > length > > from math import log,ceil > > log_of_2 = log(2) > > numBits = lambda num : int(ceil(log(num)/log_of_2)) > > # expand bits to integers of arbitrary length > > arbBits = lambda num : sum((bytes[num >> i & 255] for i in > > range(0,numBits(num),8)),()) > > t0 = time.time() > > L = arbBits(y) > > t1 = time.time() > > print 'Paul McGuire algorithm:',t1-t0 > > > t0 = time.time() > > L = [y >> i & 1 for i in range(177149)] > > t1 = time.time() > > print ' Matimus algorithm:',t1-t0 > > > x = gmpy.mpz(2**177149 - 1) > > t0 = time.time() > > L = [gmpy.getbit(x,i) for i in range(177149)] > > t1 = time.time() > > print ' Mensanator algorithm:',t1-t0 > > > ## Paul McGuire algorithm: 17.4839999676 > > ## Matimus algorithm: 3.28100013733 > > ## Mensanator algorithm: 0.125 > > Oof! Pre-calculating those byte bitmasks doesn't help at all! It > would seem it is faster to use a single list comp than to try to sum > together the precalcuated sublists. > > I *would* say though that it is somewhat cheating to call the other > two algorithms with the hardcoded range length of 177149, when you > know this is the right range because this is tailored to fit the input > value 2**177149-1. This would be a horrible value to use if the input > number were something small, like 5. I think numBits still helps here > to handle integers of arbitrary length (and only adds a slight > performance penalty since it is called only once). I agree. But I didn't want to compare your numBits against gmpy's numdigits() which I would normally use. But since the one algorithm required a hardcoded number, I thought it best to hardcode all three. I originally coded this stupidly by converting the number to a string and then converting to a list of integers. But Matimus had already posted his which looked a lot better than mine, so I didn't. But then I got to wondering if Matimus' solution requires (B**2+B)/2 shift operations for B bits. My attempt to re-code his solution to only use B shifts didn't work out and by then you had posted yours. So I did the 3-way comparison using gmpy's direct bit comparison. I was actually surprised at the difference. I find gmpy's suite of bit manipulation routines extremely valuable and use them all the time. That's another reason for my post, to promote gmpy. It is also extremely important to keep coercion out of loops. In other words, never use literals, only pre-coerced constants. For example: import gmpy def collatz(n): ONE = gmpy.mpz(1) TWO = gmpy.mpz(2) TWE = gmpy.mpz(3) while n != ONE: if n % TWO == ONE: n = TWE*n + ONE else: n = n/TWO collatz(gmpy.mpz(2**177149-1)) > > -- Paul From researchbase at gmail.com Thu Jul 12 15:54:24 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Fri, 13 Jul 2007 01:24:24 +0530 Subject: inspite of proper package structure, no module named xyz error. Message-ID: hello all, can some one suggest me the best solution for a package? I have a package folder called idm and there are the following files in there. __init__.py which is right now empty. mainwindow.py which has a single class called MainWindow which is an MDI Parent frame from wxpython. student.py which is a child frame which gets called from the main menu. exam.py, another child frame. now when I try to run mainwindow.py file with the "import idm"statement, I get the following error. no module named idm. what could be the problem? I have imported all the necessary modules in mainwindow. kindly help. regards, Krishnakant. From bignose+hates-spam at benfinney.id.au Wed Jul 25 02:52:35 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 25 Jul 2007 16:52:35 +1000 Subject: idiom for RE matching References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> <1185157313.356112.159020@z24g2000prh.googlegroups.com> <2f6dnUlUxd2_7TjbnZ2dnUVZ_qy3nZ2d@comcast.com> Message-ID: <876449j7po.fsf@benfinney.id.au> Gordon Airporte writes: > I did already find that it speeds things up to pre-test a line like > > if 'bets' or 'calls' or 'raises' in line: > run the appropriate re's > > which isn't very pretty at all Nor does it work the way you might suppose: >>> line = "foo calls" >>> if 'bets' or 'calls' or 'raises' in line: ... print "Yes" ... Yes >>> line = "spam eggs" >>> if 'bets' or 'calls' or 'raises' in line: ... print "Yes" ... Yes Hint: the expression being evaluated for the 'if' statement above is equivalent to: if (('bets') or ('calls') or ('raises' in line)): print "Yes" -- \ "An eye for an eye would make the whole world blind." -- | `\ Mahatma Gandhi | _o__) | Ben Finney From philr at aspexconsulting.co.nz Wed Jul 11 16:44:19 2007 From: philr at aspexconsulting.co.nz (Phil Runciman) Date: Thu, 12 Jul 2007 08:44:19 +1200 Subject: S2K DTS and Python In-Reply-To: <1184093190.699539.260600@22g2000hsm.googlegroups.com> References: <1184093190.699539.260600@22g2000hsm.googlegroups.com> Message-ID: -----Original Message----- From: stefaan [mailto:stefaan.himpe at gmail.com] Sent: Wednesday, 11 July 2007 6:47 a.m. To: python-list at python.org Subject: Re: S2K DTS and Python > > However, I now want to update some tables in MSAccess, and it occurred > > to me that because Sequel Server 2000 DTS can interface with scripting > > languages that maybe I could call my first Python program from within > > DTS and then update the tables using DTS. (I am learning DTS hence the > > idea). I have never heard about DTS, so I cannot advise you on that. But since you mentioned MsAccess, I want to mention that I have successfully used the DejaVu object relational mapper[1] to access MsAccess databases. Other ORMs like SqlObject and SqlAlchemy - to the best of my knowledge - do not support MsAccess out of the box (yet?). [1] http://projects.amor.org/docs/dejavu/1.5.0RC1/ Thanks for your reply Stefaan. I will file away that information. It looks useful. From lance at augustmail.com Tue Jul 10 12:40:46 2007 From: lance at augustmail.com (Lance Hoffmeyer) Date: Tue, 10 Jul 2007 16:40:46 GMT Subject: win32com ppt embedded object Message-ID: Hey all, I am trying to create some python code to edit embedded ppt slides and need some help. import win32com.client from win32com.client import constants import re import codecs,win32com.client import time import datetime import win32com.client.dynamic ###################################################### ############ VARIOUS VARIABLES TO SET ################ path = "C:\temp/" ###################################################### ###################################################### PPT=win32com.client.Dispatch("PowerPoint.Application") WB=PPT.Presentations.Open(path + "File.ppt") PPT.Visible=1 PPTSLIDE= 29 for Z in WB.Slides(29).Shapes: if (Z.Type== 7): ZZ=Z.OLEFormat.Object WSHEET = ZZ.Worksheets(1) WSHEET.Range("A1").Value = .50 WSHEET.Range("A1").NumberFormat="0%" Gives error: Traceback (most recent call last): File "P:\Burke\TRACKERS\Ortho-McNeil\04 2007, 04-10 WAVE 4\Automation\Document1.py", line 23, in ? WSHEET = ZZ.Worksheets(1) File "C:\Program Files\Python\lib\site-packages\win32com\client\dynamic.py", line 489, in __getattr__ raise AttributeError, "%s.%s" % (self._username_, attr) AttributeError: .Worksheets Tool completed with exit code 1 Why is ZZ unknown and how to I correct this? Thanks in advance, Lance From bbxx789_05ss at yahoo.com Sun Jul 29 12:37:38 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 29 Jul 2007 09:37:38 -0700 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1185703671.241103.124780@g12g2000prg.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> <1184458002.961657.267830@x35g2000prf.googlegroups.com> <1184466882.446791.127670@x35g2000prf.googlegroups.com> <1185658013.859359.47700@57g2000hsv.googlegroups.com> <1185703671.241103.124780@g12g2000prg.googlegroups.com> Message-ID: <1185727058.306635.203130@b79g2000hse.googlegroups.com> On Jul 29, 4:07 am, Graham Dumpleton wrote: > Have you got an appropriate LoadModule directive in Apache > configuration to load the mod_python module? That you get this error > is indicative of mod_python module not being loaded. You can check the > Apache error logs to see if mod_python got loaded. > > See: > > http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking > > for more help on debugging. > That article says the LoadModule directive should be: >LoadModule python_module libexec/mod_python.so I saw this note in /Library/Apache2/conf/http.conf # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so "logs/foo.log" # with ServerRoot set to "/Library/Apache2" will be interpreted by the # server as "/Library/Apache2/logs/foo.log". I have this server root in /Library/Apache2/conf/httpd.conf: ServerRoot "/Library/Apache2" So in the Load Module directive, the actual path to the mod_python.so file is: /Library/Apache2/libexec/mod_python.so But I checked and I don't have a /Library/Apache2/libexec directory. From horpner at yahoo.com Mon Jul 30 07:24:05 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 30 Jul 2007 11:24:05 GMT Subject: Hex editor display - can this be more pythonic? References: Message-ID: On 2007-07-30, Dennis Lee Bieber wrote: > On Sun, 29 Jul 2007 18:30:22 -0700, CC > declaimed the following in comp.lang.python: > >> >> Yeah, with this I'm not that concerned about Windows. Though, can WinXP >> still load the ansi.sys driver? >> > I'm actually not sure... > > I think if one uses the 16-bit command parser it is available, but > not the 32-bit parser... > > command.com vs cmd.exe Yes. You can load the ansi.sys driver in command.com on Windows 2000 and XP, and it will work with simply batch files. But it doesn't work with Python, for reasons I don't know enough about Windows console programs to understand. -- Neil Cerutti The audience is asked to remain seated until the end of the recession. --Church Bulletin Blooper From josiah.carlson at sbcglobal.net Wed Jul 25 02:42:15 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Wed, 25 Jul 2007 06:42:15 GMT Subject: decorators tutorials In-Reply-To: <1185192282.331334.213730@x35g2000prf.googlegroups.com> References: <1185178383.499234.299850@z24g2000prh.googlegroups.com> <1185180112.321457.73170@n2g2000hse.googlegroups.com> <1185183257.471106.318070@x35g2000prf.googlegroups.com> <46a48245$0$19544$426a34cc@news.free.fr> <1185192282.331334.213730@x35g2000prf.googlegroups.com> Message-ID: james_027 wrote: > hi bruno, > > That seems to be hard to read at all, or I am just very new to python? No, it's hard to read. Note that it's not, technically, necessary to use nested functions to get the same results as a particular decorator. For example, earlier you provided... def check_login(func): def _check_login(*args): print "I am decorator" return func(*args) return _check_login That could be written as... class check_login: def __init__(self, func): self.func = func def __call__(self, *args): print "I am decorator" return self.func(*args) The latter class-based method is a bit clunkier, but I find that it's easier to understand and unravel after the fact (you can also add your own __repr__ method for useful introspection). > With that decorator how do I take advantage of it compare when I just > write a function that could do the same as what the decorator did? I > could translate the could from above into ... > > def check_login(msg): > #... > def my_func(toto, tata): > #... > > #call it like this > check_login('msg') > my_func('toto', 'tata') There are many uses for decorators (I'm sure others have posted about them already), and really, the syntax is a convenience meant to reduce the number of times you need to type the same string... @long_decorator def realy_long_function_name(): ... rather than... def realy_long_function_name(): ... realy_long_function_name = long_decorator(realy_long_function_name) I try to limit my use of decorators whenever possible, both because I still have to support Python 2.3 (which doesn't support the syntax), and because I find that they obfuscate what the code is doing more often than not. I will admit that they are useful as a metaprogramming technique. Just be careful. - Josiah From gagsl-py2 at yahoo.com.ar Mon Jul 16 14:06:45 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jul 2007 15:06:45 -0300 Subject: Discover instance variables References: <1184606748.599294.293570@n60g2000hse.googlegroups.com> Message-ID: En Mon, 16 Jul 2007 14:25:48 -0300, JonathanB escribi?: > Ok, I know there has to be a way to do this, but my google-fu fails me > (once more). I have a class with instance variables (or should they be > called attributes, I'm newish to programming and get really confused > with OO sometimes), like the one in this example: > > class Foo(): > self.a = "bar" > self.z = "test" > self.var = 2 > > foo = Foo() > > I want to print a list of the variables (strings, integers, etc) in > Foo, without knowing their names. So that the user who needs to change > a peice of information can view the variable list, enter the name of > the variable they need to change and then make the change. This is You should define more precisely *which* attributes do you actually want in the list, but I think this may serve as a starting point: py> def get_attributes(obj): ... return [attr for attr in dir(obj) if not attr.startswith('_') and ... type(getattr(obj,attr)) in ( ... int,str,unicode,float,dict,list,tuple)] ... py> f=open("c:\\test.py") py> get_attributes(f) ['mode', 'name', 'softspace'] The list keeps only the types explicitely enumerated. Other types are excluded, as well as names starting with "_". Another criterion would be `not attr.startswith('_') and not callable(getattr(obj,attr))` -- Gabriel Genellina From w3 at w3.com Thu Jul 19 15:29:35 2007 From: w3 at w3.com (W3) Date: Thu, 19 Jul 2007 15:29:35 -0400 Subject: Pure Python equivalent of unix "file" command? Message-ID: <2007071915293516807-w3@w3com> Hi all, Just a quick one... Is there such a thing? Thanks, /Walter -- From marco at sferacarta.com Wed Jul 25 09:21:33 2007 From: marco at sferacarta.com (Marco Mariani) Date: Wed, 25 Jul 2007 15:21:33 +0200 Subject: Pickled objects over the network In-Reply-To: References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com><011401c7caa0$3e3e5900$03000080@hendrik> <012901c7cb60$5ba530c0$03000080@hendrik> <00c601c7cc38$d826ba00$03000080@hendrik> <00bd01c7ccf6$8fa62540$03000080@hendrik> Message-ID: Hendrik van Rooyen ha scritto: > But more seriously - is there any need for a simple serialiser that will > be able to be used to transfer a subset of the built in types over an > open network in a safe manner, for the transfer of things like lists of > parameters? Yes, there seems to be a need for XML/YAML/JSON :-) From mensanator at aol.com Wed Jul 11 13:46:23 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Wed, 11 Jul 2007 10:46:23 -0700 Subject: binascii.unhexlify ... not clear about usage, and output In-Reply-To: <1184142108.846958.189080@k79g2000hse.googlegroups.com> References: <1180511251.625790.280260@h2g2000hsg.googlegroups.com> <1184142108.846958.189080@k79g2000hse.googlegroups.com> Message-ID: <1184175983.898310.321630@q75g2000hsh.googlegroups.com> On Jul 11, 3:21 am, Vishal wrote: > On May 30, 1:31 pm, Peter Otten <__pete... at web.de> wrote: > > > > > > > Vishal wrote: > > > I have a file with a long list of hex characters, and I want to get a > > > file with corresponding binary characters > > > > here's what I did: > > > >>>> import binascii > > >>>> f1 = 'c:\\temp\\allhex.txt' > > >>>> f2 = 'c:\\temp\\allbin.txt' > > >>>> sf = open(f1, 'rU') > > >>>> df = open(f2, 'w') > > >>>> slines = sf.readlines() > > >>>> for line in slines: > > > ... x = line.rstrip('\n') > > > ... y = binascii.unhexlify(x) > > > ... df.write(y) > > > ... > > >>>> df.close() > > >>>> sf.close() > > > Your code is OK, but you have to open f2 in binary mode if your data is > > truly binary (an image, say). > > > > But what I get is all garbage, atleast textpad and notepad show that > > > I tried doing it for only one string, and this is what I am seeing on > > > the interpreter: > > > >>>> x > > > '0164' > > >>>> y > > > '\x01d' > > > > I was expecting 'y' would come out as a string with binary > > > characters!!! > > > What are "binary characters"? > > > > What am i missing here? Can someone please help. > > > What /exactly/ did you expect? Note that "\x01d" and "\x01\x64" are just > > different renderings of the same string chr(0x01) + chr(0x64). > > > Peter > > Thanks Peter for the explanation. Actually what I want is: > > if Input is 0x0164, Output should be: 0000000101100100 > where each nibble is separated and the output appears in terms of '0's > and '1's. > > Can I do that with this function binascii.unhexlify()??? You can with gmpy: >>> import gmpy >>> x = 0x0164 >>> s = gmpy.digits(x,2) # convert to base 2 >>> y = '0'*(16-len(s)) + s # pad to 16 bits >>> y '0000000101100100' > > Thanks and best regards, > Vishal From josiah.carlson at sbcglobal.net Mon Jul 9 12:06:17 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Mon, 09 Jul 2007 09:06:17 -0700 Subject: trouble controlling vim with subprocess on windows machine In-Reply-To: <1183970186.663847.4380@o61g2000hsh.googlegroups.com> References: <1183970186.663847.4380@o61g2000hsh.googlegroups.com> Message-ID: Eric_Dexter at msn.com wrote: > I am having trouble contolling vim with subprocess on a windows > machine. It appears that vim comes up on the machine all right and it > sometimes looks like it is doing the searchs what I am asking it to do > but when I am asking it to load a file it doesn't do anything. Is > there something I need to do to push the data through the pipe?? Here > is a couple different ways I am trying to do it. [snip] This recipe for asynchronous communication using subprocess could be used to write an expect-like tool: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 It works on both Windows and *nix. - Josiah From bdesth.quelquechose at free.quelquepart.fr Thu Jul 19 00:29:59 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 19 Jul 2007 06:29:59 +0200 Subject: Pythonic way for missing dict keys In-Reply-To: References: Message-ID: <46a20f0b$0$27858$426a74cc@news.free.fr> Alex Popescu a ?crit : > Hi all! > > I am pretty sure this has been asked a couple of times, but I don't seem > to find it on the archives (Google seems to have a couple of problems > lately). > > I am wondering what is the most pythonic way of dealing with missing > keys and default values. > > According to my readings one can take the following approaches: > > 1/ check before (this has a specific name and acronym that I haven't > learnt yet by heart) > > if not my_dict.has_key(key): > my_obj = myobject() > my_dict[key] = my_obj > else: > my_obj = my_dict[key] if key not in my_dict: my_obj = my_dict[key] = myobject() else: my_obj = my_dict[key] > 2/ try and react on error (this has also a specific name, but...) > > try: > my_obj = my_dict[key] > except AttributeError: > my_obj = myobject() > my_dict[key] = my_obj cf above for a shortcut... > 3/ dict.get usage: > > my_obj = my_dict.get(key, myobject()) Note that this last one won't have the same result, since it won't store my_obj under my_dict[key]. You'd have to use dict.setdefault : my_obj = my_dict.setdefault(key, myobject()) > I am wondering which one is the most recommended way? It depends on the context. wrt/ 1 and 2, use 1 if you expect that most of the time, my_dict[key] will not be set, and 2 if you expect that most of the time, my_dict[key] will be set. > get usage seems > the clearest, but the only problem I see is that I think myobject() is > evaluated at call time, Myobject will be instanciated each time, yes. > and so if the initialization is expensive you > will probably see surprises. No "surprise" here, but it can indeed be suboptimal if instanciating myobject is costly. From zentraders at gmail.com Fri Jul 20 15:39:39 2007 From: zentraders at gmail.com (Zentrader) Date: Fri, 20 Jul 2007 19:39:39 -0000 Subject: Efficiently removing duplicate rows from a 2-dimensional Numeric array In-Reply-To: References: <76EEE12626B7A84EBACE67EC513AE53D060F8CE9@WIN-MSG-20.wingroup.windeploy.ntdev.microsoft.com> Message-ID: <1184960379.633837.28510@e16g2000pri.googlegroups.com> On Jul 19, 8:35 pm, "Terry Reedy" wrote: > "Alex Mont" wrote in message > I have a 2-dimensional Numeric array with the shape (2,N) and I want to > remove all duplicate rows from the array. For example if I start out > with: > [[1,2], > [1,3], > [1,2], > [2,3]] > > I want to end up with > [[1,2], > [1,3], > [2,3]]. Converting to a set is the best way to go. You can convert [1, 2] to something like "001002" and use that if you first locate, or already know the largest number. The brute force way is to loop through the list and compare this sub-list with list[N+1], then list[N+2], to the end of the list. If not found then append to a second list. From mail at microcorp.co.za Fri Jul 20 02:40:03 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 20 Jul 2007 08:40:03 +0200 Subject: Real-time Update References: <1184747090.102324.265230@i13g2000prf.googlegroups.com> <1i1hmwc.8aomfq13e95mpN%aleax@mac.com> Message-ID: <011301c7caa0$3d9e2160$03000080@hendrik> "Alex Martelli" wrote: > Hendrik van Rooyen wrote: > > > there is a recipe for this sort of thing, but I keep losing links. > > . > thanks - but its probably no use - I predict I will lose this too... : - ) - Hendrik From miki.tebeka at gmail.com Thu Jul 12 09:48:06 2007 From: miki.tebeka at gmail.com (Miki) Date: Thu, 12 Jul 2007 13:48:06 -0000 Subject: web page text extractor In-Reply-To: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> References: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> Message-ID: <1184248086.912636.254980@q75g2000hsh.googlegroups.com> Hello jk, > For a project, I need to develop a corpus of online news stories. I'm > looking for an application that, given the url of a web page, "copies" > the rendered text of the web page (not the source HTNL text), opens a > text editor (Notepad), and displays the copied text for the user to > examine and save into a text file. Graphics and sidebars to be > ignored. The examples I have come across are much too complex for me > to customize for this simple job. Can anyone lead me to the right > direction? Going simple :) from os import system from sys import argv OUTFILE = "geturl.txt" system("lynx -dump %s > %s" % (argv[1], OUTFILE)) system("start notepad %s" % OUTFILE) (You can find lynx at http://lynx.browser.org/) Note the removing sidebars is a very difficult problem. Search for "wrapper induction" to see some work on the subject. HTH, -- Miki http://pythonwise.blogspot.com From http Fri Jul 20 06:13:19 2007 From: http (Paul Rubin) Date: 20 Jul 2007 03:13:19 -0700 Subject: code packaging Message-ID: <7xfy3jpem8.fsf_-_@ruckus.brouhaha.com> I've been through this kind of thing a few times in the past and received excellent advice here on clpy about how to deal with specific technical aspects (e.g. how to use setuptools, InnoSetup, etc). I'm now wondering where this type of thing is best addressed in more general terms. What I usually see happening, in projects I've worked on and in others, is that developers get the code working on their own computers, using source control tools and (if we're lucky) tests developed in parallel with the code, but without much attention to final packaging until the very end when the code is about to be shipped. Is this appropriate? Inappropriate? Do your projects start using serious packaging and distribution tools very early in development, before the code is anywhere near usable? Should they? I'm involved in something that I wish was that way, mainly because I really don't have any way to put a complete installation on my own computers; I have to develop my subsystem more or less independently of the overall app, then toss stuff over the wall to the more central application guys for integration, which gets slow sometimes because we're distributed all over. This is a fairly complex server app that depends on a lot of external packages and programs running across multiple machines, so I could see the packaging problem being messy. It would cause a significant interruption in development to try to package things so that the non-central developers could install and hack it without a lot of assistance. But I think it would be worthwhile given how much easier it would become to test changes. We do plan to bundle up and release the code sometime (maybe as a Debian package) but for now that's deferred until the code is more complete and stable. I'm wondering how other projects go about this. From mail at timgolden.me.uk Tue Jul 10 03:57:49 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 10 Jul 2007 08:57:49 +0100 Subject: S2K DTS and Python In-Reply-To: References: Message-ID: <46933BFD.2040606@timgolden.me.uk> Phil Runciman wrote: > I am a Python newbie so please be gentle on me. Welcome to Python. > I have created a program that takes text files within a directory and it > successfully parses the information from them to create 3 CSV files. Good so far. > However, I now want to update some tables in MSAccess, and it occurred > to me that because Sequel Server 2000 DTS can interface with scripting > languages that maybe I could call my first Python program from within > DTS and then update the tables using DTS. (I am learning DTS hence the > idea). Unless you *really* wanted to learn DTS (and I don't find it that useful myself) then simply do this through Python... and have some fun at the same time :) > My questions are: > > Has anyone used Python within DTS? Haven't, but I wouldn't even try. Unless I were constrained by some kind of contractual binding, I wouldn't even *start* using DTS if I could use Python. I find it far too opaque. > Am I off the wall trying such a thing? No, but I think it's easier to use the csv module, pyodbc [1] and either code the SQL directly, which is what I tend to do, or use one of the several SQL-ORM-style wrappers around: SQLObject[2], sqlalchemy[3] and its friend Elixir[4], or the newly-advertised Storm[5] from Canonical. Feel free to post back with questions or progress. TJG [1] http://pyodbc.sf.net [2] http://www.sqlobject.org/ [3] http://sqlalchemy.org [4] http://elixir.ematia.de/ [5] https://storm.canonical.com/ From bignose+hates-spam at benfinney.id.au Mon Jul 9 19:40:33 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 10 Jul 2007 09:40:33 +1000 Subject: Broken MUA interactions References: <1183498045.092504.229250@m36g2000hse.googlegroups.com> <94ccbe710707071511o3beee718wc12f15082b3c6e18@mail.gmail.com> <87vecvmqw5.fsf_-_@benfinney.id.au> <4866bea60707090648v772e81d2r261e8d927310591c@mail.gmail.com> Message-ID: <87hcodm9hq.fsf@benfinney.id.au> "Gabriel Genellina" writes: > No, it's not correct to modify Reply-To. Some reasons: > http://www.unicom.com/pw/reply-to-harmful.html Not to mention that, since the publication of that document, it's now even more clearly incorrect to munge 'reply-to' fields; the standards now specify exactly what that field is for. -- \ "Teach a man to make fire, and he will be warm for a day. Set a | `\ man on fire, and he will be warm for the rest of his life." -- | _o__) John A. Hrastar | Ben Finney From oren.tsur at gmail.com Tue Jul 24 01:57:26 2007 From: oren.tsur at gmail.com (oren.tsur at gmail.com) Date: Tue, 24 Jul 2007 05:57:26 -0000 Subject: Parsing XML with ElementTree (unicode problem?) In-Reply-To: References: <1185200976.082516.105420@57g2000hsv.googlegroups.com> Message-ID: <1185256646.060652.199740@d55g2000hsg.googlegroups.com> On Jul 23, 4:46 pm, "Richard Brodie" wrote: > wrote in message > > news:1185200976.082516.105420 at 57g2000hsv.googlegroups.com... > > > so what's the difference? how comes parsing is fine > > in the first case but erroneous in the second case? > > You may have guessed the encoding wrong. It probably > wasn't utf-8 to start with but iso8859-1 or similar. > What actual byte value is in the file? I tried it with different encodings and it didn't work. Anyways, I would expect it to be utf-8 since the XML response to the amazon query indicates a utf-8 (check it with http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=189P5TE3VP7N9MN0G302&Operation=ItemLookup&ItemId=1400079179&ResponseGroup=Reviews&ReviewPage=166 in your browser, the first line in the source is ) but the thing is that the parser parses it all right from the web (the amazon response) but fails to parse the locally saved file. > > 2. there is another problem that might be similar I get a similar > > error if the content of the (locally saved) xml have special > > characters such as '&' > > Either the originator of the XML has messed up, or whatever > you have done to save a local copy has mangled it. I think i made a mess. I changed the '&' in the original response to 'and' because the parser failed to parse the '&' (in the locally saved file) just like it failed with the French characters. Again, parsing the original response was just fine. Thanks again, Oren From bignose+hates-spam at benfinney.id.au Thu Jul 26 01:18:32 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Jul 2007 15:18:32 +1000 Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> <87ps2ghtd7.fsf@benfinney.id.au> <1185412639.075218.186290@z24g2000prh.googlegroups.com> Message-ID: <87d4yfivyv.fsf@benfinney.id.au> "mensanator at aol.com" writes: > IDLE 1.2c1 > >>> s = '123 456' > >>> s.split() > ['123', '456'] The str.split method has no bearing on this discussion, which is about the Python language syntax, and numeric literal values in particular. -- \ "Pinky, are you pondering what I'm pondering?" "Wuh, I think | `\ so, Brain, but burlap chafes me so." -- _Pinky and The Brain_ | _o__) | Ben Finney From nagle at animats.com Sun Jul 8 20:14:35 2007 From: nagle at animats.com (John Nagle) Date: Mon, 09 Jul 2007 00:14:35 GMT Subject: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc) In-Reply-To: <1183939608.088756.178320@m37g2000prh.googlegroups.com> References: <1183939608.088756.178320@m37g2000prh.googlegroups.com> Message-ID: socialanxiety at gmail.com wrote: > i hope someone here can help me. > > basically, me and my friend have a summer project. > > in this project, we need something that would basically function as a > blender. we know we'll need to buy a motor that spins, but what we're > having trouble with is figuring out how to program it. we want to be > able to control the speed of the motor. how would we accomplish this? > > i'm new to all of this, so i'm having a hard time wrapping my mind > around how it'd be possible to program one of those things :\ > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then > turn the other direction. > > would you program it the same way you would on a personal computer > (via c, python, etc)? Try "comp.robotics.misc" for the basics of robot motor control. John Nagle From jjl at pobox.com Sat Jul 14 09:11:07 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 14 Jul 2007 13:11:07 GMT Subject: Can a low-level programmer learn OOP? References: Message-ID: <87lkdjyvtg.fsf@pobox.com> aahz at pythoncraft.com (Aahz) writes: [...] > Note very very carefully that Python does not require an OOP style of > programming, agree > but it will almost certainly be the case that you just > naturally start using OOP techniques as you learn Python. There's some truth to this. But stagnation is also very easy to achieve, without conscious effort to improve. Also, reading OOP books (and this list) is still beneficial, both before and after you've understood each concept: before because it helps to learn new concepts at a faster rate, and to learn concepts you'd otherwise miss; after because it helps "clean up" and extend your understanding and because it teaches you standard names for things, helping communication. John From mccredie at gmail.com Tue Jul 17 17:08:56 2007 From: mccredie at gmail.com (Matt McCredie) Date: Tue, 17 Jul 2007 14:08:56 -0700 Subject: Break up list into groups In-Reply-To: <469D09CC.3080402@ronadam.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> <1184694533.380918.169640@m37g2000prh.googlegroups.com> <469D09CC.3080402@ronadam.com> Message-ID: <9e95df10707171408k2dfc8e08wd4056b80fcbe309b@mail.gmail.com> That certainly is fast, unfortunately it doesn't pass all of the tests. I came up with those tests so I don't know how important they are to the original poster. I modified it and came up with a generator and a non-generator version based (roughly) on your algorithm, that are almost as quick, and pass all of the tests. Some of the modifications were done just to make it quicker, so it would be fair when comparing against the other methods. I hard-coded the comparison instead of using a function and created a function that directly generates and returns a list instead of a generator. I would probably use the generator version in my code, but wrapping `list' around a generator adds about 4us (on my machine). Anyway, getgroups7 passes all of the tests I mentioned and it was timed at 10.37usec/pass. The down side: the code doesn't seem nearly as elegant. Matt def gengroups7(seq): iseq = iter(xrange(len(seq))) start = 0 for i in iseq: if seq[i]&0x80: start = i break else: return for i in iseq: if seq[i]&0x80: yield seq[start:i] start = i yield seq[start:] def getgroups7(seq): groups = [] iseq = iter(xrange(len(seq))) start = 0 for i in iseq: if seq[i]&0x80: start = i break else: return groups for i in iseq: if seq[i]&0x80: groups.append(seq[start:i]) start = i groups.append(seq[start:]) return groups -------------- next part -------------- An HTML attachment was scrubbed... URL: From theller at ctypes.org Fri Jul 13 13:28:17 2007 From: theller at ctypes.org (Thomas Heller) Date: Fri, 13 Jul 2007 19:28:17 +0200 Subject: renaming an open file in nt like unix? In-Reply-To: <1184346880.093826.176350@n2g2000hse.googlegroups.com> References: <1184346880.093826.176350@n2g2000hse.googlegroups.com> Message-ID: aaron.watters at gmail.com schrieb: > Hi. I'm writing an archival system which I'd like to be portable > to Windows. > > The system relies on the property of Unix which allows a > process to keep a file open even if another process renames > it while it is open. Neither process sees any anomaly or > error. > > Do the NT file systems support this feature (which I think is > standard for POSIX systems)? Yes, you can do that. We implemented something like this to replace dlls there are currently in use - rename the currently open file, create a new one with the old name (newly started processes will use the new one then), and delete the renamed one at the next possible occasion (usually at the next reboot). I'm not so sure on which NT versions it works this way, at least in w2000 and newer. Thomas From dr.death.tm at gmail.com Tue Jul 3 05:46:59 2007 From: dr.death.tm at gmail.com (ddtm) Date: Tue, 03 Jul 2007 09:46:59 -0000 Subject: Python IRC bot using Twisted Message-ID: <1183456019.764920.6820@q75g2000hsh.googlegroups.com> I'm using an example of IRC bot (_ttp://twistedmatrix.com/projects/ words/documentation/examples/ircLogBot.py) to create my own bot. But I have a problem. I'm trying to make my bot send messages periodically. But I can't find a way of adding Timer or something similar to my code so that it could work. Could somebody modify an example to make IRC bot send anything to chat every 20 seconds? P.S. Timer should not lock the main program (I think it should work in other thread or so) P.P.S. Could somebody write a code of delay between messages too? In pseudocode it looks like this: sleep(20) sendMessage(channel,'lopata') This delay should be non-locking too. P.P.P.S. Sorry for my bad English (and for a noob question too) From george.sakkis at gmail.com Mon Jul 2 22:49:59 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 03 Jul 2007 02:49:59 -0000 Subject: try/finally in threads Message-ID: <1183430999.552755.83550@57g2000hsv.googlegroups.com> I posted this on the Pyro list but I'm not sure if it's related specifically to Pyro. The "finally" clause below is not executed when f() runs on on a (daemon) thread and the program exits. DAEMON here is a global Pyro.code.Daemon instance. def f(): try: DAEMON.requestLoop() finally: # nothing is printed if f() runs in a thread print "i am here!!" DAEMON.shutdown() print "i am over!!" Is "finally" not guaranteed to be executed in a non-main thread or is there something else going on ? George From steve at holdenweb.com Mon Jul 30 20:28:08 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Jul 2007 20:28:08 -0400 Subject: OOP in Python book? In-Reply-To: References: <1185550866.950455.61240@g12g2000prg.googlegroups.com> Message-ID: James Stroud wrote: > Dick Moores wrote: >> At 01:27 PM 7/28/2007, Dennis Lee Bieber wrote: >> >>> On Fri, 27 Jul 2007 16:27:57 -0700, Dick Moores >>> declaimed the following in comp.lang.python: >>> >>> >>>> Well, the publisher is Prentice Hall, "The world's leading >>>> educational publisher". Textbooks are typically expensive. >>>> >>> Yeah... But at that price it should have hard-covers! >> >> Should have, but look at this popular Cultural Anthropology text >> (paperback): . List price is $120.95 USD. >> (BTW I just bought the 6th edition online for about $10.) >> >> Then there's Calculus: Single Variable (Paperback) >> List price $123.95 USD. >> >> And so it goes. >> >> Dick >> >> > > Balme your professors. They are not paying for the books. Of course most > will be give a lot of lip-service to educational access for > disadvantaged groups but thier choice of books usually suggests > otherwise. The high price of textbooks and the tendency for professors > to overlook alternatives is helping to keep the rich educated and the > poor, well, poor. > > James > Though like the music industry the book publishing trade is having to come to terms with the fact that they no longer have the same monopoly on information that they used to. 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 R.Brodie at rl.ac.uk Mon Jul 30 10:45:22 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Mon, 30 Jul 2007 15:45:22 +0100 Subject: File handle not being released by close References: <1185806160.161748.58910@d55g2000hsg.googlegroups.com> Message-ID: wrote in message news:1185806160.161748.58910 at d55g2000hsg.googlegroups.com... > I'm guessing the garbage collector is causing the file to be written, > but shouldn't close do this? Only if you call it ;) From jeba_ride at yahoo.com Tue Jul 24 13:53:02 2007 From: jeba_ride at yahoo.com (Clement) Date: Tue, 24 Jul 2007 17:53:02 -0000 Subject: Problem in Socket..... Message-ID: <1185299582.776366.17970@d55g2000hsg.googlegroups.com> Is it possible to close the socket connection immediately in Python...... Because i am getting error even though i close it after all the transfer.... I read from one article it is possible in C socket.... Whether is it possible in Python? From nospam.themindstorm at gmail.com Sat Jul 21 10:42:07 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Sat, 21 Jul 2007 14:42:07 +0000 (UTC) Subject: Pythonic way for missing dict keys References: <46a20fda$0$27858$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote in news:46a20fda$0$27858$426a74cc at news.free.fr: > Alex Popescu a ?crit : >> Jakub Stolarski wrote in > > > [snip...] > > > d = dict() > answer = d.get('answer', 42) > answer in d > => False > Thanks. I think to make the 3rd approach completely equivalent I should have been using d.setdefault(key, myojbect()). ./alex -- .w( the_mindstorm )p. From dabu11et at rock.com Mon Jul 9 19:29:18 2007 From: dabu11et at rock.com (dabu11et at rock.com) Date: Mon, 09 Jul 2007 16:29:18 -0700 Subject: Comparing modified elements in Sets In-Reply-To: <1184011034.839268.116730@r34g2000hsd.googlegroups.com> References: <1184011034.839268.116730@r34g2000hsd.googlegroups.com> Message-ID: <1184023758.621240.136330@c77g2000hse.googlegroups.com> On Jul 9, 2:57 pm, ChrisEdge... at gmail.com wrote: > I've got a set with contents like: [filename1.mp3, filename2.mp3, > filename3.mp3, ...] > I've got another set with contents like [filename1.ogg, > filename3.ogg, ...] > And another set with contents like [filename1, filename 2, ...] > > I'd like to be able to compare set 1 with set 2 and have it match > filename1 and filename3, or compare set 1 with 3 and get back > filename1, filename2. etc. > > Is there a way for me to do this inside the compare function, rather > than having to make duplicate copies of each set? my resume References: <4697d9f0$0$7614$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Chris Carlen a ?crit : >[edit] >> Must possibly learn a completely new way of thinking (OOP) > > Not necessarly. While Python is OO all the way down - meaning that > everything you'll work with will be an object (functions included) -, it > doesn't *force* you into OO (IOW : you don't have to define classes to > write a Python program). You can as well use a procedural - or even > somewhat functional - approach, and most Python programs I've seen so > far are usually a mix of the three. > >> not just a new language syntax. > > You forgot one of the most important part of a language : idioms. And > it's definitively *not* idiomatic in Python to use classes when a > simpler solution (using plain functions and modules) is enough. I see. That's very promising. I guess some articles I read painted a picture of religiousity among OOP programmers. But that is not the impression I am getting at all on the street. > IMHO, the biggest gain (in learning Python vs LabVIEW) is that you'll > add a very valuable tool to your toolbox - the missing link between C > and shell scripts. Thanks for the comments! -- Good day! ________________________________________ Christopher R. Carlen Principal Laser&Electronics Technologist Sandia National Laboratories CA USA crcarleRemoveThis at BOGUSsandia.gov NOTE, delete texts: "RemoveThis" and "BOGUS" from email address to reply. From mail at microcorp.co.za Tue Jul 10 03:34:15 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 10 Jul 2007 09:34:15 +0200 Subject: Should I use Python for these programs? References: Message-ID: <02c101c7c2c6$e387f600$03000080@hendrik> "CC" wrote: > > I have considerable C and assembly language experience. However, these > are mostly on embedded microcontrollers since I moved away from PC > programming all the way back in 1988 :-O Your experience parallels mine, except that mine has a surfeit of assembler... > > I wish to accomplish a few PC programming tasks, and am considering to > learn Python: go for it - you will be delighted with the simplicity of the complex stuff, and irritated at the hoops that you have to jump through to do low level stuff, but the trade off is worth the pain. > > 1. Develop a simple GUI program to run on Linux and Windows which can > send parameters and small blocks of data to an embedded microcontroller > device via RS-232 or USB. Also display simple data (probably single > numbers) sent from the device. If you spend a bit of money on a Lantronix Xport, you can use ethernet, and then the linux/windows problems goes away - as sockets seem to "just work" > > Note, if it is USB, then the client will be implemented by me using FTDI > chips that appear to the PC as a serial port. > > 2. Develop a simple vector drawing program that will allow one to > freehand draw a sketch composed of a few lines, or perhaps render text > in a vector form. Then sample the lines with a certain (user > configurable) spacing, and use the mouse to move the sample points along > the lines to tweak the sample locations if desired. Then output a file > of X,Y coordinates for the samples. > > What is this crazy thing for? It's to develop simple lasershow vector > frames. I am also designing a DSP-based lasershow output device, so the > same capabilities of delivering a data payload over serial/USB to a > target device will be needed here as well. > > I would prefer to be able to write a program that is cross-platform > between Linux and Windows. I realize this might be especially > problematic with the serial comms. true - its not quite the same. > > I am also confused by the plethora of Python GUI extensions, though > Tkinter seems like a likely candidate. I am uncertain if I will have > difficulty learning how to use this if I don't know Tcl/Tk. No - there are excellent examples and docs available on the web. Unless you are doing something very fancy, you dont "need" to know Tcl. The development cycle is fast, and if you get stuck you can get help here - this is a super group of people (said he modestly... :- ) ) > > Do you think Python is the right language for these projects? Yes - I am in the process of finishing an Injection Moulding Machine Controller, with the GUI in tkinter (cos its in the standard library), with some crude animation of the machine functions - and it all "just works" In my case, the OS is linux, and the interface is serial - but then I am not trying for cross platform compatibility. - I have implemented a sliding window full duplex reliable protocol, so it is possible to use Python to talk to a serial device. (at 115200, so its not "that" slow) > > Any input will be appreciated. > hth - Hendrik From nick at craig-wood.com Thu Jul 19 14:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 19 Jul 2007 13:30:04 -0500 Subject: wxPython and threads References: <1184726489.112138.96350@z28g2000prd.googlegroups.com> Message-ID: Josiah Carlson wrote: > Nick Craig-Wood wrote: > > I'd dispute that. If you are communicating between threads use a > > Queue and you will save yourself thread heartache. Queue has a non > > blocking read interface Queue.get_nowait(). > > If you have one producer and one consumer, and the consumer will be > notified when there is an item available, AND deques (in Python 2.4, > 2.5, and presumably later) are threadsafe, then the *additional* > locking, blocking, etc., that a Queue provides isn't necessary. > > Whether one wants to use a Queue for 'piece of mind', or for future > expansion possibilities is another discussion entirely, but his > application (as stated) will work with a deque for the worker thread -> > GUI thread communication path. You are right deque's do say they are thread safe - I didn't know that. From the docs :- Deques support thread-safe, memory efficient appends and pops from either side of the deque with approximately the same O(1) performance in either direction. I think I'd go for the peace of mind option, but YMMV of course ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From nazgul at jsbsystems.com Sun Jul 29 11:54:50 2007 From: nazgul at jsbsystems.com (nazgul) Date: Sun, 29 Jul 2007 10:54:50 -0500 Subject: Compiling 2.5.1 on OpenBSD 4.1 References: <46AC1B91.3070706@v.loewis.de> Message-ID: =?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?= wrote in news:46AC1B91.3070706 at v.loewis.de: >> I'm stumped. Any suggestions? > > You will have to find the true declaration of lstat - reading > man pages or checking that everything "looks right" won't help. > > So where is lstat declared? Is it declared at all, and if so, > is that declaration conditional perhaps? > > Produce a preprocessor output (posixmodule.i), by adding > -fsave-temps to the compiler line compiling posixmodule.c > (copy the line from the make output into a shell, and add > this command line); then inspect that output to see whether > lstat has been declared. > > Regards, > Martin > Thanks Martin. Did I mention this was OpenBSD 4.1 in the original post? Here's the patch: --- configure.~1~ Mon Mar 12 06:50:51 2007 +++ configure Sun Jul 29 11:47:27 2007 @@ -1553,7 +1553,7 @@ # On OpenBSD, select(2) is not available if _XOPEN_SOURCE is defined, # even though select is a POSIX function. Reported by J. Ribbens. # Reconfirmed for OpenBSD 3.3 by Zachary Hamm, for 3.4 by Jason Ish. - OpenBSD/2.* | OpenBSD/3.[0123456789] | OpenBSD/4.[0]) + OpenBSD/2.* | OpenBSD/3.[0123456789] | OpenBSD/4.[01]) define_xopen_source=no;; # Defining _XOPEN_SOURCE on NetBSD version prior to the introduction of # _NETBSD_SOURCE disables certain features (eg. setgroups). Reported by From hsoula at gmail.com Tue Jul 3 14:27:11 2007 From: hsoula at gmail.com (ed) Date: Tue, 03 Jul 2007 18:27:11 -0000 Subject: The best platform and editor for Python In-Reply-To: <1183398645.511107.258700@n2g2000hse.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> Message-ID: <1183487231.191350.62920@q75g2000hsh.googlegroups.com> for my part, i'm a big fan of DrPython for writing python code (especially on windows). http://drpython.sourceforge.net/ you will need wxPython to have it running though It's not per se an IDE but it has a lot of feature to help you writing with some interesting plug- ins. You can launch code in the IDE, you have an inserted console etc. Oh and it's written in python :) ./ed From NikitaTheSpider at gmail.com Thu Jul 12 14:46:00 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Thu, 12 Jul 2007 14:46:00 -0400 Subject: Problem with Python's "robots.txt" file parser in module robotparser References: <0T7li.5316$rL1.2716@newssvr19.news.prodigy.net> Message-ID: In article , John Nagle wrote: > Nikita the Spider wrote: > > > > > Hi John, > > Are you sure you're not confusing your sites? The robots.txt file at > > www.ibm.com contains the double slashed path. The robots.txt file at > > ibm.com is different and contains this which would explain why you > > think all URLs are denied: > > User-agent: * > > Disallow: / > > > Ah, that's it. The problem is that "ibm.com" redirects to > "http://www.ibm.com", but but "ibm.com/robots.txt" does not > redirect. For comparison, try "microsoft.com/robots.txt", > which does redirect. Strange thing for them to do, isn't it? Especially with two such different robots.txt files. -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From python at jayloden.com Tue Jul 31 16:27:25 2007 From: python at jayloden.com (Jay Loden) Date: Tue, 31 Jul 2007 16:27:25 -0400 Subject: Iteration over strings In-Reply-To: <496954360707311307y7d503b8eybd72795c8e699104@mail.gmail.com> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> <46AF7A49.3040804@jayloden.com> <46AF8046.7090702@gmx.net> <496954360707311307y7d503b8eybd72795c8e699104@mail.gmail.com> Message-ID: <46AF9B2D.8040501@jayloden.com> Robert Dailey wrote: > Hey, > > Thanks a lot for your answers guys. I had already known that strings are > immutable, but having been a C++ programmer for years I'm still trying to > get over the fact that it's not std::string :) The python documentation > isn't that easy to navigate in my opinion, so I wasn't able to find the > 'replace()' function you guys are talking about. It's actually the perfect > solution for the problem. > > I appreciate your time. I have to agree with you WRT to the Python documentation, it does tend to be lacking and difficult to find things at times. In this case the two ways I can think of to look for something like this would have been: pydoc string which lists the replace() method in the documentation for the string module, or to search Google for it. There are a lot of code samples out there for Python such as the online Python Cookbook: http://aspn.activestate.com/ASPN/Python/Cookbook/ I also highly recommend Python in Nutshell, the Python Cookbook, or Programming Python (all O'Reilly books). Programming Python is a huge tome but like all O'Reilly books in the Programming X series, it is aimed at someone who's not necessarily new to programming but is new to the language. That in combination with lots of code samples might be best for you since you're familiar with programming and it's language specifics you need references for. I'm sure there are other great books, those just happen to be the ones I'm familiar with :-) -Jay From kay.schluehr at gmx.net Fri Jul 6 01:11:56 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 05 Jul 2007 22:11:56 -0700 Subject: The best platform and editor for Python In-Reply-To: <1183673613.113448.75000@o61g2000hsh.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183646799.400176.144570@k79g2000hse.googlegroups.com> <1183673613.113448.75000@o61g2000hsh.googlegroups.com> Message-ID: <1183698716.764845.135950@o61g2000hsh.googlegroups.com> On Jul 6, 12:13 am, Alex Popescu wrote: > On Jul 5, 5:46 pm, "sjdevn... at yahoo.com" wrote: > > > > > Kay Schluehr wrote: > > > On Jul 3, 8:12 pm, cla... at lairds.us (Cameron Laird) wrote: > > > > > Python is simply easier than C++; you might > > > > well find that a debugger, for example, doesn't feel as essential > > > > as it is for you with C++. > > > > That's what I love most about the Python community. Whenever there is > > > just a non-standard, platform-dependent or crappy implementation of a > > > feature you get told that you don't need it. > > > A fairly nice debugger is standard and built-in to the regular Python > > distribution on all platforms. > > > But 95% of what a debugger is used for IME is getting a stack trace-- > > in Python (or Java or Ruby or most modern languages) you get that > > automatically, and the debugger is nowhere near as useful as it is in > > C or C++. > > I am a Python newbie, but unfortunately I don't agree with that. For > me having a debugger helped understand very quickly the flow > in the libraries for which otherwise I would have had to navigate > through code (which once again is not always easy without a good IDE). You don't have to be unfortune about it. As you see there is no consensus. I don't even know how Java developers would respond to the assertion that the debugger is halfway irrelevant because they can read the stacktraces ( A real C programmer and real man can read core dumps. So what? ) Java is often considered as Blub but it doesn't at least deny progress in tool development of the last 20 years. > But this is just a newbie opinion :-), I don't think so. BTW if you want to take a glimpse on the future of "dynamic" languages you might also checkout this paper: http://lamp.epfl.ch/~mcdirmid/mcdirmid07live.pdf Kay From dhwild at talktalk.net Sat Jul 28 04:34:53 2007 From: dhwild at talktalk.net (David H Wild) Date: Sat, 28 Jul 2007 09:34:53 +0100 Subject: 128 or 96 bit integer types? References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com> <1185562901.206212.52570@j4g2000prf.googlegroups.com> <1185607142.096574.209200@e16g2000pri.googlegroups.com> Message-ID: <46ab05a9$0$1345$834e42db@reader.greatnowhere.com> In article <1185607142.096574.209200 at e16g2000pri.googlegroups.com>, mensanator at aol.com wrote: > For example, how many ways can you put 492 marbles into > 264 ordered bins such that each bin has at least 1 marble? > The answer > 66189415264331559482776409694993032407028709677550 > 59629130019289014193777349831417543311612293951363 > 4124491233746912456893016976209252459301489030 > has 146 digits. What on earth made you think of that question? -- David Wild using RISC OS on broadband www.davidhwild.me.uk From gggg.iiiii at gmail.com Mon Jul 23 22:23:28 2007 From: gggg.iiiii at gmail.com (G) Date: Mon, 23 Jul 2007 22:23:28 -0400 Subject: Subclassing int In-Reply-To: <9e95df10707231830k749c94d1t76571f7c0e9e72d3@mail.gmail.com> References: <4a7f84ac0707231803x7083a688kc91965a5d78e679@mail.gmail.com> <9e95df10707231830k749c94d1t76571f7c0e9e72d3@mail.gmail.com> Message-ID: <4a7f84ac0707231923s213e91e6s7a77a067d7d83243@mail.gmail.com> Thanks a lot Matt and Steve. I replaced __int__ with __new__ and it worked On 7/23/07, Matt McCredie wrote: > > Do you guys know why the if statement is not evaluated? > > > For immutable types __new__ is called before __init__. There are some > details here: http://docs.python.org/ref/customization.html. Also, it > isn't really clear what you want to do if the value is set to None anyway. > In your example you return None, but that simply won't work since you can't > return anything from __init__. Perhaps your need could be met by a function > instead: > > > def INT(x): > if x is None: > return None > else: return int(x) > > > -Matt > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bob at mellowood.ca Sat Jul 14 13:44:05 2007 From: bob at mellowood.ca (bvdp) Date: Sat, 14 Jul 2007 10:44:05 -0700 Subject: Circular import problem In-Reply-To: References: <1184294176.550267.119980@n60g2000hse.googlegroups.com> <1184343897.111992.107880@g4g2000hsf.googlegroups.com> Message-ID: <1184435045.834596.97600@o61g2000hsh.googlegroups.com> > > But, I still don't understand how python can access a function in a > > file I have NOT included. In this case, to get things to work, I DO > > NOT "import MMA.grooves" but later in the module I access a function > > with "xx=MMA.grooves.somefunc()" and it finds the function, and works > > just fine. It shouldn't work. > > That depends a bit on what is "MMA" and what is "grooves". > MMA.grooves means "look for an attribute named grooves inside MMA". If MMA > is a module, and MMA.grooves is a class/function defined inside the > module, you don't need to import it before using it. > But if MMA is a package, and MMA.grooves is a module inside that package, > you need to import it first (unless MMA/__init__.py does that already) In this case (and I should have been more clear) MMA is a package and grooves is a module. It is working now, but before I moved other imports around I was able to do the following: 1. NOT include MMA.gooves, 2. call the function MMA.grooves.somefunc() and have it work. The point I was trying to make was that something in my imports was causing the namespace to contain MMA.grooves.* when it hadn't been imported in that module. I suspect that my reordering effected some initialization of modules, probably the creation of some classes. But that is a guess. I've just used an empty __init__.py file. I will have to read up a bit more on packages and see what advantage there is to import in that. > > I have tried to delay the import, and that does work. But, from a > > stylistic view I really to like to have all my imports at the top of > > the module. Maybe some old assembler/C habits on my part. > > Sure, it's considered good style. Which is considered good style? Loading at the top or loading when needed? From crcarleRemoveThis at BOGUSsandia.gov Fri Jul 13 12:14:47 2007 From: crcarleRemoveThis at BOGUSsandia.gov (Chris Carlen) Date: Fri, 13 Jul 2007 09:14:47 -0700 Subject: Understanding python functions - Instant Python tutorial In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Thu, 12 Jul 2007 21:51:08 -0300, Chris Carlen > escribi?: >> http://hetland.org/writing/instant-python.html >> I don't understand Hetland's terminology though, when he is speaking of >> "binding" and "reference." Actually, Hetland's entire first paragraph >> is unclear. > First, see this short article http://effbot.org/zone/python-objects.htm I'll have a look. > Now, forget about C "variables" and "pointers" because you won't get > much far with those concepts. Ok, painful, but I'll try. > Objects exist - and we usually use names to refer to them. This line: > > a = 1 > > means "make the name 'a' refer to the object 1", or, "bind the name 'a' > to the instance of type int with value 1", or "let 'a' be a reference > to the object 1" > > This line: > > some_list[1] = 4 > > means "make the second element of some_list refer to the object 4", or > "alter some_list so its element [1] is a reference to the object 4" > > bind the name 'a' to the instance of type int with value 1", or "let > 'a' be a reference to the object 1" > > Note that some objects are immutable - like the number 1, which will > always be the number 1 (*not* an integer "variable" that can hold any > integer value). Other objects -like lists and dictionaries, by example, > or most user defined classes- are mutable, and you can change its > contents and properties. Modifying an object is not the same as > rebinding its name: > > x = [1,2,3] > y = x > x[1] = 4 > print x # [1, 4, 3] > print y # [1, 4, 3] Thanks to your explanation, I understand! > x = [1,2,3] > y = x > x = [1,4,3] > print x # [1, 4, 3] > print y # [1, 2, 3] > > You can test is two names refer to the same object using the is > operator: x is y. You will get True in the first case and False in the > second case. I don't quite get this "x is y" stuff yet. Let's go back the statement: x = [1,2,3] Do we then say: "[1,2,3] is x" or is it the other way around: "x is [1,2,3]" ??? I think it is the former in Python, whereas it would be the latter in C. So Python is like saying "I am Chris Carlen." This is actually completely ridiculous, since I am me, not my name. The name refers to me. I get that. Yet our spoken language puts it in a way which is backwards. Thanks for the input. -- Good day! ________________________________________ Christopher R. Carlen Principal Laser&Electronics Technologist Sandia National Laboratories CA USA crcarleRemoveThis at BOGUSsandia.gov NOTE, delete texts: "RemoveThis" and "BOGUS" from email address to reply. From crobc at BOGUS.sbcglobal.net Sun Jul 29 21:27:25 2007 From: crobc at BOGUS.sbcglobal.net (CC) Date: Sun, 29 Jul 2007 18:27:25 -0700 Subject: Hex editor display - can this be more pythonic? In-Reply-To: <5h49ijF3iormrU1@mid.uni-berlin.de> References: <5h49ijF3iormrU1@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Sun, 29 Jul 2007 12:24:56 -0700, CC wrote: >>The next step consists of printing out the ASCII printable characters. >>I have devised the following silliness: >> >>printable = ' >>1!2 at 3#4$5%6^7&8*9(0)aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ\ >>`~-_=+\\|[{]};:\'",<.>/?' > > I'd use `string.printable` and remove the "invisible" characters like '\n' > or '\t'. What is `string.printable` ? There is no printable method to strings, though I had hoped there would be. I don't yet know how to make one. >>for c in ln: >> if c in printable: sys.stdout.write(c) >> else: sys.stdout.write('.') > The translation table can be created once and should be faster. I suppose the way I'm doing it requires a search through `printable` for each c, right? Whereas the translation would just be a lookup operation? If so then perhaps the translation would be better. >>I'd like to display the non-printable characters differently, since they >>can't be distinguished from genuine period '.' characters. Thus, I may >>use ANSI escape sequences like: >> >>for c in ln: >> if c in printable: sys.stdout.write(c) >> else: >> sys.stdout.write('\x1B[31m.') >> sys.stdout.write('\x1B[0m') >> >>print > > `re.sub()` might be an option here. Yeah, that is an interesting option. Since I don't wish to modify the block of data unless the user specifically edits it, so I might prefer the simple display operation. > For escaping: > > In [90]: '\n'.encode('string-escape') > Out[90]: '\\n' Hmm, I see there's an encoder that can do my hex display too. Thanks for the input! -- _____________________ Christopher R. Carlen crobc at bogus-remove-me.sbcglobal.net SuSE 9.1 Linux 2.6.5 From stargaming at gmail.com Thu Jul 19 13:03:33 2007 From: stargaming at gmail.com (Stargaming) Date: Thu, 19 Jul 2007 19:03:33 +0200 Subject: Itertools question: how to call a function n times? In-Reply-To: References: Message-ID: <469f9966$0$25811$9b622d9e@news.freenet.de> Matthew Wilson schrieb: > I want to write a function that each time it gets called, it returns a > random choice of 1 to 5 words from a list of words. > > I can write this easily using for loops and random.choice(wordlist) and > random.randint(1, 5). > > But I want to know how to do this using itertools, since I don't like > manually doing stuff like: > > phrase = list() > for i in random.randint(1, 5): > > phrase.append(random.choice(wordlist)) > > It just seems slow. > > All advice welcome. > > TIA > > Matt > You could do it either using the previously suggested list comprehension way or, if you don't need to have all choices in memory at once, use generator expressions. They're basically like list comprehensions, except that you wrap them into parentheses (), not brackets []. phrase = (random.choice(wordlist) for i in xrange(random.randint(1, 5))) You loose the ability to slice it directly (eg. phrase[3]), though. (See itertools.islice for a way to do it.) HTH, Stargaming From brenNOSPAMbarn at NObrenSPAMbarn.net Thu Jul 5 13:48:23 2007 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Thu, 05 Jul 2007 17:48:23 GMT Subject: Proposal: s1.intersects(s2) References: <5f1pldF3a62csU5@mid.uni-berlin.de> <1183600138.759015.246040@c77g2000hse.googlegroups.com> Message-ID: Steven D'Aprano wrote: > Just because I've never come across it doesn't mean it exists, so > I'd be grateful for any reference to a technical definition, or > even references to any mathematician using intersect as a verb in a > vigorous, non-hand-waving way. Here's a link to get you started: Here ( http://arxiv.org/PS_cache/math/pdf/0702/0702029v1.pdf )is a Russian math text (in English) which says: "If A \cap B 6 = \emptyset, then we say that the sets A and B do intersect. Otherwise, if A \cap B = \emptyset, then we say that these sets do not intersect." Here ( http://www.tcs.ifi.lmu.de/~fischerf/publications/bfh_tark07.pdf ) is a math paper which says: "Sets that are disjoint in the diagram may have an empty intersection, i.e., there exist instances where these sets do not intersect." A simple Google search will also turn up numerous uses of the phrase "non-intersecting sets", which would seem to be parallel (i.e., people are not bending over backwards to say "disjoint sets" or "sets with empty intersection"). -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From nosp at exam.de Mon Jul 16 04:47:16 2007 From: nosp at exam.de (nosp at exam.de) Date: Mon, 16 Jul 2007 10:47:16 +0200 Subject: PIL cutting off letters In-Reply-To: <1181934049.401650.115360@q19g2000prn.googlegroups.com> References: <1181934049.401650.115360@q19g2000prn.googlegroups.com> Message-ID: test From stefaan.himpe at gmail.com Tue Jul 10 14:46:30 2007 From: stefaan.himpe at gmail.com (stefaan) Date: Tue, 10 Jul 2007 11:46:30 -0700 Subject: S2K DTS and Python In-Reply-To: References: Message-ID: <1184093190.699539.260600@22g2000hsm.googlegroups.com> > > However, I now want to update some tables in MSAccess, and it occurred > > to me that because Sequel Server 2000 DTS can interface with scripting > > languages that maybe I could call my first Python program from within > > DTS and then update the tables using DTS. (I am learning DTS hence the > > idea). I have never heard about DTS, so I cannot advise you on that. But since you mentioned MsAccess, I want to mention that I have successfully used the DejaVu object relational mapper[1] to access MsAccess databases. Other ORMs like SqlObject and SqlAlchemy - to the best of my knowledge - do not support MsAccess out of the box (yet?). [1] http://projects.amor.org/docs/dejavu/1.5.0RC1/ From alexandre.ferrieux at gmail.com Mon Jul 23 06:37:47 2007 From: alexandre.ferrieux at gmail.com (Alexandre Ferrieux) Date: Mon, 23 Jul 2007 03:37:47 -0700 Subject: Lazy "for line in f" ? In-Reply-To: References: <1185120650.412694.314280@o61g2000hsh.googlegroups.com> <1185143634.778056.227720@g4g2000hsf.googlegroups.com> <1185173778.656660.195650@n60g2000hse.googlegroups.com> <7xbqe3efm5.fsf@ruckus.brouhaha.com> <1185177589.837857.105390@r34g2000hsd.googlegroups.com> <1185182315.489049.271010@r34g2000hsd.googlegroups.com> Message-ID: <1185187067.468425.109860@r34g2000hsd.googlegroups.com> On Jul 23, 12:18 pm, Duncan Booth wrote: > > Whatever, the iterator makes the code both cleaner and faster. It is at > the expense of not being suitable for interactive sessions, or in some > cases pipes, but for those situations you can continue to use readline > and the extra overhead in runtime will not likely be noticable. But *why* is it so ? If Python calls fgets() which already has internal buffering, why is the extra buffering gaining so much ? -Alex From kyosohma at gmail.com Mon Jul 9 10:17:51 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 09 Jul 2007 07:17:51 -0700 Subject: Tool for finding external dependencies In-Reply-To: <1183945183.147231.120180@z28g2000prd.googlegroups.com> References: <1183945183.147231.120180@z28g2000prd.googlegroups.com> Message-ID: <1183990671.337753.106370@k79g2000hse.googlegroups.com> On Jul 8, 8:39 pm, Rob Cakebread wrote: > Hi, > > I need to find external dependencies for modules (not Python standard > library imports). > > Currently I use pylint and manually scan the output, which is very > nice, or use pylint's --ext-import-graph option to create a .dot file > and extract the info from it, but either way can take a very long > time. > > I'm aware of Python's modulefinder.py, but it doesn't find external > dependencies (or at least I don't know how to make it do them). > > Thanks, > Rob Recently I ran into some debugging issues and the freeware app "Dependency Walker" was suggested to me. I still haven't used it much since I only got it last Friday, but it looks promising: http://www.dependencywalker.com Mike From gagsl-py2 at yahoo.com.ar Mon Jul 9 21:42:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Jul 2007 22:42:53 -0300 Subject: Error when trying to write unicode xml to zipfile References: <1184022684.557693.111890@n60g2000hse.googlegroups.com> Message-ID: En Mon, 09 Jul 2007 20:11:24 -0300, Martin escribi?: > I get below error when trying to write unicode xml to a zipfile. > > zip.writestr('content.xml', content.toxml()) > File "/usr/lib/python2.4/zipfile.py", line 460, in writestr > zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum > UnicodeEncodeError: 'ascii' codec can't encode character u'\u25cf' in > position 2848: ordinal not in range(128) > > Any ideas? Encode before writing. Assuming you want to use utf-8: zip.writestr('content.xml', content.toxml().encode('utf-8')) In general, when working with unicode, it's best to decode bytes into unicode as early as possible (when reading input), process only unicode inside the program, and encode into bytes at the last step (when writing output). Some non-unicode-aware libraries may interfere with this flow, unfortunately. -- Gabriel Genellina From aleax at mac.com Sun Jul 1 17:47:48 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 1 Jul 2007 14:47:48 -0700 Subject: object references/memory access References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> Message-ID: <1i0kq0f.1m7ykg7xajggbN%aleax@mac.com> dlomsak wrote: ... > search and return takes a fraction of a second. For a large return (in > this case 21,000 records - 8.3 MB) is taking 18 seconds. 15 of those > seconds are spent sending the serialized results from the server to > the client. I did a little bit of a blind experiment and doubled the So here's a tiny example to show that the mere transfer of bytes on the socket should be taking nowhere like that long: #!/usr/local/bin/python import socket, os, time, sys port = 8881 sendsize = 1024 recvsize = 1024 totsize = 8*1024*sendsize def server(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', 8881)) sock.listen(5) newSocket, address = sock.accept() totbytes = 0 start = time.time() while totbytes < totsize: receivedData = newSocket.recv(recvsize) if not receivedData: break totbytes += len(receivedData) newSocket.close() sock.close() return totbytes, time.time()-start def client(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 8881)) totbytes = 0 while totbytes < totsize: sock.sendall(sendsize*'x') totbytes += sendsize sock.close() def main(): print "moving %d bytes (ss=%d, rs=%d)" % (totsize, sendsize, recvsize) if os.fork(): # parent process forbytes, tooktime = server() else: # child process time.sleep(0.5) client() sys.exit(0) stend = time.time() print "%d bytes in %5.2f sec (ss=%d, rs=%d)" % (forbytes, tooktime, sendsize, recvsize) main() brain:~/downloads alex$ python sere.py moving 8388608 bytes (ss=1024, rs=1024) 8388608 bytes in 0.08 sec (ss=1024, rs=1024) So, moving 8.3 MB on a bare socket should take about 100 milliseconds, give or take. So let's try WITH pickling and unpickling (done right): #!/usr/local/bin/python import socket, os, time, sys, random, cPickle port = 8881 sendsize = 1024 recvsize = 1024 data = [random.random() for i in xrange(1000*1000)] pickled_data = cPickle.dumps(data, 2) totsize = len(pickled_data) def server(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', 8881)) sock.listen(5) newSocket, address = sock.accept() totbytes = 0 recvdata = [] start = time.time() while totbytes < totsize: receivedData = newSocket.recv(recvsize) if not receivedData: break totbytes += len(receivedData) recvdata.append(receivedData) newSocket.close() sock.close() data = cPickle.loads(''.join(recvdata)) return totbytes, time.time()-start def client(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', 8881)) totbytes = 0 while totbytes < totsize: totbytes += sock.send(pickled_data[totbytes:totbytes+sendsize]) sock.close() def main(): print "moving %d bytes (ss=%d, rs=%d)" % (totsize, sendsize, recvsize) if os.fork(): # parent process forbytes, tooktime = server() else: # child process time.sleep(0.5) client() sys.exit(0) stend = time.time() print "%d bytes in %5.2f sec (ss=%d, rs=%d)" % (forbytes, tooktime, sendsize, recvsize) main() brain:~/downloads alex$ python sere.py moving 9002006 bytes (ss=1024, rs=1024) 9002006 bytes in 0.32 sec (ss=1024, rs=1024) So, a bit more data, quite a bit longer, but still on the order of magnitude of 300 milliseconds or so. Again this suggests the problems are not "intrinsic" to the task. It's hard to guess at exactly what it may be that you're doing wrong. For example, if recvdata was a string (grown with +=) rather than a list (grown with append), this would boost the runtime to 0.76 seconds; a huge waste (more than a factor of two blown away by a minor programming gaucheness) but still a long way from the several orders of magniture you're observing. So, I suggest you try programming the interaction directly to bare sockets, as I do here (and in several examples in Chapter 20 in "Python in a Nutshell" 2nd edition), and see what difference that makes to your timings. Alex From fdu.xiaojf at gmail.com Mon Jul 16 09:03:21 2007 From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com) Date: Mon, 16 Jul 2007 21:03:21 +0800 Subject: questions about functions inside a function In-Reply-To: References: Message-ID: <469B6C99.7030903@gmail.com> Hi, Duncan Booth wrote: > "fdu.xiaojf at gmail.com" wrote: > >> What I want is, the value of i should be bounded to the anonymous >> function. And the output should like this: >> >> for f in a: >> print f() >> 0 >> 1 >> 4 >> 9 >> >> How to achieve this? > > Use default arguments when defining your function: default arguments are > evaluated when the function is defined, bound arguments get the current > value of the variable at the point when it is referenced during the call. > > Also, since you give your function a name anyway ('b') you might as well > use a named function as being clearer than using lambda: > >>>> a = [] >>>> for i in range(4): > def b(i=i): > return i**2 > a.append(b) > > >>>> for f in a: > f() > > > 0 > 1 > 4 > 9 Thanks for some quick replies. I'm trying to minimize a function f(X) (X = [x1, x2, ..., xn]) using scipy.optimize.fmin_cobyla. The parameter of the function is a list of N variables. fmin_cobyla also accept a 'cons' parameter as constraint function, which is a list of functions. In order to make sure all variables be larger than 0, I tried to created constraint function like this: cons = [] for i in range(N): c = lambda x: x[i] - 1e-10 cons.append(c) But when functions in cons are evaluated, the value in all functions are all the same(N-1, which is the last value of i in the loop). What I want is, when functions in cons be evaluated, every function refers to a different variable in X. Regards Xiao Jianfeng From jenifferlopez20 at gmail.com Sun Jul 15 09:05:34 2007 From: jenifferlopez20 at gmail.com (jeniffer) Date: Sun, 15 Jul 2007 13:05:34 -0000 Subject: =?utf-8?B?4peZ4pa6SW5zdGFudGx5IFR1cm4geW91ciBDb21wdXRlciBpbnRvIGEgU3VwZXIgVFYg4peE4peZ?= Message-ID: <1184504734.773809.246570@i13g2000prf.googlegroups.com> Instantly Turn your Computer into a Super TV ? Watch all your favorite shows on your Computer & TV! ? Channels you can?t get any other place in the U.S.A! ? Watch from anywhere in the world! ? Save 1000's of $$$ over many years on cable and satellite bills ? INSTANT DOWNLOAD ? And much, much more! For More Details: http://tvonpc.xt.cx From ptmcg at austin.rr.com Sun Jul 8 20:29:53 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Sun, 08 Jul 2007 17:29:53 -0700 Subject: accessing an object instance by only having one of its attribute values In-Reply-To: <1183921865.879071.172730@n2g2000hse.googlegroups.com> References: <1183918727.033724.213010@22g2000hsm.googlegroups.com> <1183921865.879071.172730@n2g2000hse.googlegroups.com> Message-ID: <1183940993.096789.148950@22g2000hsm.googlegroups.com> On Jul 8, 2:11 pm, mshiltonj wrote: > On Jul 8, 2:18 pm, feli... at gmail.com wrote: > > > Hello all, > > > Imaybe someone can help me with this question. > > Is there a direct way of accessing an object instance, if all I know > > is the value of one of its attributes? > > The object is part of a list of objects, and I would like to pick the > > object directly by using this attribute value, instead of going > > through the list and checking if each objects attribute value is the > > one I am looking for. > > > Thank you in advance > > I'd set up a dict as a lookup table, assuming the attribute values are > unique per object. > > list_of_objects = (obj1, obj2, obj3, obj4); > > obj_lookup_by_attr = {}; > > for obj in list_of_objects: > obj_lookup_by_attr.set(obj.attr, obj) > > [...] > > obj = obj_lookup_by_attr.get(attr_val, None); > > if (obj): > [...] I have some comments on the Pythonicity of your suggestions. Same assumption, object attr is a unique key of some sort. How to create the dict of objects, and how to retrieve an object by key. -- Paul list_of_objects = (obj1, obj2, obj3, obj4); # creating a dict by initializing to empty, and then looping # through input list and adding items one at a time obj_lookup_by_attr = {}; for obj in list_of_objects: #obj_lookup_by_attr.set(obj.attr, obj) # why use set for this? why not just this: obj_lookup_by_attr[obj.attr] = obj # or even better might be to use a generator expression to create a # sequence of tuples, and call the dict constructor - a good idiom to # learn obj_lookup_by_attr = dict( (obj.attr,obj) for obj in list_of_objects ) [...] obj = obj_lookup_by_attr.get(attr_val, None); # oh woe if obj is an instance of a class that defines special # true/falseness - obj might be a real object, but evaluates to false # #if (obj): # # much better to test this way # (and NEVER test using "if obj != None:" - this is wasteful # nonsense, since None is a singleton) if obj is not None: [...] From jgodoy at gmail.com Sun Jul 22 14:05:56 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sun, 22 Jul 2007 15:05:56 -0300 Subject: Advice on sending images to clients over network References: <1185095666.627415.108450@w3g2000hsg.googlegroups.com> <7xlkd8mktt.fsf@ruckus.brouhaha.com> Message-ID: <2ticn4-3k6.ln1@strongwill.g2ctech> Paul McNett wrote: > Paul Rubin wrote: >> Frank Millman writes: >>> Any suggestions will be much appreciated. >> >> Why on earth don't you write the whole thing as a web app instead of >> a special protocol? Then just use normal html tags to put images >> into the relevant pages. > > I believe he has a full desktop client app, not a web app. Believe it or > not, there's still a solid place for desktop applications even in this > ever-increasing webified world. He's using wxPython and already has network connectivity to access the database server. > Use the right tool for the job... Yep... I also believe that a HTTP server is the right tool. :-) From danb_83 at yahoo.com Mon Jul 16 20:18:32 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Mon, 16 Jul 2007 17:18:32 -0700 Subject: In a dynamic language, why % operator asks user for type info? In-Reply-To: <1184631007.920803.147790@j4g2000prf.googlegroups.com> References: <1184631007.920803.147790@j4g2000prf.googlegroups.com> Message-ID: <1184631512.329438.90050@i13g2000prf.googlegroups.com> On Jul 16, 7:10 pm, Karthik Gurusamy wrote: > Hi, > > The string format operator, %, provides a functionality similar to the > snprintf function in C. In C, the function does not know the type of > each of the argument and hence relies on the embedded % > specifier to guide itself while retrieving args. > > In python, the language already provides ways to know the type of an > object. > > So in > > output = '%d foo %d bar" % (foo_count, bar_count), > why we need to use %d? In order to distinguish between, for example: >>> '%c' % 42 '*' >>> '%d' % 42 '42' >>> '%e' % 42 '4.200000e+01' >>> '%f' % 42 '42.000000' >>> '%g' % 42 '42' >>> '%i' % 42 '42' >>> '%o' % 42 '52' >>> '%r' % 42 '42' >>> '%s' % 42 '42' >>> '%u' % 42 '42' >>> '%x' % 42 '2a' From Colin.Prepscius at morganstanley.com Tue Jul 24 13:55:43 2007 From: Colin.Prepscius at morganstanley.com (Prepscius, Colin (IT)) Date: Tue, 24 Jul 2007 13:55:43 -0400 Subject: exec and func_code In-Reply-To: <1185298743.3370.25.camel@dot.uniqsys.com> References: <1185298743.3370.25.camel@dot.uniqsys.com> Message-ID: Actually, thx to Gabrielle Genellina, who wrote earlier: Instead of using exec, rebuild a new function from the unmarshalled code: import new f3 = new.function(f2.func_code, globals()) f3(parameter) I haven't tried it yet, but will today... -----Original Message----- From: python-list-bounces+colin.prepscius=morganstanley.com at python.org [mailto:python-list-bounces+colin.prepscius=morganstanley.com at python.org ] On Behalf Of Carsten Haese Sent: Tuesday, July 24, 2007 1:39 PM To: python-list at python.org Subject: Re: exec and func_code On Tue, 2007-07-24 at 13:24 -0400, Prepscius, Colin (IT) wrote: > Does anybody know how to pass parameters to 'exec > somefunction.func_code'? > > def f1(): > print 'this is f1' > > def f2(p): > print 'this is f2, p =', str(p) > > exec f1.func_code > THIS RESULTS IN: "this is nf1" WHICH IS NICE > > exec f2.func_code > THIS RESULTS IN: TypeError: f2() takes exactly 1 argument (0 given) > WHICH IS EXPECTED > > exec f2.func_code in {'p':34} > THIS RESULTS IN: TypeError: f2() takes exactly 1 argument (0 > given) ????? Why not just "f2(34)"? What problem are you trying to solve here? -- Carsten Haese http://informixdb.sourceforge.net -- http://mail.python.org/mailman/listinfo/python-list -------------------------------------------------------- NOTICE: If received in error, please destroy and notify sender. Sender does not intend to waive confidentiality or privilege. Use of this email is prohibited when received in error. From nazgul at jsbsystems.com Sat Jul 28 21:17:13 2007 From: nazgul at jsbsystems.com (nazgul at jsbsystems.com) Date: Sat, 28 Jul 2007 20:17:13 -0500 Subject: Memory utilization (linux v. openbsd) Message-ID: Hi all, I have an app that runs on multiple boxes. On my slackware box, running Python 2.5.1, top shows this: Mem: 1002736k total, 453268k used, 549468k free, 31392k buffers Swap: 2097136k total, 0k used, 2097136k free, 136876k cached PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 2741 dnm 16 0 267m 261m 2676 S 99.3 26.7 14:54.62 python The same app running on OpenBSD 4.1 (but on Python 2.5P3 from ports) yields this (actually, I have 2 copies running on a dualcore box): Memory: Real: 1130M/1989M act/tot Free: 792K Swap: 337M/2048M used/tot PID USERNAME PRI NICE SIZE RES STATE WAIT TIME CPU COMMAND 12380 dnm 64 0 926M 436M run/0 - 22:22 73.58% python2.5 22956 dnm 64 0 933M 695M onproc/0 - 22:46 68.55% python2.5 RES was has over 800M earlier in the job. My problem is that the two process under OpenBSD are going to fail with a MemoryError becaause the size just keeps getting larger and larger. ulimit -d is 1G for each process. Any idea why the memory utilization is so much higher under OpenBSD? What I also find interesting is that the OpenBSD box seems to grind to a halt (that's probably due to swapping since there's 500M of swap space in use). Those processes should both be over 90% since they are CPU bound, and they are that way at the start of the run. Gradually, the system % creeps up as does idle, but there's no reason for them to be idle. It's a CPU bound process. (While I'm typing this top is showing cpu rats of 63% and 41% for the two jobs). TIA, nazgul From irmen.NOSPAM at xs4all.nl Tue Jul 17 14:24:49 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 17 Jul 2007 20:24:49 +0200 Subject: Best method for inter process communications In-Reply-To: <1184606522.541918.18870@22g2000hsm.googlegroups.com> References: <1184606522.541918.18870@22g2000hsm.googlegroups.com> Message-ID: <469d0971$0$336$e4fe514c@news.xs4all.nl> JamesHoward wrote: > I am looking for a way of performing inter process communication over > XML between a python program and something else creating XML data. What is that "something else"? --irmen From duncan.booth at invalid.invalid Mon Jul 2 16:21:20 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Jul 2007 20:21:20 GMT Subject: Bug in Python class static variable? References: <1183372758.251109.34550@z28g2000prd.googlegroups.com> <1183406012.465981.35700@z28g2000prd.googlegroups.com> Message-ID: Bruza wrote: > On Jul 2, 3:52 am, Duncan Booth wrote: >> Bruza wrote: >> > I am trying to define a class static variable. But the value of the >> > static variable seems to be only defined inside the file that the >> > class is declared. See the code below. When I run "python w.py", I >> > got: >> >> When you run "python w.py" the *script* w.py is loaded as the module >> __main__. Importing a module called 'w' creates a new module which is >> unrelated to __main__. If you want access to variables defined in the >> main script then you need to import __main__. >> >> Don't use 'from module import *': >> >> The import statements are executed when the interpreter reaches them >> in the source. Even if you fix your code to import from __main__, the >> values you try to import from __main__ won't exist when the import >> statement executes: the first 'from a import *' will load and execute >> all of module 'a', but when that executes 'from __main__ import *' it >> just imports names defined in the main script *before* a was >> imported. >> >> In general, don't try to do this: put all your classes into modules >> and just put minimal startup code into a script. > > Duncan, > > Thanks for replying. However, I am still confused... > Even if I put "from __main__ import *" in both "a.py" and "w.py", I > still got > the same results. So, how should I re-structure my program to make the > class > static variable works??? > Option 1: In w.py put: import a and then refer to a.ClassA In a.py put: import __main__ and then refer to __main__.ClassW But better, option 2: Create a new file script.py which contains: import w if __name__=='__main__': w.startup() then in a use 'import w' and in w use 'import a' and refer to a.ClassA and w.ClassW as above. Try to think through the order in which Python interprets your code: remember everything is interpreted. Both 'import' statements and 'class' statements are really just variation on an assignment, so none of the names exist until the lines which declare them have been executed. A line 'import a' is roughly the same as: a = __import__(something) and a statement such as 'class ClassA: whatever' is roughly the same as: ClassA = type('ClassA', baseclasses, dict) You should never attempt to use the 'from X import *' form of import when you have modules which include each other (you might get away with it if you move the imports to the end of the module instead of the beginning, but it is much simpler just to import the modules, and good practice in any case). From bbxx789_05ss at yahoo.com Fri Jul 20 03:30:43 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 20 Jul 2007 00:30:43 -0700 Subject: Script to POST to web page with cookies? In-Reply-To: References: Message-ID: <1184916643.653764.220690@o61g2000hsh.googlegroups.com> On Jul 19, 7:43 pm, Gilles Ganault wrote: > Hello > > I need to write a script to automate fetching data from a web site: > 1. using the POST method, log on, with login/password saved as cookies > 2. download page and extract relevent information using regexes > 3. log off > 4. wait for a random number of minutes, and GOTO 1 > > I'm a bit confused with how to get POST and cookies in the same > script: > - urllib vs urllib2 vs httplib? > - "ClientCookie.urlopen("www") behaves identically to urllib2.urlopen, > except that it deals with cookies automatically" > > Has anyone some working code that I could borrow (er... steal) to do > this? > > Thank you. Also, see here: http://www.voidspace.org.uk/python/articles/cookielib.shtml From lance at augustmail.com Wed Jul 11 17:14:42 2007 From: lance at augustmail.com (Lance Hoffmeyer) Date: Wed, 11 Jul 2007 21:14:42 GMT Subject: win32com ppt embedded object - SOLVED In-Reply-To: References: Message-ID: <6Lbli.29372$BT3.26862@trnddc06> Basically, if I ran (after discovering what the object name I was trying to modify in the ppt slide was): if WB.Slides(29).Shapes("Object 2").Type==7: PWB = WB.Slides(29).Shapes("Object 2") #Select the Graph Object oGraph = PWB.OLEFormat.Object oGraph.Application.datasheet.Range("00").Value = "Fav" this code worked. When I ran this: for shape in WB.Slides(29).Shapes: if (shape.Type== 7): print shape.Name PWB = WB.Slides(29).Shapes(shape) oGraph = PWB.OLEFormat.Object oGraph.Application.datasheet.Range("00").Value = "Fav" I got an error. I tried "print shape" I received Putting in PWB = WB.Slides(29).Shapes(shape.Name) instead of PWB = WB.Slides(29).Shapes(shape) allowed this to work. Also, I discovered I was working with a MSGraph object and not an Excel spreadsheet object. for shape in WB.Slides(29).Shapes: if (shape.Type== 7): print shape.Name PWB = WB.Slides(29).Shapes(shape.Name) oGraph = PWB.OLEFormat.Object oGraph.Application.datasheet.Range("00").Value = "Fav" Lance Lance Hoffmeyer wrote: > Hey all, > > I am trying to create some python code to edit embedded ppt slides and need some help. > > import win32com.client > from win32com.client import constants > import re > import codecs,win32com.client > import time > import datetime > import win32com.client.dynamic > ###################################################### > ############ VARIOUS VARIABLES TO SET ################ > path = "C:\temp/" > ###################################################### > ###################################################### > > > PPT=win32com.client.Dispatch("PowerPoint.Application") > WB=PPT.Presentations.Open(path + "File.ppt") > PPT.Visible=1 > PPTSLIDE= 29 > > for Z in WB.Slides(29).Shapes: > if (Z.Type== 7): > ZZ=Z.OLEFormat.Object > WSHEET = ZZ.Worksheets(1) > WSHEET.Range("A1").Value = .50 > WSHEET.Range("A1").NumberFormat="0%" > > Gives error: > > Traceback (most recent call last): > File "P:\Burke\TRACKERS\Ortho-McNeil\04 2007, 04-10 WAVE 4\Automation\Document1.py", line 23, in ? > WSHEET = ZZ.Worksheets(1) > File "C:\Program Files\Python\lib\site-packages\win32com\client\dynamic.py", line 489, in __getattr__ > raise AttributeError, "%s.%s" % (self._username_, attr) > AttributeError: .Worksheets > > Tool completed with exit code 1 > > > > Why is ZZ unknown and how to I correct this? > > > > > Thanks in advance, > > Lance > > From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jul 4 06:20:13 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 04 Jul 2007 12:20:13 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xd4z837e2.fsf@ruckus.brouhaha.com> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> Message-ID: <468b7426$0$9063$426a34cc@news.free.fr> Paul Rubin a ?crit : > greg writes: >>> E.g. your program might pass its test and run properly for years >>> before some weird piece of input data causes some regexp to not quite >>> work. >> Then you get a bug report, you fix it, and you add a test >> for it so that particular bug can't happen again. > > Why on earth would anyone prefer taking a failure in the field over > having a static type check make that particular failure impossible? Because static type checks impose a lot of arbitrary restrictions, boilerplate code etc, which tends to make code more complicated than it needs to be, which is a good way of introducing bugs that wouldn't have existed without static type checks. Depending on the application domain and some technical and non-technical constraints and requirements, it (often) happens that it's better to have the application deployed now with an occasional error message than to have it next year... And FWIW, when it comes to "weird piece of input data", statically typed languages are not specially better than dynamic ones... From steve at REMOVE.THIS.cybersource.com.au Fri Jul 27 20:21:14 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Jul 2007 10:21:14 +1000 Subject: Comparing Dictionaries References: <1185529358.128424.52450@19g2000hsx.googlegroups.com> Message-ID: On Fri, 27 Jul 2007 14:11:02 -0500, Kenneth Love wrote: > The published recipe (based on ConfigParser) did not handle my INI > files. I have periods in both the section names and the key names. > The INI files contents were developed according to an internally > defined process that other non-Python programs rely on. The published > recipe *did not work* with this scenario. I think you have made a mistake. ConfigParser as published certainly DOES accept periods in section and option names. It just *works*. Here's my INI file: [SECTION.FRED] option.wilma = 45 And here's how I read it: >>> import ConfigParser >>> D = ConfigParser.ConfigParser() >>> D.read('Desktop/data.ini') ['Desktop/data.ini'] >>> D.sections() ['SECTION.FRED'] >>> D.options('SECTION.FRED') ['option.wilma'] >>> D.getint('SECTION.FRED', 'option.wilma') 45 Even if the existing ConfigParser doesn't do what you want, the right way to fix the problem is not to recreate the entire module from scratch, but to subclass it: import ConfigParser class MyConfigParser(ConfigParser.ConfigParser): # Warning: untested. I haven't even looked at the source code # of the original. def getint(self, section, option): value = super(MyConfigParser, self).getint(section, option) return value + 1 (Although, it has to be said... if somebody can subclass ConfigParser so that writing a modified file doesn't remove comments, I'll be mightily impressed.) -- Steven. From kyosohma at gmail.com Fri Jul 20 17:12:13 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Fri, 20 Jul 2007 21:12:13 -0000 Subject: Python MAPI In-Reply-To: <1184960314.426690.238270@z28g2000prd.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> Message-ID: <1184965933.212060.214800@m3g2000hsh.googlegroups.com> > > If Process Monitor has an option to save its output as text files / > CSV files (some of the other SysInternals tools do), you might want to > try using (a Windows version) of grep or awk to filter out the > noise .. > > Vasudev 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. Mike From gagsl-py2 at yahoo.com.ar Mon Jul 9 05:01:00 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Jul 2007 06:01:00 -0300 Subject: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc) References: <1183939608.088756.178320@m37g2000prh.googlegroups.com> Message-ID: En Sun, 08 Jul 2007 21:06:48 -0300, escribi?: > in this project, we need something that would basically function as a > blender. we know we'll need to buy a motor that spins, but what we're > having trouble with is figuring out how to program it. we want to be > able to control the speed of the motor. how would we accomplish this? This is mostly an electronics question. How much power? For small power and fine control I'd look for "stepwise motor" on any robotics book; for a high power "blender" I think you don't care so much about fine control. In any case, it's the available motor which dictates how you can control it. > i'm new to all of this, so i'm having a hard time wrapping my mind > around how it'd be possible to program one of those things :\ > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then > turn the other direction. You may write the GUI using python, and the high level controlling API too. But you may need to use a PIC or some kind of controller, listening for commands from the PC and acting over the motor accordingly. Picasso: a Python-controlled robot for doing paintings http://youtube.com/watch?v=PsbKq5Kysj0 -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Jul 13 21:38:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jul 2007 22:38:15 -0300 Subject: MaildirMessage References: <1184287592.509355.310110@g4g2000hsf.googlegroups.com> <874pk8kedo.fsf@benfinney.id.au> <1184323081.806809.160380@m3g2000hsh.googlegroups.com> Message-ID: En Fri, 13 Jul 2007 07:38:01 -0300, Tzury escribi?: >> Which is a bug in the 'email.message' module, in my view. If it's >> attempting to support a mapping protocol, it should allow iteration >> the same way standard Python mappings do: by iterating over the keys. > > I thought it is a bug as well, but who am I a python newbie to say so. > I found inspect.getmembers(msg) as a good solution to map the message > properties. Hmmm, I don't see why a message should support iteration, or even why iterating over a message should mean iterating over its headers... Anyway, if you want to iterate over all the message headers, the simplest way is using msg.keys() -- Gabriel Genellina From mccredie at gmail.com Mon Jul 16 18:18:44 2007 From: mccredie at gmail.com (Matimus) Date: Mon, 16 Jul 2007 22:18:44 -0000 Subject: Break up list into groups In-Reply-To: <1184620307.340479.253430@z28g2000prd.googlegroups.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> Message-ID: <1184624324.847911.68310@o11g2000prd.googlegroups.com> This is a perfect place for a generator: seq = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, 13, 0xF0, 14, 0xF1, 15] def gengroups(seq): group = [] for val in seq: if val & 0x80 and group: yield group group = [] group.append(val) yield group if __name__ == "__main__": print list(gengroups(seq)) The above assumes that the first value in the input sequence will have 0x80 set. Your implementation seems to makes the same assumption though. Also, just a note... if len(local) > 0: ... is better written if local: ... From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 20 07:00:25 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 20 Jul 2007 13:00:25 +0200 Subject: How to organize control access to source code ? In-Reply-To: <7xk5svpfbf.fsf@ruckus.brouhaha.com> References: <1184618776.798929.98960@57g2000hsv.googlegroups.com> <469c6fc6$0$27173$426a34cc@news.free.fr> <7xk5svpfbf.fsf@ruckus.brouhaha.com> Message-ID: <46a095c8$0$16523$426a74cc@news.free.fr> Paul Rubin a ?crit : > Bruno Desthuilliers writes: >>> How can we organize development team with code source control policy, >>> that limit access to some portion of code ? >> The question may be of interest, but I'm afraid I don't understand how >> it relates to Python ??? > > It sounds like a reasonable application of multiple Mercurial > repositories. Mercurial is a distributed source control system > written in Python. Does that count? Hmmm, let's see... The reference implementation of Python is written in C. Should we then post Python-related questions on c.l.c ?-) From parvini_navid at yahoo.com Sun Jul 15 05:18:44 2007 From: parvini_navid at yahoo.com (Navid Parvini) Date: Sun, 15 Jul 2007 02:18:44 -0700 (PDT) Subject: standalone module Message-ID: <142168.64744.qm@web54501.mail.re2.yahoo.com> Dear All, I want to create a standalone program ( an exe file ) from my python files which works on Windows and Linux. Could you please tell me how to do that? Thank you in advance, Navid --------------------------------- Got a little couch potato? Check out fun summer activities for kids. -------------- next part -------------- An HTML attachment was scrubbed... URL: From zentraders at gmail.com Sat Jul 28 13:01:24 2007 From: zentraders at gmail.com (Zentrader) Date: Sat, 28 Jul 2007 10:01:24 -0700 Subject: a simple string question In-Reply-To: References: <1185549793.114644.62170@k79g2000hse.googlegroups.com> <1185558406.916313.32980@r34g2000hsd.googlegroups.com> <1185589263.743811.204040@x40g2000prg.googlegroups.com> <1185599148.583067.42910@d30g2000prg.googlegroups.com> <1185613816.996100.323090@r34g2000hsd.googlegroups.com> Message-ID: <1185642084.335988.95680@x40g2000prg.googlegroups.com> > >>> Short_Text="n=90; if n==90:print 'ok'" > >>> compound_lines = Short_Text.split(";") > >>> for line in compound_lines: > ... line = line.replace(":", ":\n ") > ... print line > ... > n=90 > if n==90: > print 'ok' A variation of this will work if the input file isn't too complicated. I found this link with a Google of "c to python". This will give you an idea of how difficult it can be if you take into account every possibility when converting. You might check the web first, since someone has probably already done what you want. Good luck. http://www.catb.org/~esr/ctopy/ From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 10 10:54:47 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 10 Jul 2007 16:54:47 +0200 Subject: Building a Python app with Mozilla In-Reply-To: References: Message-ID: <46939d9f$0$20742$426a74cc@news.free.fr> Thorsten Kampe a ?crit : > Hi, > > I've already sent this to the Komodo mailing list (which seemed to me > the more appropriate place) but unfortunately I got no response. > > I'd like to build a Python GUI app. Neither Tkinter nor Wxpython nor > PyQT are actually what I want (because the lack of GUI builders and > they don't really look good on Windows and Linux). Err... Actually, there are GUI builders for wxWidget (the C++ lib behind wxPython). And since wxWidgets relies on the platform's GUI libs (native on Windows, GTK or Metal on unices), I don't get the "don't look good" point ? From bj_666 at gmx.net Sat Jul 7 12:25:33 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 7 Jul 2007 16:25:33 GMT Subject: Unicode problem References: Message-ID: <5f9t3tF3c8qopU2@mid.uni-berlin.de> On Sat, 07 Jul 2007 16:06:03 +0000, pabloski at giochinternet.com wrote: > Hi to all, I have a little problem with unicode handling under Python. > > I have this code > > s = u'A unicode string with this damn apostrophe \x2019' > > outf = codecs.open('filename.txt', 'w', 'iso-8859-15') > outf.write(s) > > what I obtain is a UnicodeEncodeError that says me that character \x2019 > maps to undefined. > > But the character \x2019 is the apostrophe and in the unicode table it has > \x0027 as an equivalent, so the codecs should convert \x2019 to \x27 ( as > defined in iso-8859-15 ).... No it shouldn't because \x2019 is a "right single quotation mark" and not an apostrophe. Ciao, Marc 'BlackJack' Rintsch From camronstone at gmail.com Mon Jul 30 15:39:55 2007 From: camronstone at gmail.com (Camron S) Date: Mon, 30 Jul 2007 12:39:55 -0700 Subject: =?utf-8?B?4pa6V2F0Y2ggU2F0ZWxsaXRlIENoYW5uZWxzIG9uIHlvdXIgUEMgLSBGUkVFIeKXhA==?= Message-ID: <1185824395.084312.5070@i38g2000prf.googlegroups.com> Finally Available! Who Else Wants to Watch Satellite TV On Your Computer Without Paying Monthly Fees... FOR FREE? For the very first time, Satellite TV is available on your computer with our "Cutting-Edge" Software! It's as Easy as 1...2...3... 1. Download our TVonPCPro software 2. Click on the channel you want to watch 3. Enjoy Satellite TV on your PC It's That Simple!! For More Details:http://tvfun.xt.cx From mail at microcorp.co.za Tue Jul 10 02:01:38 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 10 Jul 2007 08:01:38 +0200 Subject: socket: connection reset by server before client gets response References: <1183819907.249945.239700@o11g2000prd.googlegroups.com><1183900086.021428.83580@e9g2000prf.googlegroups.com> <1183965689.330543.202900@z28g2000prd.googlegroups.com> Message-ID: <005901c7c2b7$c87716c0$03000080@hendrik> "ahlongxp" wrote: > I feel a little embarrassed now. There is nothing to be embarrassed about. Experience is a thing that is hard won. As someone once said: "no Pain, no Gain" - Hendrik From fadereu at gmail.com Fri Jul 20 08:36:30 2007 From: fadereu at gmail.com (DJ Fadereu) Date: Fri, 20 Jul 2007 12:36:30 -0000 Subject: Gmail Error using smtplib Message-ID: <1184934990.184567.93760@z28g2000prd.googlegroups.com> Hello, can anyone help me with this? What am I doing wrong here? (I've changed private info to yyyy/xxxxxx) I'm getting an authentication error while using a standard script Gmail: --------------------------SCRIPT----------------------------- import smtplib from email.MIMEText import MIMEText msg = MIMEText('Hello, this is fadereu...') >From = 'yyyyyyyy at gmail.com' msg['Subject'] = 'Hello' msg ['From'] = 'ccccccc at gmail.com' msg['To'] = 'fffd at xyz.com' s = smtplib.SMTP('alt1.gmail-smtp-in.l.google.com') s.set_debuglevel(1) s.login('yyyyyyyyy at gmail.com','xxxxxxxxx') s.sendmail(msg['From'], msg['To'], msg.as_string()) s.close() ----------------------------ERROR------------------------------ Traceback (most recent call last): File "C:\Documents and Settings\Acer User\Desktop\Code\S60 scripts \Fadereu's Codez\gmail.py", line 13, in s.login('yyyyyyy at gmail.com','xxxxxxxxx'') File "C:\Python25\lib\smtplib.py", line 554, in login raise SMTPException("SMTP AUTH extension not supported by server.") SMTPException: SMTP AUTH extension not supported by server. From bbxx789_05ss at yahoo.com Fri Jul 20 12:24:05 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Fri, 20 Jul 2007 09:24:05 -0700 Subject: Open HTML file in IE In-Reply-To: <1184908153.349581.164580@i13g2000prf.googlegroups.com> References: <1184739605.732844.321180@m37g2000prh.googlegroups.com> <1184908153.349581.164580@i13g2000prf.googlegroups.com> Message-ID: <1184948645.786885.87160@q75g2000hsh.googlegroups.com> On Jul 19, 11:09 pm, gravey wrote: > The URL looks like this: > > file:///C|/Temp/Google%20Maps/linktothis.htm?lat=45.0&lng=-20.0&zoom=4&type =k > > The Javascript gets the URL from the Javascript location object and > parses it. I'm assuming that the location object has some kind of > Windows equivalent that might be set using win32com.client. Can anyone > shed any light on this? > > Thanks The location object is just your url. So, if the url of the page you open in IE is parsed by javascript, then you need to use a url with the proper information in it. From duncan.booth at invalid.invalid Sat Jul 21 10:48:10 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 21 Jul 2007 14:48:10 GMT Subject: Pythonic way for missing dict keys References: Message-ID: "Rustom Mody" wrote: > Can someone who knows about python internals throw some light on why >>>> x in dic > is cheaper than >>>> dic.has_key(x) > > ?? > Some special methods are optimised by having a reserved slot in the data structure used to implement a class. The 'in' operator uses one of these slots so it can bypass all the overheads of looking up an attribute such as 'has_key'. From bj_666 at gmx.net Wed Jul 25 14:09:55 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Jul 2007 18:09:55 GMT Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <1185385653.269942.3570@19g2000hsx.googlegroups.com> Message-ID: <5gphvjF3gg2e0U2@mid.uni-berlin.de> On Wed, 25 Jul 2007 10:47:33 -0700, Paddy wrote: > But then,what would _0 be, the number 0 or the name _0 analagous to > a0 Of course the name because numbers have to start with a digit or a dot. Otherwise this would break backwards compatibility. Ciao, Marc 'BlackJack' Rintsch From python-url at phaseit.net Mon Jul 30 12:33:10 2007 From: python-url at phaseit.net (Gabriel Genellina) Date: Mon, 30 Jul 2007 16:33:10 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jul 30) Message-ID: QOTW: "If you really want to learn hard-core Python, probably your best bet is: * read everything Tim Peters has ever written in comp.lang.python (this will take a few months), start with "import this" * read everything the PyPy guys have ever written (particularly Christian and Armin) * read and try to beat the more exotic recipes in the Python cookbook * read the papers from the various PyCons on metaclasses and the like, build a couple of dozen metaclasses and descriptors." - Mike C. Fletcher "Why would you want to become a programmer? Programmers smell bad, they have no social life, they get treated like crap by everyone. They can get paid pretty well but then they spend all the money on useless electronic junk so they still live like bums. There is only one reason to be a programmer, which is that the drive to program burns in you like a fire. But in that case don't ask how to become a programmer, because you are already one, so welcome to the ranks ;-)." - Paul Rubin Moving from .net to Python: How to implement Events and Delegates (Observer pattern) http://groups.google.com/group/comp.lang.python/browse_thread/thread/c6808e6362996834/ How to efficiently access the first, second, etc. lines of a text file http://groups.google.com/group/comp.lang.python/browse_thread/thread/800e92738e0a23b/ Borrowing from the D language: 123 456 789 == 123456789, and other suggestions. http://groups.google.com/group/comp.lang.python/browse_thread/thread/93dc57f9190b93bc/ Ways to write an "is_iterable" function, and why there can't be an universal version: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c37eea080073729f/ Using ClientForm and mechanize to automate web form submissions http://groups.google.com/group/comp.lang.python/browse_thread/thread/d544e5a719692775/ Started as: Where do they teach Python officially?, later discussing what's good for a programmer to know: http://groups.google.com/group/comp.lang.python/browse_thread/thread/fafd2b5042ab2453/ math.pow(3,50)!=3**50 -or- Don't use floating point exponentiation when you actually want an integer operation http://groups.google.com/group/comp.lang.python/browse_thread/thread/b2155e82b23e1bea/ Closures/Blocks in Python: what is good Ruby code style is not necesarily good for Python. http://groups.google.com/group/comp.lang.python/browse_thread/thread/7e3ee98e03731ecb/ How get "next month's" name: the orthodox ways, and a tricky one by Carsten Haese: http://groups.google.com/group/comp.lang.python/browse_thread/thread/1baa0d207ca55662/ ======================================================================== 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 gagsl-py2 at yahoo.com.ar Sun Jul 29 11:21:02 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 29 Jul 2007 12:21:02 -0300 Subject: Python 2.5.1 can't find win32file? References: <1185628601.992750.55990@e16g2000pri.googlegroups.com> <1185634068.634813.187350@e16g2000pri.googlegroups.com> Message-ID: En Sat, 28 Jul 2007 11:47:48 -0300, samwyse escribi?: > On Jul 28, 8:16 am, samwyse wrote: >> I just upgraded from 2.4.something to 2.5.1. I get the stuff below. >> I tried easy-installing pywin32; same results. Anyone know what's >> going on? > > Interestingly enough, this works: > > C:\Python25>path=%path%;C:\Python25\Lib\site-packages\pywin32-210- > py2.5-win32.eg > g\pywin32_system32 > > C:\Python25>python > Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit > (Intel)] on win32 > Type "help", "copyright", "credits" or "license" for more information. >>>> import win32file >>>> > > It looks like the system search path isn't getting updated so that > PYWINTYPES25.DLL can be found when win32file.pyd is loaded. I may be wrong, but I think eggs don't support external dlls. I don't use eggs, and downloading and installing pywin32 has always worked for me. -- Gabriel Genellina From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jul 10 17:44:37 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 10 Jul 2007 23:44:37 +0200 Subject: Best architecture for proxy? References: <1184076639.815417.48390@g4g2000hsf.googlegroups.com> Message-ID: <5ficu5F3cram2U4@mid.individual.net> Andrew Warkentin wrote: > I am going to write a general-purpose modular proxy in Python. It > will consist of a simple core and several modules for things like > filtering and caching. I am not sure whether it is better to use > multithreading, or to use an event-driven networking library like > Twisted or Medusa/ Asyncore. Which would be the better > architecture to use? I'd definitely use an event-driven approach with Twisted. Generally, multithreading is less performant than multiplexing. High performance servers mostly use a combination of both, though. Regards, Bj?rn -- BOFH excuse #306: CPU-angle has to be adjusted because of vibrations coming from the nearby road From kimiraikkonen85 at gmail.com Sun Jul 1 15:10:54 2007 From: kimiraikkonen85 at gmail.com (kimiraikkonen) Date: Sun, 01 Jul 2007 12:10:54 -0700 Subject: The best platform and editor for Python Message-ID: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> Hi, For experienced with Pyhton users, which developing software and enviroment would you suggest for Pyhton programming? Compiler+Editor +Debugger. Also what are your suggestions for beginners of Pyhton programming? Thank you. From arkanes at gmail.com Mon Jul 30 11:42:03 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 30 Jul 2007 10:42:03 -0500 Subject: How to write GUI and event separately in wxPython?? In-Reply-To: References: <1185777254.925902.204500@z28g2000prd.googlegroups.com> <5h5kmiF3hmufcU3@mid.uni-berlin.de> <5h5upbF3hmufcU5@mid.uni-berlin.de> Message-ID: <4866bea60707300842m4f81d37ay34d46d30a8885a6@mail.gmail.com> On 7/30/07, Steve Holden wrote: > Marc 'BlackJack' Rintsch wrote: > > On Mon, 30 Jul 2007 06:32:55 -0400, Steve Holden wrote: > > > >> >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)] > >> True > > > > First I thought: Why the unnecessary list comprehension but to my surprise: > > > > In [33]: xrange(42) == xrange(42) > > Out[33]: False > > > > That's strange. > > > Not so strange really. The two xrange objects are different (though I > confess I haven't looked to see how they implement comparisons), but > iterating over them produces the same result. nitpick: list(xrange(42)) == list(xrange(42)) is slightly more concise than the list comp.. From bbxx789_05ss at yahoo.com Mon Jul 30 02:21:22 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sun, 29 Jul 2007 23:21:22 -0700 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1185751725.882668.269850@i13g2000prf.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> <1184458002.961657.267830@x35g2000prf.googlegroups.com> <1184466882.446791.127670@x35g2000prf.googlegroups.com> <1185658013.859359.47700@57g2000hsv.googlegroups.com> <1185703671.241103.124780@g12g2000prg.googlegroups.com> <1185727058.306635.203130@b79g2000hse.googlegroups.com> <1185751725.882668.269850@i13g2000prf.googlegroups.com> Message-ID: <1185776482.804291.301200@g4g2000hsf.googlegroups.com> On Jul 29, 5:28 pm, Graham Dumpleton wrote: > On Jul 30, 2:37 am, 7stud wrote: > > > > > On Jul 29, 4:07 am, Graham Dumpleton > > wrote: > > > > Have you got an appropriate LoadModule directive in Apache > > > configuration to load the mod_python module? That you get this error > > > is indicative of mod_python module not being loaded. You can check the > > > Apache error logs to see if mod_python got loaded. > > > > See: > > > > http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking > > > > for more help on debugging. > > > That article says the LoadModule directive should be: > > > >LoadModule python_module libexec/mod_python.so > > > I saw this note in /Library/Apache2/conf/http.conf > > > # Configuration and logfile names: If the filenames you specify for > > many > > # of the server's control files begin with "/" (or "drive:/" for > > Win32), the > > # server will use that explicit path. If the filenames do *not* begin > > # with "/", the value of ServerRoot is prepended -- so "logs/foo.log" > > # with ServerRoot set to "/Library/Apache2" will be interpreted by the > > # server as "/Library/Apache2/logs/foo.log". > > > I have this server root in /Library/Apache2/conf/httpd.conf: > > > ServerRoot "/Library/Apache2" > > > So in the Load Module directive, the actual path to the mod_python.so > > file is: > > > /Library/Apache2/libexec/mod_python.so > > > But I checked and I don't have a /Library/Apache2/libexec directory. > > Run 'apxs' for the version of Apache you are using to work out what > the actual modules directory should be: > > $ /usr/local/apache-2.2.4/bin/apxs -q LIBEXECDIR > /usr/local/apache-2.2.4/modules > > If there is no mod_python.so in there then you can't have done the > mod_python install properly. Go back to the mod_python source code and > rerun: > > sudo make install_dso > > When you do that it will even tell you exactly what the LoadModule > line you should use is. > > Also ensure you actually installed the Python module components of > mod_python. You can redo that by running: > > sudo make install_py_lib > > Graham I posted *everything* I did to install mod_python in my second post. I just discovered there are additional steps I should have done, i.e. make and make install. After I did those steps, I looked at the output and there were no obvious errors. I then proceeded with the Testing section of the mod_python manual. I added the following LoadModule directive to my httpd.conf file: LoadModule python_module /Library/Apache2/modules/mod_python.so and I added the following to http.conf(I created the directory ../ htdocs/modPythonPages): AddHandler mod_python .py PythonHandler mptest PythonDebug On Then I started apache and it started up normally. Then I created a file called mptest.py in the ../htdocs/modPythonPages/ directory with this in it: from mod_python import apache def handler(req): req.content_type = "text/plain" req.write("Hello World!") return apache.OK But when I type the following url in my browser's address bar: http://localhost/modPythonPages/mptest.py all the text in the file is displayed--not the message "Hello World!". So I checked the Troubleshooting section, which said to add the following to httpd.conf: SetHandler mod_python PythonHandler mod_python.testhandler I did that, then restarted apache, and typed the following into my browser's address bar: http://localhost/mpinfo and I got a page displaying lots of information about my configuration, but I don't know how any of that helps me figure out what is wrong. I also get this with an interactive python session: >>> import mod_python.psp Traceback (most recent call last): File "", line 1, in ? File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/site-packages/mod_python/psp.py", line 21, in ? import apache, Session, util, _psp File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/site-packages/mod_python/apache.py", line 30, in ? import _apache ImportError: No module named _apache >>> import mod_python.testhandler Traceback (most recent call last): File "", line 1, in ? File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/site-packages/mod_python/testhandler.py", line 26, in ? from mod_python import apache, util File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/site-packages/mod_python/apache.py", line 30, in ? import _apache ImportError: No module named _apache >>> import mod_python >>> mod_python.version '3.3.1' >>> According to your article here: http://www.dscpl.com.au/wiki/ModPython/Articles/GettingModPythonWorking that output is as it should be. Following your article, I tried using a .htaccess file instead of putting the tags in httpd.conf. I deleted the tags I added to httpd.conf and restarted apache, but the same thing happened when I tried to display the page in my browser: the text in the file displayed instead of the message. So following along with your article, I added the following to httpd.conf: AllowOverride FileInfo I restarted apache, but I got the same results when I tried to access the page in my browser. BUT THEN...I somehow happened to do an: $ls -al on my modPythonPages directory and I got this: drwxr-xr-x 5 autie admin 170 Jul 29 23:24 . drwxrwxr-x 11 root admin 374 Jul 28 15:05 .. -rw-r--r-- 1 me admin 65 Jul 29 23:18 .htaccess.txt -rw-r--r-- 1 me admin 355 Jul 29 23:24 mptest.py As you can see when I saved the file, my mac added the .txt extension. Since my mac hides the files with a "." in front of them, I couldn't what the .htaccess file looked like in Finder after I saved the file--the file just disappeared. I can't find a way to make my mac display the "." files in Finder. So, I changed the name of the file: $mv .htacces.txt .htaccess and then I typed the following in my browser's address bar again: http://localhost/modPythonPages/mptest.py and this time I got the correct message: mptest.py Yeah! So is my install good? Why didn't the Directory tags in httpd.conf work? From greg at cosc.canterbury.ac.nz Tue Jul 10 06:21:41 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Tue, 10 Jul 2007 22:21:41 +1200 Subject: The best platform and editor for Python In-Reply-To: <1183644537.859604.27790@w5g2000hsg.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183644537.859604.27790@w5g2000hsg.googlegroups.com> Message-ID: <5fh546F3cmr4lU1@mid.individual.net> Nicola Musatti wrote: > It's in *commercial* projects that > features nobody really needs are not implemented. Profit is > fundamental in convincing you that you really need the features. In Soviet Russia, you don't need features, features need *you*. -- Greg From pbouige at electre.pasteur.fr Wed Jul 11 02:43:30 2007 From: pbouige at electre.pasteur.fr (Philippe Bouige) Date: Wed, 11 Jul 2007 06:43:30 +0000 (UTC) Subject: storing pickles in sql data base References: <592087469.jZQWuvoN0q@teancum> Message-ID: In article <592087469.jZQWuvoN0q at teancum>, David Bear wrote: >I need to store pickled objects in postgresql. You have this : http://blog.melhase.net/articles/2006/06/06/ a-tale-of-postgresql-types-and-python http://blog.melhase.net/articles/2006/06/13/ auto-postgresql-pickles Philippe Bouige From python at jayloden.com Sun Jul 22 01:18:22 2007 From: python at jayloden.com (Jay Loden) Date: Sun, 22 Jul 2007 01:18:22 -0400 Subject: [2.5] Regex doesn't support MULTILINE? In-Reply-To: References: Message-ID: <46A2E89E.4050509@jayloden.com> Gilles Ganault wrote: > Problem is, when I add re.DOTLINE, the search takes less than a second > for a 500KB file... and about 1mn30 for a file that's 1MB, with both > files holding similar contents. > > Why such a huge difference in performance? > > ========= Using Re ============= > import re > import time > > pattern = "(\d+:\d+).*?" > > pages = ["500KB.html","1MB.html"] > > #Veeeeeeeeeeery slow when parsing 1MB file ! > p = re.compile(pattern,re.IGNORECASE|re.MULTILINE|re.DOTALL) > #p = re.compile(pattern,re.IGNORECASE|re.MULTILINE) > > for page in pages: > f = open(page, "r") > response = f.read() > f.close() > > start = time.strftime("%H:%M:%S", time.localtime(time.time())) > print "before findall @ " + start > packed = p.findall(response) > if packed: > for item in packed: > print item > =========================== > I don't know if it'll result in a performance difference, but since you're just saving the result of re.findall() to a variable in order to iterate over it, you might as well just use re.finditer() instead: for item in p.finditer(response): print item At least then it can start printing as soon as it hits a match instead of needing to find all the matches first. -Jay From zentara at highstream.net Thu Jul 26 10:56:13 2007 From: zentara at highstream.net (zentara) Date: Thu, 26 Jul 2007 14:56:13 GMT Subject: I am giving up perl because of assholes on clpm -- switching to Python References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> Message-ID: On Wed, 25 Jul 2007 14:45:29 -0500, Martha_Jones at tx.net wrote: >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 This is where the big boys play, you have to be able to be able to scuffle and take punishment if you are wrong or unduly ignorant. You also need to squash somehow who attacks you, when you know you are right. I was watching a CNBC yesterday, and they interviewed a leading solar panel company's CEO. One guy just blasted him for no reason other than he gets a government subsidy, and even the moderator felt bad for the way the executive was blasted. BUT...... they are the big boys, playing for real money, and if you play there, you have to expect to have your toughness tested..... it means real profit and loss. If you want a better place to ask beginner questions, or to be treated with more respect, try the perl-beginners maillist or http://perlmonks.org. The monks are usually very polite. zentara -- I'm not really a human, but I play one on earth. http://zentara.net/japh.html From nowhere at a.com Thu Jul 5 16:57:32 2007 From: nowhere at a.com (Wojtek) Date: Thu, 05 Jul 2007 20:57:32 GMT Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: James Harris wrote : > I have a requirement to store timestamps in a database. Simple enough > you might think but finding a suitably general format is not easy. The > specifics are > > 2) not bounded by Unix timestamp 2038 limit I use the Java Calendar class for storing dates, which as I understand it, uses a long to store the date/time/milliseconds. In my application I use the date 9999.12.31 23:59:59.000 to store a blank date. Calendar has no problem storing that date, and returning the correct year, month, day, hour, minute, and second. Note: Since I am using the year 9999 as a "magic number", some of you may think that I am repeating the Y2K problem. Hey, if my application is still being used in the year 9998 I am not being paid nearly enough... -- Wojtek :-) From len-l at telus.net Sun Jul 1 13:27:33 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Sun, 01 Jul 2007 17:27:33 GMT Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> Message-ID: <9uRhi.17027$xk5.14289@edtnps82> Douglas Alan wrote: > Lenard Lindstrom writes: > >> Explicitly clear the exception? With sys.exc_clear? > > Yes. Is there a problem with that? > As long as nothing tries to re-raise the exception I doubt it breaks anything: >>> import sys >>> try: raise StandardError("Hello") except StandardError: sys.exc_clear() raise Traceback (most recent call last): File "", line 5, in raise TypeError: exceptions must be classes, instances, or strings (deprecated), not NoneType But it is like calling the garbage collector. You are tuning the program to ensure some resource isn't exhausted. It relies on implementation specific behavior to be provably reliable*. If this is indeed the most obvious way to do things in your particular use case then Python, and many other languages, is missing something. If the particular problem is isolated, formalized, and general solution found, then a PEP can be submitted. If accepted, this would ensure future and cross-platform compatibility. * reference counting is an integral part of the CPython C api so cannot be changed without breaking a lot of extension modules. It will remain as long as CPython is implemented in C. --- Lenard Lindstrom From dwarnold45 at suddenlink.net Sat Jul 7 02:59:22 2007 From: dwarnold45 at suddenlink.net (David) Date: Fri, 06 Jul 2007 23:59:22 -0700 Subject: malloc error for newbie Message-ID: <1183791562.999601.83790@z28g2000prd.googlegroups.com> Hi, Very new to python. When I uncomment the line # self.im.putpalette(mkpalette()) in the following code, I get the error: python $ ./mandelbrot.py Python(2860) malloc: *** Deallocation of a pointer not malloced: 0xff000000; This could be a double free(), or free() called with the middle of an allocated block; Try setting environment variable MallocHelp to see tools to help debug I don't have the expertise to get by this error. Can someone help? Thanks. #! /usr/local/bin/python # Filename: mandelbrot.py import Image, ImagePalette def mkpalette(): global palette palette = [0,0,0] for i in range(256): palette.extend([i*5%200+55,i*7%200+55,i*11%200+55]) return palette class Mandelbrot: def __init__(self,filename='mandelbrot.png', size=(512,512), n=64, box=((-2,1.25), (0.5,-1.25))): self.filename=filename self.size=size self.n=n self.uleft=box[0] self.lright=box[1] self.width=self.lright[0]-self.uleft[0] self.height=self.uleft[1]-self.lright[1] def newimage(self): self.im=Image.new('P', self.size) # self.im.putpalette(mkpalette()) def compute(self): self.newimage() def test(): f=Mandelbrot(filename='mandelbrot.png', size=(512,512), n=64, box=((-2,1.25), (0.5,-1.25))) f.compute() if __name__=='__main__': test() From m2i3k2000 at gmail.com Thu Jul 26 11:18:04 2007 From: m2i3k2000 at gmail.com (m2i3k) Date: Thu, 26 Jul 2007 08:18:04 -0700 Subject: ctypes:passing python class instances through c and back Message-ID: <1185463084.435165.260100@i38g2000prf.googlegroups.com> Hi I have C code with requires me to register a python callback. I am able to get the callback working well using ctypes if I use global functions without any context argument for the callback. Now I want to register a python class member function for callback, and give "self" as the context argument at the time of callback registration. Then the c code can invoke the callback with self as the context argument class SomeClass(object): def __init__(self): self.msg = 'Hello' def callbackMethod(context): # self = somemagic(context) <<<<<< how to convert this ptr back to instance??? print self.msg CALLBACK_FN_TYPE = WINFUNCTYPE(None,c_void_p) s=SomeClass() registerCallback(CALLBACK_FN_TYPE(s.callbackMethod),py_object(self)) If I print context that comes in the callback, it is the address of the instance 's'. Now how do I generate the class instance back from the void* context that is passed into the callback? From arkanes at gmail.com Sat Jul 28 14:15:12 2007 From: arkanes at gmail.com (Chris Mellon) Date: Sat, 28 Jul 2007 13:15:12 -0500 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? In-Reply-To: <0T49il77ItapNv8%stesch@parsec.no-spoon.de> References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> <0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de> <0T49iehiIt1hNv8%stesch@parsec.no-spoon.de> <46AB8194.2060906@web.de> <0T49il77ItapNv8%stesch@parsec.no-spoon.de> Message-ID: <4866bea60707281115sceea9d2pb8f6884369146fdf@mail.gmail.com> On 7/28/07, Stefan Scholl wrote: > Stefan Behnel wrote: > > Stefan Scholl wrote: > >> But the style of the answers makes me wonder if I should report > >> the bug in xml.sax (or its documentation) or just ignore it. > > > > Note that PyXML is no longer actively maintained, so it's unlikely that > > Too bad it can still be found in at least 80 % of all XML > examples. I should burn the XML chapter of the cookbook. > > By the way: Thanks for the tip regarding LXML. I'll try to > remember it for the next project. > > > > reporting the bug would get you a version that raises an exception when > > passing a unicode string *independent of the Python version*. > > > > Besides, the bug has been fixed in Python 2.5 already. > > Just checked on a system without PyXML: xml/sax/__init__.py > defines parseString() and uses cStringIO (when available). > > Python 2.5.1 > Yes, thats the fixed bug. After all this you still do not seem to be clear on what the bug is. The bug is not that your code fails in 2.5, it's that it worked at all in 2.4. From apetresc at uwaterloo.ca Thu Jul 19 15:15:06 2007 From: apetresc at uwaterloo.ca (Adrian Petrescu) Date: Thu, 19 Jul 2007 12:15:06 -0700 Subject: Interpreting os.lstat() In-Reply-To: <87vecger28.fsf@mulj.homelinux.net> References: <1184806559.224636.266500@e9g2000prf.googlegroups.com> <87vecger28.fsf@mulj.homelinux.net> Message-ID: <1184872506.044912.213940@q75g2000hsh.googlegroups.com> On Jul 19, 4:27 am, Hrvoje Niksic wrote: > Adrian Petrescu writes: > > I checked the online Python documentation athttp://python.org/doc/1.5.2/lib/module-stat.html > > but it just says to "consult the documentation for your system.". > > The page you're looking for is athttp://www.python.org/doc/current/lib/os-file-dir.html. For lstat it > says "Like stat(), but do not follow symbolic links." For stat it > says: > > 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) > [...] > 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.) Thank you, both Will and Hrvoje. Those links answer my questions. :) From nick at craig-wood.com Mon Jul 9 04:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 09 Jul 2007 03:30:06 -0500 Subject: How to Machine A python script execute Machine B python script? References: <1183945503.875939.292420@57g2000hsv.googlegroups.com> <1183948545.893438.305600@g37g2000prf.googlegroups.com> Message-ID: half.italian at gmail.com wrote: > On Jul 8, 6:45 pm, johnny wrote: > > Anyone know how I can make Machine A python script execute a python > > script on Machine B ? > > xmlrpc will work. Or pyro http://pyro.sourceforge.net/ Pyro is short for PYthon Remote Objects. It is an advanced and powerful Distributed Object Technology system written entirely in Python, that is designed to be very easy to use. Never worry about writing network communication code again, when using Pyro you just write your Python objects like you would normally. With only a few lines of extra code, Pyro takes care of the network communication between your objects once you split them over different machines on the network. All the gory socket programming details are taken care of, you just call a method on a remote object as if it were a local object! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From samwyse at gmail.com Fri Jul 13 12:53:08 2007 From: samwyse at gmail.com (samwyse) Date: Fri, 13 Jul 2007 09:53:08 -0700 Subject: Re-raising exceptions with modified message In-Reply-To: References: <1183863713.876365.111820@57g2000hsv.googlegroups.com> <1184239885.828717.271410@r34g2000hsd.googlegroups.com> <1184258925.321462.50270@k79g2000hse.googlegroups.com> Message-ID: <1184345588.791872.79010@d55g2000hsg.googlegroups.com> On Jul 13, 12:45 am, Christoph Zwerschke wrote: > samwyse wrote: > > TypeError: __class__ must be set to a class > > > Excpt ceratinly appears to be a class. Does anyone smarter than me > > know what's going on here? > > Not that I want to appear smarter, but I think the problem here is that > exceptions are new-style classes now, whereas Empty is an old-style > class. But even if you define Empty as a new-style class, it will not > work, you get: > > TypeError: __class__ assignment: only for heap types > > This tells us that we cannot change the attributes of a built-in > exception. If it would be possible, I simply would have overridden the > __str__ method of the original exception in the first place. > > -- Chris Chris, you owe me a beer if you're ever in St. Louis, or I'm ever in Germany. # ----- CUT HERE ----- # Written by Sam Denton # You may use, copy, or distribute this work, # as long as you give credit to the original author. # tested successfully under Python 2.4.1, 2.4.3, 2.5.1 """ On Jul 5, 2007, at 8:53 am, Christoph Zwerschke wrote: > What is the best way to re-raise any exception with a message > supplemented with additional information (e.g. line number in a > template)? Let's say for simplicity I just want to add "sorry" to > every exception message. Here is an example of typical usage: >>> def typical_usage(code): ... try: ... code() ... except Exception, e: ... simplicity = lambda self: str(e) + ", sorry!" ... raise modify_message(e, simplicity) Note that if we want to re-cycle the original exception's message, then we need our re-formatter (here called 'simplicity') to be defined inside the exception handler. I tried verious approaches to defining the re-formater, but all of them eventually needed a closure; I decided that I liked this approach best. This harness wraps the example so that doctest doesn't get upset. >>> def test_harness(code): ... try: ... typical_usage(code) ... except Exception, e: ... print "%s: %s" % (e.__class__.__name__, str(e)) Now for some test cases: >>> test_harness(lambda: 1/0) ZeroDivisionError: integer division or modulo by zero, sorry! >>> test_harness(lambda: unicode('\xe4')) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128), sorry! """ def modify_message(old, f): """modify_message(exception, mutator) --> exception Modifies the string representation of an exception. """ class NewStyle(old.__class__): def __init__(self): pass NewStyle.__name__ = old.__class__.__name__ NewStyle.__str__ = f new = NewStyle() new.__dict__ = old.__dict__.copy() return new def _test(): import doctest return doctest.testmod(verbose=True) if __name__ == "__main__": _test() From brotherjenos at gmail.com Tue Jul 17 17:57:16 2007 From: brotherjenos at gmail.com (Walker Lindley) Date: Tue, 17 Jul 2007 14:57:16 -0700 Subject: Pickled objects over the network Message-ID: <9c8d48280707171457p4448fdf3of40562bf62a18fc6@mail.gmail.com> I'm working on a distributed computing program and need to send Python objects over a TCP socket. Specifically, the objects that I'm working with subclass the builtin list type (I don't know whether or not that matters), but also include other data fields. These objects are put into dictionaries along with some other control information and the dictionaries are pickled and sent across the network. I'm using the makefile() function in socket to get a file descriptor for the socket and then calling pickle.dump with the dictionary object and the socket file descriptor. I was originally using pickle protocol 0, but then read about the possibility of buffering problems and realized that protocol 0 was giving me strings about 1500 characters long. After some testing, I settled on protocol 2 which manages to package the data into about 400 characters. In any case, the client side of the program appears to send the data just fine, at least as far as I can tell. On the server side, however, the data takes a very long time to get there and then I get an error in the pickle module: Traceback (most recent call last): File "server.py", line 176, in serv.runServer() File "server.py", line 99, in runServer recvPacket = pickle.load(clientFile) File "/usr/lib/python2.5/pickle.py", line 1370, in load return Unpickler(file).load() File "/usr/lib/python2.5/pickle.py", line 858, in load dispatch[key](self) File "/usr/lib/python2.5/pickle.py", line 1187, in load_appends mark = self.marker() File "/usr/lib/python2.5/pickle.py", line 874, in marker while stack[k] is not mark: k = k-1 IndexError: list index out of range Hopefully I'm doing something obviously wrong, but if anyone can help based on that description or if you need to see the source, please let me know (it's GPL'd). Thank you so much for any help. -Walker Lindley -- 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: From gagsl-py2 at yahoo.com.ar Mon Jul 23 21:36:14 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Jul 2007 22:36:14 -0300 Subject: Re-running unittest References: Message-ID: At 23/07/2007 09:59, "Israel Fern?ndez Cabrera" wrote: (Please keep posting on the list - many other people may have better ideas on this) > Well... probably my English and my intentions to not ti write > to much made my explanation unclear. The code I wrote was just > to illustrate my problem, is not the "real" code. Your > assumptions were OK, I?m loading the test inside and IDE, but > not IDLE. What I want to to is to "discover" the tests, and > then provide a GUI to execute them easily, like Eclipse does. > As you say, I get test objects and code objects created that is > why I use reload to "refresh" the module object. My concern is > that in the sample code, all the Unittest related objects are > recreated and the objects are loaded from a string before > executing the tests, but still they remain in memory. > I have used "reload" just to prove the problem could be fixed > like that, to confirm the source of the problem, I agree this > is not a good solution. > The fixing test looks strange but was the easier way I found to > reproduce the problem since the test does not actually "test" > any outside object, was just a way to change the passing/no > passing status of the test. > Thks for your time hope this time I made myself clear ;) I think you can't use reload in this scenario. Your framework would have to know which modules to reload, which names to rebind, which imports to re-execute, which objects to re-create... Reloading without intimate knowledge of how the reloaded module is used is hard, if not impossible. Perhaps the best option is to run the tests in another process. Use any of the available IPC mechanisms to gather the test results. This has the added advantage of isolating the tested code from your GUI testing framework; all requested resources are released to the OS; the tests run in a predictable environment; etc. From nospam-abuse at ilyaz.org Thu Jul 5 16:48:08 2007 From: nospam-abuse at ilyaz.org (Ilya Zakharevich) Date: Thu, 5 Jul 2007 20:48:08 +0000 (UTC) Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <1183576255.668414.256990@q69g2000hsb.googlegroups.com> <5f31fvF3asl6lU1@mid.individual.net> <1183665370.643503.157060@m36g2000hse.googlegroups.com> Message-ID: [A complimentary Cc of this posting was sent to James Harris ], who wrote in article <1183665370.643503.157060 at m36g2000hse.googlegroups.com>: > On 5 Jul, 02:53, greg wrote: > > James Harris wrote: > > > With that the time would range to +/- 9000 > > > quintillion years (18 digits) > > > > Use the Big Bang as the epoch, and you won't have > > to worry about negative timestamps. In pedantic mode: negative timestamps make sense with Big Bang as the epoch as well. (AFAIU, the current way of thinking is that it was "just too hot" before the big bang, it is not that "there was nothing".) Hope this helps, Ilya From sjmachin at lexicon.net Mon Jul 2 05:16:15 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 02 Jul 2007 02:16:15 -0700 Subject: Probably simple syntax error In-Reply-To: <1183351228.878746.233430@o61g2000hsh.googlegroups.com> References: <1183351228.878746.233430@o61g2000hsh.googlegroups.com> Message-ID: <1183367775.360977.201520@m37g2000prh.googlegroups.com> On Jul 2, 2:40 pm, Dustin MacDonald wrote: > Hi everyone. > > This is my first time posting to this newsgroup, and although I > maintain my netiquette I might've missed something specific to the > newsgroup, so hopefully you can avoid flaming me if I have :) I > apologize for the length of this post but I figure the more > information the better. The more relevant information the better. It would have helped had you shown (a) the first use of weights_array (b) your import statements > > My problem is that I'm getting a syntax error in some Python code that > looks quite simple. The original code was in Object Pascal as I'm a > recent Delphi-turned-Python programmer. > > I took the code (which is only about 130 lines in OP) and 'translated' > it the best I could into Python (ended up being one line shy of 80 > when I was done). I can't see any problems with the code but it's > coming up with a bunch of errors, which I'm guessing are probably my > assuming something is the same in Python as it is in Pascal, and being > wrong. > > Anyway, here's the code I'm having trouble with (the same error comes > up several times but this is the first part of the code it shows up > in): Others have pointed out that the likely source of your first problem is using () instead of [] for list subscripting. I'll move on to the next few ... > > [code] > randomizing_counter = 0 > # Put the loop counter for the randomizing to zero. Problem 2: excessive verbosity > until_val = 36 > # Set the "until val" to 36. We'll compare them to make sure we're not > at the end of our wordlist_both. > > while randomizing_counter < until_val: Try this: weights_array = [] assert len(wordlist_both) == 36 # ??? for _unused in range(len(wordlist_both)): # calculate something weights_array.append(something) > big_randomized_int = RandRange(0,100) Problem 3a: You have an import statement like import random in which case you would get a runtime error, and should have: .... = random.randrange(0, 100) or Problem 3b: You have an import statement like: from random import randrange as RandRange which will not cause a runtime error, merely mass barfing among the spectators :-) > # Make a random value and store it. > small_randomized_int = big_randomized_int / 100 Problem 5: putting comments after the code instead of on the same line as the statement you think needs explanation (most don't) or before it. > # Divide that random value and store it in a different variable. Problem 6: big_randomized_int can only have values in 0, 1, ..., 98, 99. So small_randomized_int will have the value 0, always. Perhaps you meant: small_randomised_float = big_randomized_int / 100.0 > small_randomized_int = Round(small_randomized_int, 2) > # Round that value to 2 decimal places Problem 7: even if you did intend big.... / 100.00, the above is redundant. 1 / 100.0 is 0.01, 99 / 100.0 is 0.99 -- no rounding is necessary. Problem 8: it's round(), not Round() > **weights_array(randomizing_counter) = small_randomized_int > # Assign the first randomized value to our first word to be weighted. First? It's done each time around the loop. > randomizing_counter = randomizing_counter + 1 > # Up the counter and repeat. > [/code] > So, here's the looping version: weights_array = [] for _unused in range(len(wordlist_both)): weights_array.append(random.randrange(100) / 100.0) and here's the obligatory one-liner, using a list comprehension: weights_array = [random.randrange(100) / 100.0 for _unused in range(len(wordlist_both))] and here's an example of it in use: >>> import random >>> wordlist_both = 10 * ['foo'] >>> weights_array = [random.randrange(100) / 100.0 for _unused in range(len(wordlist_both))] >>> weights_array [0.38, 0.12, 0.55000000000000004, 0.23999999999999999, 0.91000000000000003, 0.48999999999999999, 0.91000000000000003, 0.67000000000000004, 0.77000000000000002, 0.81999999999999995] >>> Problem 9: you were expecting "precise" values like 0.55 and 0.24. Solution is to read this: http://docs.python.org/tut/node16.html HTH, John From clj2289 at gmail.com Wed Jul 11 18:50:26 2007 From: clj2289 at gmail.com (clj2289 at gmail.com) Date: Wed, 11 Jul 2007 22:50:26 -0000 Subject: Phoenix-iTorrent: iTunes Bit Torrent client v 0.3 release In-Reply-To: References: Message-ID: <1184194226.475188.85370@22g2000hsm.googlegroups.com> On Jul 10, 1:50 pm, "Danyelle Gragsone" wrote: > How is this related to python? Hi Danyelle, Phoenix-iTorrent, as well as its Bit Torrent underpinnings, is written completely in python. Both projects use py2exe and py2app to create native binaries for the Windows and Mac OS X platform. I hope that you find it useful and enjoy using it. All the best, Chris From jeffbg123 at gmail.com Thu Jul 12 09:01:30 2007 From: jeffbg123 at gmail.com (jeffbg123) Date: Thu, 12 Jul 2007 13:01:30 -0000 Subject: Screen Scraping Question In-Reply-To: References: <1184157921.488811.295570@n60g2000hse.googlegroups.com> Message-ID: <1184245290.056488.178630@57g2000hsv.googlegroups.com> On Jul 11, 10:31 pm, Dan Stromberg - Datallegro wrote: > On Wed, 11 Jul 2007 12:45:21 +0000, jeffbg123 wrote: > > Hey, > > > I am trying to make a bot for a flash game using python. However I am > > having some trouble with a screen scraping strategy. Is there an > > accepted way to compare a full screenshot with the image that I want > > to locate? It is a math based game, so I just have to check what > > number, 1-9, appears in the center of the flash game. Is there an > > easier method to do this? > > > Thanks > > > -Jeff > > That sounds like an OCR problem, unless the numbers are so consistently > rendered that you can just store copies of all 9 (I'd pick a non-lossy > format) and compare. The numbers are always rendered the same. So I don't know if OCR is a necessary step. Also, what if I just got the data from the packets? Any disadvantages to that? Any good python packet capturing libraries? Thanks From kay.schluehr at gmx.net Thu Jul 5 17:13:29 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Thu, 05 Jul 2007 14:13:29 -0700 Subject: The best platform and editor for Python In-Reply-To: <1183655933.475488.157270@m36g2000hse.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183646799.400176.144570@k79g2000hse.googlegroups.com> <1183655933.475488.157270@m36g2000hse.googlegroups.com> Message-ID: <1183670009.035673.256680@w5g2000hsg.googlegroups.com> On Jul 5, 7:18 pm, kimiraikkonen wrote: > I just wanted a simple answer to my simple question, however topic has > messed up. Think questioner as a beginner and use more understandable > terms to help :) > > Thanks. The problem is simply that the Python community has failed in this respect. There are many platform dependent and ideology driven ways to do deal with code editing / debugging but not actually a recommend or "pythonic" way. Other than Smalltalk, Python has not created an own style / identity regarding decent development environments and since half of the community is happy with Emacs and the other half wants to program in a VS-like environment, neither consensus nor progress has to be expected. If you use Google groups to access comp.lang.python you will also recognize that your question comes up every few weeks so it has a certain tradition to create the same spectrum of answers. From half.italian at gmail.com Sun Jul 8 22:35:45 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Mon, 09 Jul 2007 02:35:45 -0000 Subject: How to Machine A python script execute Machine B python script? In-Reply-To: <1183945503.875939.292420@57g2000hsv.googlegroups.com> References: <1183945503.875939.292420@57g2000hsv.googlegroups.com> Message-ID: <1183948545.893438.305600@g37g2000prf.googlegroups.com> On Jul 8, 6:45 pm, johnny wrote: > Anyone know how I can make Machine A python script execute a python > script on Machine B ? xmlrpc will work. ~Sean From python at jayloden.com Thu Jul 26 03:53:25 2007 From: python at jayloden.com (Jay Loden) Date: Thu, 26 Jul 2007 03:53:25 -0400 Subject: How to tell when a socket is closed on the other end? In-Reply-To: References: <1185371863.622473.205010@19g2000hsx.googlegroups.com> Message-ID: <46A852F5.8000907@jayloden.com> Roy Smith wrote: > In article <1185371863.622473.205010 at 19g2000hsx.googlegroups.com>, > billiejoex wrote: > >> Hi there. >> I'm setting up test suite for a project of mine. >> >From test suite, acting as a client, I'd like to know, in certain >> situations, if the socket is closed on the other end or not. >> I noticed that I can "detect" such state if a call to socket.read() >> returns 0 but it seems a little poor to me. :-\ >> Is there a reliable way to test such socket 'state'? > > This isn't really a Python question, it's a Berkeley Socket API question. > You don't say, but I assume you're talking about a TCP (i.e. SOCKSTREAM) > connection? > > The answer is you can use the select() system call to detect "exceptional > conditions" on a socket. Python's select module provides this > functionality, but to understand how to use it, you need to study the > underlying API. Thanks for the interesting information and suggestion of using select(). You are correct that this is actually mostly a socket API question but pertains to Python since the code is all Python's socket and asyncore modules. It might help to step back and explain the original problem. The goal of this portion of the test suite we are writing for the project is to determine if a remote server is behaving properly by closing a socket from the server side based on a client-side command. Really what's needed is a way to make sure the socket gets closed, and preferably determine if it was closed from the remote end as expected. Do you know if this is possible to determine from the client side reliably/accurately? Would select()'s exceptional condition flag actually indicate whether or not the root cause of the condition was a socket closed by the remote peer? I've read through the select's manpage and I can't seem to find a reference that indicates what the possible values are for the I/O descriptor sets returned by select. Is there another man page, or a place in the header file for select I can look? Thanks for your help, -Jay From steveandleyla at gmail.com Sun Jul 1 18:53:30 2007 From: steveandleyla at gmail.com (steveandleyla at gmail.com) Date: Sun, 01 Jul 2007 15:53:30 -0700 Subject: what is the PythonWin Message-ID: <1183330410.164963.151790@c77g2000hse.googlegroups.com> I downloaded Python 5.1 for windows so I could run a program. I have to do the following: In PythonWin, select Tools | COM MakePy utility | Microsoft Speech Object Library 5.1). I can't find PythonWin .. Does anybody know what this is. I have the Python shell gui but no "PythonWin". THanks. From stargaming at gmail.com Thu Jul 12 03:46:16 2007 From: stargaming at gmail.com (Stargaming) Date: Thu, 12 Jul 2007 09:46:16 +0200 Subject: bool behavior in Python 3000? In-Reply-To: References: <5ficp9F3cram2U2@mid.individual.net> <469472f4$0$1293$9b622d9e@news.freenet.de> Message-ID: <4695dc48$0$13186$9b622d9e@news.freenet.de> Steven D'Aprano schrieb: > On Wed, 11 Jul 2007 08:04:33 +0200, Stargaming wrote: > > > >>No, I think Bjoern just wanted to point out that all those binary >>boolean operators already work *perfectly*. You just have to emphasize >>that you're doing boolean algebra there, using `bool()`. >>"Explicit is better than implicit." > > > > So we should always write things explicitly like: > > if bool(bool(some_condition) is True) is True: > first_line = str(some_string).split(str("\n"))[int(0)] > n = int(int(len(list(some_list))) + int(1)) > elif bool(bool(some_condition) is False) is True: > f = float(math.sin(float(6.0)/float(math.pi))) > > instead of the less explicit code. I'll try to remember that, thank you > for the advice. > > > You're missing like 400 bool(...) is True constructs there! Fatal error, recursion depth reached. Aww! From ahlongxp at gmail.com Fri Jul 13 10:57:44 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Fri, 13 Jul 2007 14:57:44 -0000 Subject: bool behavior in Python 3000? In-Reply-To: <5ficedF3cram2U1@mid.individual.net> References: <5ficedF3cram2U1@mid.individual.net> Message-ID: <1184338664.047759.309940@g37g2000prf.googlegroups.com> On Jul 11, 5:36 am, Bjoern Schliessmann wrote: > Is there any type named "bool" in standard Python? check this out. >>> doespythonrock = True >>> print type(doespythonrock) >>> -- ahlongxp Software College,Northeastern University,China ahlongxp at gmail.com http://www.herofit.cn From cam.ac.uk at mh391.invalid Tue Jul 10 12:18:17 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 10 Jul 2007 17:18:17 +0100 Subject: bool behavior in Python 3000? In-Reply-To: References: Message-ID: Alan Isaac wrote: > Is there any discussion of having real booleans > in Python 3000? I'm not sure how the bools we have now are not "real." > Say something along the line of the numpy implementation for arrays of > type 'bool'? What aspect of this do you want? A bool typecode for the stdlib array module? I can guess a number of things that you might mean, but it would be best if you explained with an example of what current behavior is and what you would like it to be. -- Michael Hoffman From rkmr.em at gmail.com Mon Jul 30 10:43:23 2007 From: rkmr.em at gmail.com (rkmr.em at gmail.com) Date: Mon, 30 Jul 2007 07:43:23 -0700 Subject: making a variable available in a function from decorator In-Reply-To: <5h5e3lF3hmufcU1@mid.uni-berlin.de> References: <5h5e3lF3hmufcU1@mid.uni-berlin.de> Message-ID: is it possible to do this without passing it as a function argument? On 30 Jul 2007 06:17:25 GMT, Marc 'BlackJack' Rintsch wrote: > On Sun, 29 Jul 2007 15:22:47 -0700, rkmr.em at gmail.com wrote: > > > I create a variable in a decorator. i want to be able to access that > > variable in the function to be decorated. How to do this? > > Pass it as argument to the function: > > def deco(func): > eggs = 42 > def decorated(*args, **kwargs): > kwargs['spam'] = eggs > func(*args, **kwargs) > return decorated > > @deco > def test(parrot, spam): > print parrot, spam > > Ciao, > Marc 'BlackJack' Rintsch > -- > http://mail.python.org/mailman/listinfo/python-list > From dral at informatik.tu-chemnitz.de Mon Jul 9 03:06:37 2007 From: dral at informatik.tu-chemnitz.de (Alexander Draeger) Date: Mon, 09 Jul 2007 09:06:37 +0200 Subject: Decorating instance methods Message-ID: Hello everybody, I'm very interesting in using the decorator concept, but I can't convert it in useful things. I have read many about decorators and have seen a lot of examples, but I search a possibility, to decorate methods of classes with reference to the instances. For example: I have a class A: class A(object): def __init__(self, name): self.name=name @logging def hello(self, name): print 'Hello World.' >>>a=A('Ernie') >>>b=A('Bert') >>>a.hello() Entering a method. [Ernie] Hello World. >>>b.hello() Entering a method. [Bert] Hello World. How should I implement the function logging, when I want to use the variable self.name for the logging message? Alex From p at ulmcnett.com Sun Jul 22 13:48:10 2007 From: p at ulmcnett.com (Paul McNett) Date: Sun, 22 Jul 2007 10:48:10 -0700 Subject: Advice on sending images to clients over network In-Reply-To: <1185095666.627415.108450@w3g2000hsg.googlegroups.com> References: <1185095666.627415.108450@w3g2000hsg.googlegroups.com> Message-ID: <46A3985A.9080805@ulmcnett.com> Frank Millman wrote: > I guess the point of all this rambling is that my thought process is > leading me towards my third option, but this would be a bit of work to > set up, so I would appreciate any comments from anyone who has been > down this road before - do I make sense, or are there better ways to > handle this? > > Any suggestions will be much appreciated. I would put the images into a static web directory, either on the same or different server. Then your main server just sends the url (or relevant portion of the url, or list of all urls to download), and then the client grabs the images from your image server using urllib. Let Apache do what it's good at, instead of reinventing that particular wheel. -- pkm ~ http://paulmcnett.com From mensanator at aol.com Sat Jul 28 10:43:22 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Sat, 28 Jul 2007 07:43:22 -0700 Subject: 128 or 96 bit integer types? In-Reply-To: <7xlkd1ugvn.fsf@ruckus.brouhaha.com> References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com> <1185562901.206212.52570@j4g2000prf.googlegroups.com> <1185607142.096574.209200@e16g2000pri.googlegroups.com> <7xlkd1ugvn.fsf@ruckus.brouhaha.com> Message-ID: <1185633802.749134.258120@m37g2000prh.googlegroups.com> On Jul 28, 2:28?am, Paul Rubin wrote: > "mensana... at aol.com" writes: > > has 146 digits. And that's just the begining. The above > > actually represents a polynomial with 264 terms, the > > exponents of which range from 0 to 492. One of those > > polynomials can have over 50000 decimal digits when > > solved. > > You should use gmpy rather than python longs if you're dealing with > numbers of that size. Python multiplication uses a straightforward > O(n**2) algorithm where n is the number of digits. This is the best > way for up to a few hundred or maybe a few thousand digits. After > that, it's better to use more complicated FFT-based algorithms which > are O(n log n) despite their increased constant overhead. Gmpy does this. I actually do use gmpy. Great stuff. But one thing I learned about gmpy is to never use literals inside a loop. Otherwise the mpz coercion has to be done every time and that kills performance. So you would do something like import gmpy ONE = gmpy.mpz(1) TWO = gmpy.mpz(2) TWE = gmpy.mpz(3) n = gmpy.mpz(2**177149-1) while n > ONE: if n % TWO == 1 n = TWE*n + ONE else: n = n/TWO From evan at yelp.com Fri Jul 13 14:13:37 2007 From: evan at yelp.com (Evan Klitzke) Date: Fri, 13 Jul 2007 11:13:37 -0700 Subject: Fast powerset function In-Reply-To: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> References: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> Message-ID: On 7/12/07, Arash Arfaee wrote: > I need a powerset generator function. It's really slow with recursion. Does > anybody have any idea or code(!!) to do it in an acceptable time? > Thanks > -Arash Here's a much simpler (and faster) solution I got from a coworker: s = range(18) result = [] l = len(s) for i in range(2**l): n = i x = [] for j in range(l): if n & 1: x.append(s[j]) n >>= 1 result.append(x) print result -- Evan Klitzke From evan at yelp.com Fri Jul 13 02:53:02 2007 From: evan at yelp.com (Evan Klitzke) Date: Thu, 12 Jul 2007 23:53:02 -0700 Subject: Fast powerset function In-Reply-To: References: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> Message-ID: On 7/12/07, Evan Klitzke wrote: > On 7/12/07, Arash Arfaee wrote: > > I need a powerset generator function. It's really slow with recursion. Does > > anybody have any idea or code(!!) to do it in an acceptable time? > > Thanks > > -Arash > > I thought that this was a really interesting question, so I wrote up a > solution that doesn't use recursion. I didn't test it a whole lot, but > I'm pretty sure it works -- let me know if there are any oversights or > if you can make any improvements ;-) Also, not sure if the line breaks > will be mangled by my mail client, so bear with me if there are any > errors. > > def fact(n): > '''Factorial''' > r = 1 > for i in xrange(1, n + 1): > r *= i > return r > > def nCr(n, r): > '''Number of combinations of r items from n things''' > return fact(n) / (fact(r) * fact(n - r)) > > def get_combinations(slots, tokens): > '''A generator yielding combinations from slots of size tokens''' > maxcombos = nCr(len(slots), tokens) > for index in xrange(maxcombos): > token_copy = tokens > combo = [] > for val in xrange(1, len(slots) + 1): > if not token_copy: > break > thresh = nCr(len(slots) - val, token_copy - 1) > if index < thresh: > combo.append(slots[val-1]) > token_copy -= 1 > else: > index -= thresh > yield tuple(combo) > > def powerset(s): > '''Returns the powerset of s''' > pset = set() > for num_tokens in xrange(1, len(s)): > for combo in get_combinations(s, num_tokens): > pset.add(combo) > # These two are special cases > pset.add(s) > pset.add(tuple()) > return pset > > if __name__ == '__main__': > print powerset((1, 2, 3, 4)) One more obvious thing that I omitted. You can make this a lot faster by caching the values of nCr. This is a simple modification, that I'll leave to the reader ;-) -- Evan Klitzke From len-l at telus.net Sat Jul 14 17:11:00 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Sat, 14 Jul 2007 21:11:00 GMT Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <5dveb4F360un0U1@mid.individual.net><7xd4za1086.fsf@ruckus.brouhaha.com><5f0mhuF3b0stbU1@mid.individual.net><7xd4z837e2.fsf@ruckus.brouhaha.com><468b7426$0$9063$426a34cc@news.free.fr><7x4pkkun56.fsf@ruckus.brouhaha.com><1183575597.272150.152200@w5g2000hsg.googlegroups.com><7xzm2budfv.fsf@ruckus.brouhaha.com><7xir8vju1l.fsf@ruckus.brouhaha.com><7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: Hendrik van Rooyen wrote: > "Lenard Lindstrom" wrote: > > >> Pascal has no break, continue or return. Eiffel doesn't even have a >> goto. In such imperative languages boolean variables are used a lot. > > Thanks did not know this. > >> from StringIO import StringIO >> lines = StringIO("one\ntwo\nthree\nfour\n") >> line_number = 0 >> eof = False >> found = False >> while not (eof or found): >> line = lines.readline() >> eof = line == "" >> found = line == "three\n" >> if not found: >> line_number += 1 >> >> >> if found: >> print "Found at", line_number >> else: >> print "Not found" >> # prints "Found at 2" >> > > All right, so it is possible, with some legerdemain, > forcing the main loop to stop when the condition > is met. > However, I find the above as clear as mud, compared to: > > line_number = 0 > > for line in my_file: > line_number += 1 > if "the Target" in line: > break > > print line_number, line > > - Hendrik > I am not defending Pascal or similar languages. Pascal was an educational language designed to teach structured programming by removing temptation. The same example in Pascal would be less convoluted, thought, since Pascal has an explicit end-of-file test function (No, this is not a Python feature request.) Personally I don't miss the continuous retesting of conditions made necessary in Pascal. --- Lenard Lindstrom From steve at REMOVE.THIS.cybersource.com.au Tue Jul 17 09:06:45 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 17 Jul 2007 23:06:45 +1000 Subject: Dict Help References: Message-ID: On Tue, 17 Jul 2007 10:57:29 +0100, Robert Rawlins - Think Blue wrote: > Morning Gabriel, > > I'm looking for a little more advice on this dictionary/list to > defaultdict/set conversion that we were talking about, there were a few > things I was looking to clarify. Firstly, what is the difference between a > standard dict and a default dict? Is it purely a performance issue? >From an interactive prompt, execute the following lines: help(dict) import collections help(collections.defaultdict) A defaultdict is just like a dict except that it calls a function (specified at init time) whenever a missing key is found. Compare: >>> d = collections.defaultdict(lambda: 42) # new empty defaultdict >>> d defaultdict( at 0xb7eb4ed4>, {}) >>> d[0] # key is missing 42 >>> d defaultdict( at 0xb7eb4ed4>, {0: 42}) >>> d = {} # new empty dict >>> d.setdefault(0, 42) 42 >>> d {0: 42} > This dict is likely to grow pretty large What is "pretty large" to you or me is not necessarily large to the computer. How many keys are you thinking it will have? > and is read/written on a very > regular basis so the better performing one is going to work best for me. Python dicts are extremely efficient hash tables. They perform extremely well and are heavily optimized. > Also, am I still able to iterate over a set in the same way I can a list? Why don't you try it for yourself? for x in set([1, 2, 3]): print x > Here is an example of my add function at the moment, how can that be > converted to a defaultdict/set instead of the dict/list approach? > > self.History = {} > > def addHistory(self, address, media): > if address not in self.History: > self.History[address] = [] > > self.History[address].append(media) def addHistory(self, address, media): self.history.setdefault(address, []).append(media) -- Steven From kyosohma at gmail.com Thu Jul 19 10:07:33 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 19 Jul 2007 07:07:33 -0700 Subject: Real-time Update In-Reply-To: References: <1184747090.102324.265230@i13g2000prf.googlegroups.com> Message-ID: <1184854053.993871.268340@j4g2000prf.googlegroups.com> On Jul 18, 4:43 pm, a... at pythoncraft.com (Aahz) wrote: > In article <1184747090.102324.265... at i13g2000prf.googlegroups.com>, > > ReTrY wrote: > > >I'm writing a program with Tkinter GUI, When the program is running it > >need to be updated every five seconds (data comes from internet). How > >should I do that ? How to make a function in main loop ? > > See the Tkinter example from my threads tutorial on my website. > -- > Aahz (a... at pythoncraft.com) <*> http://www.pythoncraft.com/ > > I support the RKAB There's also a good example on the wxPython wiki dealing with threads that you should be able to adapt to Tkinter. http://wiki.wxpython.org/LongRunningTasks Mike From kyosohma at gmail.com Sun Jul 1 13:47:24 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sun, 01 Jul 2007 10:47:24 -0700 Subject: Python + Google Calendar API issue In-Reply-To: <5epk7jF39ch77U1@mid.uni-berlin.de> References: <1183246269.152344.3510@c77g2000hse.googlegroups.com> <5epk7jF39ch77U1@mid.uni-berlin.de> Message-ID: <1183312044.591626.133240@n60g2000hse.googlegroups.com> On Jul 1, 7:15 am, "Diez B. Roggisch" wrote: > kyoso... at gmail.com schrieb: > > > > > Hi, > > > I was trying to hook into Google Calendar today using their gdata > > module for Python, but I can't seem to get Python to work with it. > > When I run the setup.py from the command line, I get the following: > > > Traceback (most recent call last): > > File "J:\Python\Lib\site-packages\gdata\setup.py", line 39, in ? > > package_dir = {'gdata':'src/gdata', 'atom':'src/atom'} > > File "J:\Python\lib\distutils\core.py", line 137, in setup > > raise SystemExit, gen_usage(dist.script_name) + "\nerror: %s" % > > msg > > SystemExit: usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 > > [cmd2_opts] ...] > > or: setup.py --help [cmd1 cmd2 ...] > > or: setup.py --help-commands > > or: setup.py cmd --help > > > error: no commands supplied > > > I tried using some different commands, like --verbose, but it would > > just give me the same traceback. I also tried manually copying all the > > files into my site-packages directory (as you can see from the > > traceback) in hopes that it might work without running the setup.py > > file. > > > Does anyone have any ideas? I don't usually have any problem getting > > these things to work. I am using Python 2.4.3 on Windows XP Pro SP2. > > Did you supply an install command: > > python setup.py install > > --verbose is no command. > > Diez Oops. When I typed it gave me lots of info, but I guess I mis- read it. Turns out you were quite right and that all I needed was the "install" command. Thanks a lot! Mike From westymatt at gmail.com Thu Jul 26 11:10:23 2007 From: westymatt at gmail.com (matt westerburg) Date: Thu, 26 Jul 2007 11:10:23 -0400 Subject: Fwd: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: <4b490f2f0707260809v362c2c72t73f1fd3dbf2cb45e@mail.gmail.com> References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> <4b490f2f0707260809v362c2c72t73f1fd3dbf2cb45e@mail.gmail.com> Message-ID: <4b490f2f0707260810qe4a410co366291a6dccd4f01@mail.gmail.com> ---------- Forwarded message ---------- From: matt westerburg Date: Jul 26, 2007 11:09 AM Subject: Re: I am giving up perl because of assholes on clpm -- switching to Python To: zentara Welcome, the people here are friendly occasional argument, not very often of course. Welcome to python by the way. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Mon Jul 16 02:28:45 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 16 Jul 2007 08:28:45 +0200 Subject: Access Object From 2 Applications or Fix Scheduler References: <015201c7c71a$2be05df0$83a119d0$@rawlins@thinkbluemedia.co.uk> Message-ID: <00a501c7c776$900ba8a0$03000080@hendrik> Robert Rawlins - Think Blue wrote: >Hello Guys, > >I have two applications which I need to get talking and sharing an object, what ?s the best way to do this? Basically my >first application parses an XML document into a bunch of lists and tuples etc, and I need to access the data in these lists >and tuples from my second application. Is this possible? And what?s the simplest method? > >This problem all evolves from a hack/work around I?ve had to place together as I have been having problems with >sched, these two applications used to be a single one to start with but for some reason when scheduling tasks using the >sched module they wouldn?t ever run when supposed too, so I?d schedule it to run every 2 minutes and it would run >between 3 and 15 minutes :-s so I ripped it out into its own application and it now runs every 2 minutes exactly. > >I either need to fix my sched issues or the memory share, either way I?m quite happy, just need to get it working >smoothly. > >Any ideas? > You have already split the thing, so I would: schedule the XML parser and make it do its stuff. then pickle the results using cPickle then from this first thing, either: write the pickles to temp files and start the second thing using eg os.system() or start the second thing and use a named pipe to pass the pickles over for unpickling and processing, or use one of the popens, or have a look at Pyro, or start the second thing as a thread and use a Queue.. of course this whole scheme will fall apart if the combined processing takes longer than the scheduling interval. HTH - Hendrik From rvanroode at gmail.com Tue Jul 10 06:23:52 2007 From: rvanroode at gmail.com (rvr) Date: Tue, 10 Jul 2007 10:23:52 -0000 Subject: stripping the first byte from a binary file Message-ID: <1184063032.195000.25880@i13g2000prf.googlegroups.com> Would someone mind showing me how to strip the first byte from a binary file? For some reason I can't figure this out from the binary file editing examples I've read. Thanks. ~rvr From alia_khouri at yahoo.com Sun Jul 22 18:47:53 2007 From: alia_khouri at yahoo.com (Alia Khouri) Date: Sun, 22 Jul 2007 15:47:53 -0700 Subject: recursively expanding $references in dictionaries Message-ID: <1185144473.592477.27570@w3g2000hsg.googlegroups.com> I was kind of wondering what ways are out there to elegantly expand '$name' identifiers in nested dictionary value. The problem arose when I wanted to include that kind of functionality to dicts read from yaml files such that: def func(input): # do something return output where: input = {'firstname': 'John', 'lastname': 'Smith', 'src': 'c:/tmp/ file', 'dir': {'path': '$src', 'fullname': '$firstname $lastname'}} output = {'firstname': 'John', 'lastname': 'Smith', 'src': 'c:/tmp/ file', 'dir': {'path': 'c:/tmp/file', 'fullname': 'John Smith'}} Doing this substitution easy done when you have a flat dict, but when they got nested, I had to resort to an undoubtedly ugly function with two recursive passes and obvious deficiencies. Is there a better way to do this? Thanks for any help... AK # test_recurse.py from string import Template from pprint import pprint def expand(dikt): ''' >>> d = expand2({'firstname': 'John', 'lastname': 'Smith', 'fullname': '$firstname $lastname'}) >>> d == {'lastname': 'Smith', 'fullname': 'John Smith', 'firstname': 'John'} True ''' subs = {} for key, value in dikt.items(): if '$' in value: subs[key] = Template(value).substitute(dikt) dikt.update(subs) return dikt dikt = {'firstname': 'John', 'lastname': 'Smith', 'fullname': '$firstname $lastname'} #~ print expand(dikt) d1 = {'firstname': 'John', 'lastname': 'Smith', 'dir': {'fullname': '$firstname $lastname'} } d2 = {'firstname': 'John', 'lastname': 'Smith', 'src': 'c:/tmp/file', 'dir': {'fullname': '$firstname $lastname', 'path': '$src'} } def rexpand(dikt): subs = {} names = {} # pass 1 def recurse(_, sourceDict): for key, value in sourceDict.items(): if isinstance(value, dict): recurse({}, value) elif '$' in value: subs[key] = value else: names[key] = value recurse({}, dikt) print 'subs', subs print 'names', names print 'dikt (before):', dikt for key, value in subs.items(): subs[key] = Template(value).substitute(names) # ----------------------------------------------------- # pass 2 output = {} def substitute(targetDict, sourceDict): for key, value in sourceDict.items(): if isinstance(value, dict): new_target = targetDict.setdefault(key, {}) substitute(new_target, value) else: targetDict[key] = Template(value).substitute(names) substitute(output, dikt) print 'output:', output return output rexpand(d2) From shevitz at lanl.gov Wed Jul 18 18:47:26 2007 From: shevitz at lanl.gov (Danny) Date: Wed, 18 Jul 2007 22:47:26 +0000 (UTC) Subject: problem with psqlite2 return types Message-ID: Howdy, I'm having troubles with psqlite2 and the return types from a query. The problem is that my data which is numeric, is being returned as a string. I'm aware of the detect_types=sqlite.PARSE_DECLTYPES argument to the connect function. Here's my connection code: self.connection = sqlite.connect(self.dbFile, detect_types=sqlite.PARSE_DECLTYPES)# self.connection.text_factory=str self.cursor = self.connection.cursor() Here's my sql (I'm returning risk1, which is numeric): create table risk( quantity varchar(8), color varchar(8), risk1 real, risk2 real, primary key (quantity, color) ); ( I have also tried [REAL, float, FLOAT], none work for me) Here's my query (this will probably be not much use out of context...): primaryKeys = self.primaryKeyFields[table] primaryKeyList= ' and '.join(['%s = ?'% pKey for pKey in primaryKeys]) query = 'select %s from %s where %s' % (field, table, primaryKeyList) paramList = [state[primaryKey] for primaryKey in primaryKeys] self.cursor.execute(query, paramList) Any ideas? TIA, Danny From tedpottel at gmail.com Sat Jul 7 08:35:44 2007 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Sat, 07 Jul 2007 05:35:44 -0700 Subject: How to FTP a ASCII file In-Reply-To: <1183417938.257886.238320@d30g2000prg.googlegroups.com> References: <1183417366.036607.233910@n60g2000hse.googlegroups.com> <1183417938.257886.238320@d30g2000prg.googlegroups.com> Message-ID: <1183811744.501383.17840@r34g2000hsd.googlegroups.com> On Jul 2, 7:12 pm, John Machin wrote: > On Jul 3, 9:02 am, "tedpot... at gmail.com" wrote: > > > Hi, > > > My program has the following code to transfer a binary file > > > f = open(pathanme+filename,'rb') > > print "start transfer" > > self.fthHandle.storbinary('STOR '+filename, f) > > > How can I do anASCIIfile transfer?????? > > -Ted > > I'm really curious as to how you could find out how to upload a file > in binary mode, but not inASCIImode. > > According to The Fantastic Manual: > """ > storbinary( command, file[, blocksize]) > > Store a file in binary transfer mode. command should be an appropriate > "STOR" command: "STOR filename". file is an open file object which is > read until EOF using its read() method in blocks of size blocksize to > provide the data to be stored. The blocksize argument defaults to > 8192. Changed in version 2.1: default for blocksize added. > > storlines( command, file) > > Store a file inASCIItransfer mode. command should be an appropriate > "STOR" command (see storbinary()). Lines are read until EOF from the > open file object file using its readline() method to provide the data > to be stored. > """ Hi, I did a google on python file transfer and got links to sample code using a binary transfer, but thier was no links to sample code using ascc. Thank you for your help From S.Mientki-nospam at mailbox.kun.nl Mon Jul 16 04:54:03 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 16 Jul 2007 10:54:03 +0200 Subject: running a Delphi part from Python ? In-Reply-To: <469b2b65$0$21672$426a74cc@news.free.fr> References: <889c1$469b275c$d443bb3a$2876@news.speedlinq.nl> <469b2b65$0$21672$426a74cc@news.free.fr> Message-ID: <86c61$469b30d1$d443bb3a$15805@news.speedlinq.nl> Bruno Desthuilliers wrote: > Stef Mientki a ?crit : >> >> I'm starting to get used to wxPython (coming from Delphi), >> and it seems it can do almost everything I need. >> >> Now one thing I'm missing is a good RichEditor. > > Scintilla is for you, then. IIRC, there's a wxWidget widget embedding > it, and quite a few editors using it. > AFAIK, Scintilla is a code editor. What I need looks more like ms-word, handling lists, tables, images, formulas. thanks, Stef Mientki From musiccomposition at gmail.com Tue Jul 3 09:47:01 2007 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 03 Jul 2007 06:47:01 -0700 Subject: The file executing In-Reply-To: <1183430828.997331.84340@e9g2000prf.googlegroups.com> References: <1183426846.550981.11910@m36g2000hse.googlegroups.com> <1183430828.997331.84340@e9g2000prf.googlegroups.com> Message-ID: <1183470421.012591.243300@k79g2000hse.googlegroups.com> On Jul 2, 9:47 pm, Justin Ezequiel wrote: > On Jul 3, 9:40 am, Benjamin wrote: > > > How does one get the path to the file currently executing (not the > > cwd). Thank you > > os.path.dirname(sys.argv[0]) The returns the file that was called first, but not the one currently executing... From Xin.Zheng at jpl.nasa.gov Wed Jul 11 20:41:53 2007 From: Xin.Zheng at jpl.nasa.gov (Jason Zheng) Date: Wed, 11 Jul 2007 17:41:53 -0700 Subject: os.wait() losing child? In-Reply-To: References: <4694903B.8000105@cosc.canterbury.ac.nz> Message-ID: Nick Craig-Wood wrote: > The problem you are having is you are letting Popen do half the job > and doing the other half yourself. Except that I never wanted Popen to do any thread management for me to begin with. Popen class has advertised itself as a replacement for os.popen, popen2, popen4, and etc., and IMHO it should leave the clean-up to the users, or at least leave it as an option. > Here is a way which works, done completely with Popen. Polling the > subprocesses is slightly less efficient than using os.wait() but does > work. In practice you want to do this anyway to see if your children > exceed their time limits etc. I think your polling way works; it seems there no other way around this problem other than polling or extending Popen class. thanks, Jason From ptmcg at austin.rr.com Wed Jul 11 15:39:17 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Wed, 11 Jul 2007 12:39:17 -0700 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: <1184173446.779276.250530@k79g2000hse.googlegroups.com> References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> <1184173446.779276.250530@k79g2000hse.googlegroups.com> Message-ID: <1184182757.797808.206480@d55g2000hsg.googlegroups.com> On Jul 11, 12:04 pm, David Jones wrote: > > In fact, if I put (2**2)**2**2**2 > > it comes up with the correct answer, 4294967296 > > Actually, the "correct" answer (even by your own demonstration) is > 65536. It might be easier to demonstrate if we chose a less homogeneous problem: 2**3**2. A right (rightly?) associative language (such as Python) reads this as 2**(3**2), or 2**9=512. A left-associative language (such as VB) reads this as (2**3)**2 or 8**2=64. As was pointed out earlier, left-associativity with exponentiation is of little value, since (2**3)**2 is the same as 2**(3*2) or 2**6=64. -- Paul From dformosa at usyd.edu.au Thu Jul 26 16:26:49 2007 From: dformosa at usyd.edu.au (David Formosa (aka ? the Platypus)) Date: Thu, 26 Jul 2007 20:26:49 GMT 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: ["Followup-To:" header set to comp.lang.perl.misc.] On Thu, 26 Jul 2007 09:38:34 -0700, Paul Boddie wrote: [...] > you'd show off your community a bit > better by entertaining even the most naive questions - people have to > start somewhere, you know. However asking a good question doesn't take that much skill. And if you have come to a p* language as your nth programing language then you should have had developed thouse skills. Indeed its a basic skill that anyone who regards themselves as technologically litrate should develop. I have found that often the prerequisite steps for asking a question, working out exactly what behavour I desire, the behavour I'm seeing and then isolating the code to a minimum required to express the problem, often helps me solve the problem before I even have to post. From semanticist at gmail.com Fri Jul 20 00:52:55 2007 From: semanticist at gmail.com (Miles) Date: Thu, 19 Jul 2007 21:52:55 -0700 Subject: How to check if an item exist in a nested list In-Reply-To: <1184891491.713699.291800@q75g2000hsh.googlegroups.com> References: <266557d0707191443h36eceddoca7bb626f0e0a022@mail.gmail.com> <1184891491.713699.291800@q75g2000hsh.googlegroups.com> Message-ID: <1184907175.651743.15480@r34g2000hsd.googlegroups.com> Arash Arfaee wrote: > is there any way to check if "IndexError: list index out of > range" happened or going to happen and stop program from terminating? Use a try/except block to catch the IndexError http://docs.python.org/tut/node10.html#SECTION0010300000000000000000 try: do_something_0(M_list[line][row][d]) except IndexError: do_something_1() From jstroud at mbi.ucla.edu Wed Jul 25 18:14:28 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 25 Jul 2007 15:14:28 -0700 Subject: first, second, etc line of text file In-Reply-To: References: Message-ID: Daniel Nogradi wrote: > A very simple question: I currently use a cumbersome-looking way of > getting the first, second, etc. line of a text file: > > for i, line in enumerate( open( textfile ) ): > if i == 0: > print 'First line is: ' + line > elif i == 1: > print 'Second line is: ' + line > ....... > ....... > > I thought about f = open( textfile ) and then f[0], f[1], etc but that > throws a TypeError: 'file' object is unsubscriptable. > > Is there a simpler way? This is the same logic but less cumbersome, if that's what you mean: to_get = [0, 3, 7, 11, 13] got = dict((i,s) for (i,s) in enumerate(open(textfile)) if i in to_get) print got[3] This would probably be the best way for really big files and if you know all of the lines you want ahead of time. If you need to access the file multiple times at arbitrary positions, you may need to seek(0), cache lines already read, or slurp the whole thing, which has already been suggested. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From sjmachin at lexicon.net Thu Jul 5 17:58:30 2007 From: sjmachin at lexicon.net (John Machin) Date: Thu, 05 Jul 2007 14:58:30 -0700 Subject: need help with converting c function to python function In-Reply-To: <1183656728.610086.178080@k79g2000hse.googlegroups.com> References: <1183656728.610086.178080@k79g2000hse.googlegroups.com> Message-ID: <1183672710.274200.195600@z28g2000prd.googlegroups.com> On Jul 6, 3:32 am, nephish wrote: > hello all, > > i have a c function from some modbus documentation that i need to > translate into python. > > it looks like this: > > unsigned short CRC16(puchMsg, usDataLen) > unsigned char *puchMsg ; > unsigned short usDataLen ; > { > unsigned char uchCRCHi = 0xFF ; > unsigned char uchCRCLo = 0xFF ; > unsigned uIndex ; > while (usDataLen--) > { > uIndex = uchCRCHi ^ *puchMsgg++ ; > uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; > uchCRCLo = auchCRCLo[uIndex] ; > } > return (uchCRCHi << 8 | uchCRCLo) ; > > } > > some of it i can make out, but i can't seem to figgure out > this part ' auchCRCHi[uIndex}; > it looks like a typo, because there is a closing } that does not match > the opening [. Yes, that's one problem. The other problems are: (1) you haven't noticed that auchCRClo is *NOT* the same as uchCRClo (ditto "hi"). (2) the C code is missing global declarations, something like this: unsigned char auchCRCLo[256] = { yadda yadda yadda}; /* ditto "hi" */ These two tables of 8-bit constants correspond to the single "table" of 16-bit constants in the reference that Anton gave you. Aside: the code looks like it was originally Z80 assembly language subsequently transliterated into BDS C (of blessed memory). (3) you have misread/mistranslated auchCRCLo[uIndex] blindly and unconcernedly as uchCRCLo ^ uIndex !!! (ditto "hi") > > here is what i have so far, but is not giving me the right values > > def crc16(data): > crc_hi = 0xff > crc_lo = 0xff > for x in data: > crc_index = crc_hi ^ x > crc_hi = crc_lo ^ (crc_hi | crc_index) > crc_lo = crc_lo | crc_index > return (crc_hi << 8 | crc_lo) > > whaddya think? I don't think you really want to know :-) From duncan.booth at invalid.invalid Tue Jul 24 06:16:48 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Jul 2007 10:16:48 GMT Subject: Recursive lists References: <1185268478.433070.291370@q75g2000hsh.googlegroups.com> Message-ID: mizrandir at gmail.com wrote: > Can someone tell me why python doesn't crash when I do the following: > >>>> a=[] >>>> a.append(a) >>>> print a > [[...]] >>>> print a[0][0][0][0][0][0][0] > [[...]] > > How does python handle this internally? Will it crash or use up lot's > of memory in similar but more complicated cases? > > No, it remembers internally which objects it has seen when converting them with str or repr. The C api includes functions Py_ReprEnter() and Py_ReprLeave() which the builtin objects call when they enter/leave repr. If Py_ReprEnter() returns 0 the object will return its representation, on subsequent calls Py_ReprEnter() returns 1 and the object knows it is being recursed. If you have your own recursive data structures then you may have to take your own precautions against recursion. The simplest way to do this is to make sure that the recursion always goes through a builtin object such as a list or dictionary. >>> class C: ... def __repr__(self): ... return "" % self.inner ... inner = None ... >>> c = C() >>> c.inner = c >>> c File "", line 3, in __repr__ File "", line 3, in __repr__ File "", line 3, in __repr__ ... and so on ... File "", line 3, in __repr__ File "", line 3, in __repr__ File "", line 3, in __repr__ RuntimeError: maximum recursion depth exceeded >>> c.inner = [c] >>> c ]> N.B. Don't use a tuple here as tuples don't check for recursion. That's because tuples cannot be recursive except by containing another recursive data structure such as a list, dict, or user-defined object. From bbxx789_05ss at yahoo.com Mon Jul 2 16:07:58 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 02 Jul 2007 13:07:58 -0700 Subject: subprocess -- broken pipe error In-Reply-To: <5et40bF399q8uU2@mid.individual.net> References: <1183396350.429008.185200@n2g2000hse.googlegroups.com> <1183397577.959518.264230@g4g2000hsf.googlegroups.com> <1183403782.214378.270510@m36g2000hse.googlegroups.com> <5et40bF399q8uU2@mid.individual.net> Message-ID: <1183406878.003791.81320@k79g2000hse.googlegroups.com> On Jul 2, 2:03 pm, Bjoern Schliessmann wrote: > 7stud wrote: > > Why doesn't the following program write to the file? > > [...] > > It just hangs, and then when I hit Ctrl+C and look in the file, > > the data isn't in there. > > Also, the pipe may be unbuffered by > default; file access isn't. > f.close() flushes the buffer to a file. From vodela.sai at gmail.com Thu Jul 19 00:59:24 2007 From: vodela.sai at gmail.com (Rohan) Date: Thu, 19 Jul 2007 04:59:24 -0000 Subject: CSV Issues Message-ID: <1184821164.289156.201060@z24g2000prh.googlegroups.com> Hello, I'm working on a script which collects some data and puts into a csv file which could be exported to excel. so far so good, I'm able to do what I described. When I run the script for the second time after a certain period of time the results should appear next to the results of the last run, I'm unable to make a new column when the script is run after the first time. Ideally I would like to have an output which looks like this. 1/20 1/27 we.py we.py gh.py gj.py <- Indicating tht the file has changed fg.py fg.py Please help me out. Thanks From http Tue Jul 10 03:48:51 2007 From: http (Paul Rubin) Date: 10 Jul 2007 00:48:51 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <5engo8F38jdgaU1@mid.uni-berlin.de> <4686b9b0$0$27140$426a74cc@news.free.fr> <5epe7aF39ugprU1@mid.uni-berlin.de> <7xir8us3hm.fsf@ruckus.brouhaha.com> <5fgr8rF3covr2U1@mid.uni-berlin.de> Message-ID: <7xps30bsws.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > Sure. But which class of programs are decidable? There's lot's of > research going on with model checking and the like. But AFAIK, the > consensus is that the very moment you allow recursive types, the > type-checking is either incomplete, or possibly > non-deterministic. Which makes then the compiler hang. Type checking is already undecidable in many mainstream languages including C++. Nonetheless people manage to use those languages. From bj_666 at gmx.net Wed Jul 25 17:11:25 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 25 Jul 2007 21:11:25 GMT Subject: is_iterable function. References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> <5gplj6F3gg2e0U3@mid.uni-berlin.de> Message-ID: <5gpsjsF3gg2e0U4@mid.uni-berlin.de> On Wed, 25 Jul 2007 15:46:14 -0400, Carsten Haese wrote: > On Wed, 2007-07-25 at 19:11 +0000, Marc 'BlackJack' Rintsch wrote: >> And just calling `iter()` doesn't work either: >> >> In [72]: class A: >> ....: def __getitem__(self, key): >> ....: if key == 42: >> ....: return 'answer' >> ....: raise KeyError >> ....: >> >> In [73]: iter(A()) >> Out[73]: >> >> In [74]: a = iter(A()) >> >> In [75]: a.next() >> --------------------------------------------------------------------------- >> Traceback (most recent call last) >> >> /home/bj/ in () >> >> /home/bj/ in __getitem__(self, key) >> >> : >> >> >> So there's no reliable way to test for "iterables" other than actually >> iterate over the object. > > You seem to say that your 'a' object is not iterable. I disagree. While > it's true that it raises an exception upon retrieval of the zeroth > iteration, that situation is quite different from attempting to iterate > over the number 10, where you can't even ask for a zeroth iteration. But it raises that exception on every attempt to iterate and was clearly not meant to be iterable. The docs say objects that offer no `__iter__()` but a `__getitem__()` are iterable if this `__getitem__()` can be called with consecutive integers from zero up and if there is an upper limit it must be signaled by an `IndexError`. The object above doesn't follow this protocol. For me an "iterable" is about behavior. If it doesn't quack like a duck? > To illustrate this point further, imagine you write an object that > iterates over the lines of text read from a socket. If the connection is > faulty and closes the socket before you read the first line, the zeroth > iteration raises an exception. Does that mean the object is iterable or > not depending on the reliability of the socket connection? I find that > notion hard to swallow. It is an iterable as there is at least the chance or the intent of the programmer that it will behave like an iterable. The duck tries hard to quack but may be hoarse. :-) Ciao, Marc 'BlackJack' Rintsch From ervinramonllari at gmail.com Thu Jul 19 16:29:23 2007 From: ervinramonllari at gmail.com (ervin ramonllari) Date: Thu, 19 Jul 2007 22:29:23 +0200 Subject: Data type conversion Message-ID: <9f2909fa0707191329g22bdae44oe7e8215947afe973@mail.gmail.com> Hello everybody, I'm trying to read some tables from a MS Access database and dump them into a Postgres database. When I read the attributes data types, I get some numeric values, i.e. if the data type of an attribute is TEXT, I get a value 202. I don't know how to convert this number into a valid data type in Postgres. If someone can help me with this problem, I would really appreciate that. Thank you in advance, Regards, Ervin. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Mon Jul 9 01:25:31 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 09 Jul 2007 15:25:31 +1000 Subject: ANN: gozerbot 0.7 released References: <1183935992.848431.131890@r34g2000hsd.googlegroups.com> Message-ID: <87lkdqm9mc.fsf@benfinney.id.au> bthate writes: > it time for a new gozerbot release ! we made a 0.7 release of > gozerbot. When announcing a new release, please include a brief "What is gozerbot?" explanation section so that readers can know whether the announcement is of interest. -- \ "Pinky, are you pondering what I'm pondering?" "Well, I think | `\ so, Brain, but first you'd have to take that whole bridge | _o__) apart, wouldn't you?" -- _Pinky and The Brain_ | Ben Finney From steve at REMOVE.THIS.cybersource.com.au Thu Jul 5 13:06:39 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 06 Jul 2007 03:06:39 +1000 Subject: Proposal: s1.intersects(s2) References: <5f1pldF3a62csU5@mid.uni-berlin.de> <1183600138.759015.246040@c77g2000hse.googlegroups.com> Message-ID: On Thu, 05 Jul 2007 01:48:58 +0000, richyjsm wrote: > On Jul 4, 8:14 pm, Steven D'Aprano > wrote: >> However, there's a very subtle flaw in the idea. While "the intersection" >> of two sets is well-defined, "these two sets intersect" is (surprisingly!) >> _not_ well-defined. > > Poppycock! It's perfectly well defined: two sets intersect if and > only if their intersection is nonempty. That's certainly _a_ definition. I'm not a professional set theorist, but in 15-odd years of studying and teaching maths I've never come across mathematicians using intersect as a verb except as informal short-hand. I often say "North Street and South Street don't intersect", but "the intersection of sets A and B is empty". Just because I've never come across it doesn't mean it exists, so I'd be grateful for any reference to a technical definition, or even references to any mathematician using intersect as a verb in a vigorous, non-hand-waving way. Here's a link to get you started: http://www.google.com.au/search?q=define%3Aintersect > There's absolutely no reason > to single out the empty set for special treatment in this definition. But you can't avoid treating the empty set as special, because it _is_ special. You can only choose where to do so. For instance, do sets intersect with themselves? By my rule, every set intersects with itself, no exceptions. By your rule, every set intersects with itself, except for the empty set. >> The problem comes if we (perhaps naively) try to say that if a set A is a >> subset of set B, set A must intersect with B. > > Well of course false statements are going to cause problems. My statement is only false if we treat the empty set as special, which you've said we shouldn't do. By my rule: if A <= B, then A and B intersect, no exceptions. By your rule: if A <= B and A is not the empty set, then A and B intersect. >> (Not all intersecting sets are subsets, but all subsets are >> intersecting sets.) > > Not true. Can you give a counter-example, without treating the empty set as special? Of course if you exclude the empty set by definition, my statement is no longer true -- but that's begging the question of whether we should exclude the empty set or not. >> As a result, any proposed function or method that returns a True/False >> value for whether set A intersects with set B needs to define (and >> justify) what it means to say that two sets intersect when one or both >> are the empty set. > > Nope. There's one, obvious, correct definition, as given above. No > need to mention the empty set at all. It is obvious, but whether it is correct or not depends on how you decide whether two things intersect or not. -- Steven. From Roka100 at gmail.com Mon Jul 30 02:34:14 2007 From: Roka100 at gmail.com (Jia Lu) Date: Sun, 29 Jul 2007 23:34:14 -0700 Subject: How to write GUI and event separately in wxPython?? Message-ID: <1185777254.925902.204500@z28g2000prd.googlegroups.com> HI all I am making an application with wxpython. But I got a problem when I want to change the display string according to process status. I passed the frame to the processing function and use the frame.txtobj to change displaying strings. I found it is a bad method to do that. Can any one tell me how to do that usually? ( How to separate GUI and Control code? ) Thank you. From horpner at yahoo.com Thu Jul 26 18:10:55 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 26 Jul 2007 22:10:55 GMT Subject: is_iterable function. References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> <5uNpi.36822$G23.3430@newsreading01.news.tds.net> <5gs35iF3gbvuoU1@mid.uni-berlin.de> <1185484818.900893.213420@l70g2000hse.googlegroups.com> Message-ID: On 2007-07-26, George Sakkis wrote: > That's not the only problem; try a string element to see it > break too. More importantly, do you *always* want to handle > strings as iterables ? > > The best general way to do what you're trying to is pass > is_iterable() as an optional argument with a sensible default, > but allow the user to pass a different one that is more > appropriate for the task at hand: > > def is_iterable(obj): > try: iter(obj) > except: return False > else: return True > def flatten(obj, is_iterable=is_iterable): That makes good sense. Plus the subtly different way you composed is_iterable is clearer than what I originally wrote. I haven't ever used a try with an else. > if is_iterable(obj): > for item in obj: > for flattened in flatten(item, is_iterable): > yield flattened > else: > yield obj > > By the way, it's bad design to couple two distinct tasks: > flattening a (possibly nested) iterable and applying a function > to its elements. Once you have a flatten() function, > deeply_mapped is reduced down to itertools.imap. I chose to implement deeply_mapped because it illustrated the problem of trying to catch a TypeError exception when one might be thrown by some other code. I agree with your opinion that it's a design flaw, and most of my problems with the code were caused by that flaw. -- Neil Cerutti From kinch1967 at gmail.com Wed Jul 4 08:24:17 2007 From: kinch1967 at gmail.com (bullockbefriending bard) Date: Wed, 04 Jul 2007 05:24:17 -0700 Subject: Generator for k-permutations without repetition In-Reply-To: <468b8df8$0$90275$14726298@news.sunsite.dk> References: <1183548133.495759.191390@d30g2000prg.googlegroups.com> <468b8df8$0$90275$14726298@news.sunsite.dk> Message-ID: <1183551857.077116.149310@e16g2000pri.googlegroups.com> On Jul 4, 7:09 pm, Nis J?rgensen wrote: > bullockbefriending bard skrev: > > > > > I was able to google a recipe for a k_permutations generator, such > > that i can write: > > > x = range(1, 4) # (say) > > [combi for combi in k_permutations(x, 3)] => > > > [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, > > 3, 1], [1, 3, 2], [1, 3, 3], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2, > > 1], [2, 2, 2], [2, 2, 3], [2, 3, 1], [2, 3, 2], [2, 3, 3], [3, 1, 1], > > [3, 1, 2], [3, 1, 3], [3, 2, 1], [3, 2, 2], [3, 2, 3], [3, 3, 1], [3, > > 3, 2], [3, 3, 3]] > > > but what i really want is the above without repetition, i.e.: > > > [combi for combi in k_permutations_without_repetitions(x, 3)] => > > > [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] > > > For smallish lists, it's no problem to generate the list as follows: > > > no_reps_combis = [combi for combi in k_permutations(x, 3) if \ > > > len(set(combi)) == 3] > > > but i'm sure there must be a way to do this as a pure generator, just > > that i wouldn't have a clue how to go about it. > > > Help please, Python Gods! :) > > I was initially confused by your example, since the size of the > underlying set is the same as of the individual permutations. In this > case, you are just asking for all permutations of the set. > > As far as I can tell from a quick googling, the relevant definition of > k-permutation is "an ordered list of k elements from the set". Thus your > first example does not really generate k_permutations. > > A quick solution, not extensively tested > > # base needs to be an of the python builtin set > > def k_perm(base,k): > for e in base: > if k == 1: > yield [e] > else: > for perm in k_perm(base-set([e]),k-1): > yield [e] + perm > > >>> list(k_perm(set([1,2,3,4]),3)) > > [[1, 2, 3], [1, 2, 4], [1, 3, 2], [1, 3, 4], [1, 4, 2], [1, 4, 3], [2, > 1, 3], [2, 1, 4], [2, 3, 1], [2, 3, 4], [2, 4, 1], [2, 4, 3], [3, 1, 2], > [3, 1, 4], [3, 2, 1], [3, 2, 4], [3, 4, 1], [3, 4, 2], [4, 1, 2], [4, 1, > 3], [4, 2, 1], [4, 2, 3], [4, 3, 1], [4, 3, 2]] > > Much to my initial surprise, it "works" for k<1 as well: > > >>> list(k_perm(set([1,2,3,4]),-1)) > > [] > > Hope this helps > > Nis thank you!. i'll give this a try. seems to do exactly what i need. sorry about the ambiguity in my example. i chose 3 from 3 merely to keep the size of the example case small, without thinking enough about how it might cause confusion. From stargaming at gmail.com Sun Jul 8 15:02:46 2007 From: stargaming at gmail.com (Stargaming) Date: Sun, 08 Jul 2007 21:02:46 +0200 Subject: accessing an object instance by only having one of its attribute values In-Reply-To: <1183918727.033724.213010@22g2000hsm.googlegroups.com> References: <1183918727.033724.213010@22g2000hsm.googlegroups.com> Message-ID: <469134d9$0$31983$9b622d9e@news.freenet.de> feli.hp at gmail.com wrote: > Hello all, > > Imaybe someone can help me with this question. > Is there a direct way of accessing an object instance, if all I know > is the value of one of its attributes? > The object is part of a list of objects, and I would like to pick the > object directly by using this attribute value, instead of going > through the list and checking if each objects attribute value is the > one I am looking for. > > Thank you in advance > Okay, imagine you got a bunch of small packets (presents or something similiar). You want to get rid of the lightest one. You cannot see weights, so, what you're doing is basically measuring the weight of *every single packet*, compare and pick. No way around. There might be some ways not having to touch *each* object, if you precompute some results. So, in the example above, you could divide the packets into two categories, "more than 50 lbs" and "less than 50 lbs", for example. I think binary trees might be interesting here but touching every object would be way easier. HTH, Stargaming From martin at v.loewis.de Tue Jul 31 16:58:34 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 31 Jul 2007 22:58:34 +0200 Subject: Python Package Index hostname change Message-ID: <46AFA27A.4090700@v.loewis.de> The Python Packaging Index (the software formerly known as Cheeseshop) is now available at http://pypi.python.org/pypi The old addresses (www.python.org/pypi, and cheeseshop.python.org/pypi) will continue to work, either as aliases or using HTTP redirections. The software was renamed to its old name (PyPI - Python Package Index), as the Cheeseshop name was ever confusing people unfamiliar with British television comedy sketch (and puzzling even to people familiar with the sketch, as you *can* get packages from the package index). If you would like to discuss PyPI and its future, please join catalog-sig at python.org. Regards, Martin From no at no.no Sat Jul 7 15:36:36 2007 From: no at no.no (Daniel) Date: Sat, 07 Jul 2007 22:36:36 +0300 Subject: Pretty Printing Like Tidy for HTML References: <1183833340.610662.197060@o11g2000prd.googlegroups.com> Message-ID: On Sat, 07 Jul 2007 21:35:40 +0300, David wrote: > > All, > > Is there a pretty printing utility for Python, something like Tidy for > HTML? > > That will change: > > xp=self.uleft[0]+percentx*(self.xwidth) > > To: > > xp = self.uleft[0] + percentx * (self.xwidth) > > And other formatting issues. > Why not just write python as it should be written? -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From iainking at gmail.com Thu Jul 19 06:37:56 2007 From: iainking at gmail.com (Iain King) Date: Thu, 19 Jul 2007 10:37:56 -0000 Subject: wxPython and threads In-Reply-To: <1184726489.112138.96350@z28g2000prd.googlegroups.com> References: <1184726489.112138.96350@z28g2000prd.googlegroups.com> Message-ID: <1184841476.319799.278240@m3g2000hsh.googlegroups.com> On Jul 18, 3:41 am, Benjamin wrote: > I'm writing a search engine in Python with wxPython as the GUI. I have > the actual searching preformed on a different thread from Gui thread. > It sends it's results through a Queue to the results ListCtrl which > adds a new item. This works fine or small searches, but when the > results number in the hundreds, the GUI is frozen for the duration of > the search. I suspect that so many search results are coming in that > the GUI thread is too busy updating lists to respond to events. I've > tried buffer the results so there's 20 results before they're sent to > the GUI thread and buffer them so the results are sent every .1 > seconds. Nothing helps. Any advice would be great. I do something similar - populating a bunch of comboboxes from data takes a long time so I run the generator for the comboboxes in another thread (and let the user use some textboxes in the mean time). A rough edit toward what you might be doing: import thread class Processor(object): def __init__(self): self.lock = thread.allocate_lock() self.alive = False self.keepalive = False def start(self): if not self.alive: self.alive = True self.keepalive = True thread.start_new_thread(self.Process, (None,)) def stop(self): self.keepalive = False def process(self, dummy=None): self.alive = False class SearchProcessor(Processor): def __init__(self, entries, lookfor, report): Processor.__init__(self) self.entries = entries self.lookfor = lookfor self.report = report def process(self, dummy=None): for entry in self.entries: if lookfor in entry: self.report(entry) if not self.keepalive: break self.report(None) self.alive = False results = [] def storeResult(result): if result != None: results.append(result) else: notifySomeMethod(results) sp = SearchProcessor(someListOfData, someTextToSearchFor, storeResult) sp.start() when the search is done it will call notifySomeMethod with the results. Meanwhile you could, for example, bind sp.stop() to a cancel button to stop the thread, or add a counter to the storeResult function and set a status bar to the total found, or whatever else you want to do. Iain From duprez at hinet.net.au Mon Jul 16 02:13:49 2007 From: duprez at hinet.net.au (Mick Duprez) Date: Sun, 15 Jul 2007 23:13:49 -0700 Subject: embedded python in dll with C Message-ID: <1184566429.419408.177690@z28g2000prd.googlegroups.com> Hi All, I can't quite get my head around embedding Python in a C app and I have a few questions if I may, here is the background. I want to create a dll plugin that has the Python interpreter embedded in it for use in scripting an established application. So far I have created the interface dll and py module using swig. So far so good, now some questions - 1) Would it be best to combine my swig generated .c file into the same dll as my plugin dll or leave it seperate, in other words should I just embed the interpreter into the C 'plugin' dll and create the interface module and dll seperately to import into python scripts? 2) Once I have done this would it be appropriate just to use something like this in my C code - PyRun_SimpleString("import my_plugin_script"); PyRun_SimpleString("init_func_from_script()"); where 'init_func_from_script' establishes callbacks for C to use from the script using the new interface module/dll? The C application has it's own functions for registering callbacks by passing in a list of the functions, I'm hoping this will work. I'll give it a go in the mean time, just looking for the right/better way to do this, thanks. From benruza at gmail.com Tue Jul 3 05:54:55 2007 From: benruza at gmail.com (Bruza) Date: Tue, 03 Jul 2007 09:54:55 -0000 Subject: Bug in Python class static variable? In-Reply-To: References: <1183372758.251109.34550@z28g2000prd.googlegroups.com> <1183406012.465981.35700@z28g2000prd.googlegroups.com> Message-ID: <1183456495.183892.293350@e9g2000prf.googlegroups.com> On Jul 2, 1:21 pm, Duncan Booth wrote: > Bruza wrote: > > On Jul 2, 3:52 am, Duncan Booth wrote: > >> Bruza wrote: > >> > I am trying to define a class static variable. But the value of the > >> > static variable seems to be only defined inside the file that the > >> > class is declared. See the code below. When I run "python w.py", I > >> > got: > > >> When you run "python w.py" the *script* w.py is loaded as the module > >> __main__. Importing a module called 'w' creates a new module which is > >> unrelated to __main__. If you want access to variables defined in the > >> main script then you need to import __main__. > > >> Don't use 'from module import *': > > >> The import statements are executed when the interpreter reaches them > >> in the source. Even if you fix your code to import from __main__, the > >> values you try to import from __main__ won't exist when the import > >> statement executes: the first 'from a import *' will load and execute > >> all of module 'a', but when that executes 'from __main__ import *' it > >> just imports names defined in the main script *before* a was > >> imported. > > >> In general, don't try to do this: put all your classes into modules > >> and just put minimal startup code into a script. > > > Duncan, > > > Thanks for replying. However, I am still confused... > > Even if I put "from __main__ import *" in both "a.py" and "w.py", I > > still got > > the same results. So, how should I re-structure my program to make the > > class > > static variable works??? > > Option 1: > In w.py put: > > import a > > and then refer to a.ClassA > > In a.py put: > > import __main__ > > and then refer to __main__.ClassW > > But better, option 2: > > Create a new file script.py which contains: > > import w > if __name__=='__main__': > w.startup() > > then in a use 'import w' and in w use 'import a' and refer to a.ClassA and > w.ClassW as above. > > Try to think through the order in which Python interprets your code: > remember everything is interpreted. Both 'import' statements and 'class' > statements are really just variation on an assignment, so none of the names > exist until the lines which declare them have been executed. A line 'import > a' is roughly the same as: > > a = __import__(something) > > and a statement such as 'class ClassA: whatever' is roughly the same as: > > ClassA = type('ClassA', baseclasses, dict) > > You should never attempt to use the 'from X import *' form of import when > you have modules which include each other (you might get away with it if > you move the imports to the end of the module instead of the beginning, but > it is much simpler just to import the modules, and good practice in any > case). Duncan, Thanks for the reply; both approaches worked!! Looks like the problem is because of "ClassW" is defined in the default "__main__" module, not the "w" module as I thought. I also figured out a 3rd approach adding the following code in "w.py". The idea is that I force the program to import "w.py" as "w" if "w.py" is loaded into "__main__". Then I can run the qualified "w.startup()". And it also works :-)... if __name__ == '__main__': import w w.startup() From larry.bates at websafe.com Wed Jul 18 11:22:14 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 18 Jul 2007 10:22:14 -0500 Subject: shutil.copyfile problem for GIS data In-Reply-To: References: Message-ID: Ahmed, Shakir wrote: > Need help to copy a personal geodatabase from one location to another: > > > Trying to copy a personal geodatabase from one location to another > location where all the users are retrieving data from the second > location: > > 1. I can copy over the updated personal geodatabase to the working > location and overwrite it, though the file is opened by ArcGIS users > (Local Installation of Arc GIS on the users computers). > > > 2. But problem is that I can't copy over if the same updated > personal geodatabase to the working location, if users uses that same > geodatabase through CITRIX - ArcGIS ( user does not have permission to > edit the data) > > 3. the python script which I am using as follows: > > import shutil > import os > > src = "c:\mydata\test\mygeo.mdb" > dst = "v:\updated\data\mygeo.mdb" > > shutil.copyfile(src,dst) > > I highly appreciate if any one of you can help me and give me a > direction that I can solve this problem. > > Thanks in advance. > > Shak While I'm uncertain about the exact nature of your problem I can tell you that the src string you have defined won't work becaust \t is a tab character. To make shutil.copyfile work you need to do: src = r"c:\mydata\test\mygeo.mdb" dst = r"v:\updated\data\mygeo.mdb" or src = "c:\\mydata\\test\\mygeo.mdb" dst = "v:\\updated\\data\\mygeo.mdb" -Larry From deets at nospam.web.de Fri Jul 13 05:44:05 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 13 Jul 2007 11:44:05 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <468565a0$0$3686$426a74cc@news.free.fr> <7xvecumrte.fsf@ruckus.brouhaha.com> <1i13w96.kyyobph71qxrN%aleax@mac.com> <7xwsx63we6.fsf@ruckus.brouhaha.com> <878x9llv5x.fsf@benfinney.id.au> Message-ID: <5fovr8F3eglkfU1@mid.uni-berlin.de> John Nagle schrieb: > Chris Mellon wrote: >> You can't prove a program to be correct, in the sense that it's proven >> to do what it's supposed to do and only what it's supposed to do. > > Actually, you can prove quite a bit about programs with the right > tools. > For example, proving that a program cannot subscript out of range is > quite feasible. (Although not for C, where it's most needed; that language > is just too ill-defined.) You can - when there is input involved? > You can prove that certain assertions about > an object always hold when control is outside the object. You can > prove that certain entry conditions for a function are satisfied by > all its callers. > > Take a look at what the "Spec#" group at Microsoft is doing. > There's also some interesting USAF work on avionics at > > http://www.stsc.hill.af.mil/crossTalk/2006/09/0609SwardGerkenCasey.html """ For example, SPARK does not support dynamic allocation of memory so things such as pointers and heap variables are not supported. """ Pardon me, but if that's the restrictions one has to impose to his programs to make them verifiable, I'm not convinced that this is a way to go for python - or any other language - that needs programs beyond the most trivial tasks. Which is not to say that trivial code couldn't have errors, and if it's extremely cruical code, it's important that it hasn't errors. But all I can see is that you can create trustable, simple sub-systems in such a language. And by building upon them, you can ensure that at least these won't fail. But to stick with the example: if the path-planning of the UAV that involves tracking a not before-known number of enemy aircrafts steers the UAV into the ground, no proven-not-to-fail radius calculation will help you. Diez From zentraders at gmail.com Sat Jul 28 15:50:46 2007 From: zentraders at gmail.com (Zentrader) Date: Sat, 28 Jul 2007 12:50:46 -0700 Subject: Tkinter -- Show Data in an Excel like Read-Only Grid In-Reply-To: <1185630010.805799.122480@i38g2000prf.googlegroups.com> References: <1185573410.087935.146830@d30g2000prg.googlegroups.com> <1185630010.805799.122480@i38g2000prf.googlegroups.com> Message-ID: <1185652246.571751.309590@i38g2000prf.googlegroups.com> If you want to only display data in a table format, try MultiListBox.py. Just download and run for a demo. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52266 From XX.XmcX at XX.XmclaveauX.com Wed Jul 4 01:20:10 2007 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Wed, 04 Jul 2007 07:20:10 +0200 Subject: ActivePython References: <5f0g54F396io7U1@mid.individual.net> Message-ID: Hi! > Why might one choose to use ActivePython instead of using the free CPython? quiet installation? -- @-salutations Michel Claveau From JHoover at fbi.gov Sun Jul 22 20:35:03 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Sun, 22 Jul 2007 20:35:03 -0400 Subject: Where is the collections module? In-Reply-To: References: Message-ID: Gordon Airporte wrote: > I was going to try tweaking defaultdict, but I can't for the life of me > find where the collections module or its structures are defined. Python > 2.5. Thanks all. I was expecting it in Python. Time to dust off my C :-P From steve at REMOVE.THIS.cybersource.com.au Thu Jul 5 12:51:09 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 06 Jul 2007 02:51:09 +1000 Subject: Proposal: s1.intersects(s2) References: Message-ID: On Thu, 05 Jul 2007 07:34:28 -0700, Aahz wrote: > In article , > Steven D'Aprano wrote: >> >>My main feeling is that any such function should be a set method rather >>than a built-in function like len(). The name change was comparatively >>unimportant. > > Look up at the Subject: line. Subject line? What's that? *chagrined wink* > There never was any suggestion that > intersects() be anything other than a set method. My fault for replying to a reply instead of the original post. -- Steven. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jul 13 14:13:20 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 13 Jul 2007 20:13:20 +0200 Subject: NoneType object not iterable References: Message-ID: <5fptm0F3d0jiiU1@mid.individual.net> Daniel wrote: > db is out of scope, you have to pass it to the function: What's wrong about module attributes? Regards, Bj?rn -- BOFH excuse #418: Sysadmins busy fighting SPAM. From jeff at jmcneil.net Thu Jul 19 22:31:49 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Thu, 19 Jul 2007 22:31:49 -0400 Subject: subprocess (spawned by os.system) inherits open TCP/UDP/IP port In-Reply-To: References: Message-ID: <82d28c40707191931s7cf94b10td0d615badb66757a@mail.gmail.com> What's unexpected about it? Child processes inherit all of the open file descriptors of their parent. A socket is simply another open file descriptor. When your parent process exits, your child still holds a valid, open file descriptor. import sys import socket import os import time s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0) s.bind(('', 8888)) pid = os.fork() if pid > 0: time.sleep(100) elif pid == 0: time.sleep(100) $ lsof | grep python | grep jeff | grep 8888 python 13048 jeff 3u IPv4 212689 UDP *:8888 python 13049 jeff 3u IPv4 212689 UDP *:8888 -Jeff On 7/19/07, alf wrote: > > > Hi, > > I need a help with explaining following behavior. Although it is not > python issue per say, python helped me to write sample programs and > originally I encountered the issue using python software. So let's > assume we have two following programs: > > > > [myhost] ~> cat ss.py > import socket > UDPSock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) > UDPSock.bind(("",12345)) > import os > os.system('python cc.py') > > [myhost] ~> cat cc.py > import time > time.sleep(2036) > > > > then I start master one, do ctrl-Z and bg. > > [myhost] ~> python ss.py > > Suspended > [myhost] ~> bg > [1] python ss.py & > [myhost] ~> ps > UID PID PPID C STIME TTY TIME CMD > myuser00 3192 3189 0 14:57 pts/0 00:00:00 -tcsh > myuser00 3247 3192 0 14:57 pts/0 00:00:00 python ss.py > myuser00 3248 3247 0 14:57 pts/0 00:00:00 python cc.py > > > > [myhost] ~> netstat -uanp |grep 12345 > (Not all processes could be identified, non-owned process info > will not be shown, you would have to be root to see it all.) > udp 0 0 0.0.0.0:12345 0.0.0.0:* > 3247/python > > > > As expected netstat indicates process 3247 having port allocated. Then I > kill the master process and interestingly the child inherits the port > open. > > > [myhost] ~> kill 3247 > [myhost] ~> netstat -uanp | grep 12345 > (Not all processes could be identified, non-owned process info > will not be shown, you would have to be root to see it all.) > udp 0 0 0.0.0.0:12345 0.0.0.0:* > 3248/python > [1] + Terminated python ss.py > > > > Why it is happening? I know that os.system uses fork, but still this is > something unexpected. > > > Thx, Alf > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Thu Jul 26 02:31:36 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 26 Jul 2007 08:31:36 +0200 Subject: Pickled objects over the network References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com><011401c7caa0$3e3e5900$03000080@hendrik> <012901c7cb60$5ba530c0$03000080@hendrik> <00c601c7cc38$d826ba00$03000080@hendrik> <00bd01c7ccf6$8fa62540$03000080@hendrik> Message-ID: <005d01c7cf4e$9e54ba20$03000080@hendrik> "Marco Mariani" wrote: > Hendrik van Rooyen ha scritto: > > > But more seriously - is there any need for a simple serialiser that will > > be able to be used to transfer a subset of the built in types over an > > open network in a safe manner, for the transfer of things like lists of > > parameters? > > Yes, there seems to be a need for XML/YAML/JSON :-) Looks like it - else there would not be so many of them. Are they all safe and secure? - Hendrik From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 20 05:40:01 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 20 Jul 2007 11:40:01 +0200 Subject: class C: vs class C(object): In-Reply-To: References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> <469f1557$0$26759$426a74cc@news.free.fr> Message-ID: <46a082ed$0$431$426a74cc@news.free.fr> Aahz a ?crit : > In article <469f1557$0$26759$426a74cc at news.free.fr>, > Bruno Desthuilliers wrote: >> To make a long story short: Python 2.2 introduced a new object model >> which is more coherent and more powerful than the original one. The old >> one was kept so far for compatibility reasons, but there's absolutely no >> reason to use it no more since "new-style" classes can do anything >> "Classic" classes did and much more. IOW, don't even bother with >> old-style classes. > > And I'll make my usual knee-jerk response disagreeing with this. For > more info, search groups.google.com. And you'll still make it harder for newcomers to understand why a lot of things don't work correctly with their classes. How helpful... Aahz, the object model switch happened *years* ago, and it's quite clear that old style classes have been kept so far for compatibility reasons only. It's obvious that one doesn't gain *anything* - except compat with years-old pre-2.2 versions of Python - using old-style classes. So *why* on earth are you still *advocating* the use of old style classes ?????? From carsten at uniqsys.com Tue Jul 31 15:35:27 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 31 Jul 2007 15:35:27 -0400 Subject: With Statement Contexts and Context Managers In-Reply-To: <4a7f84ac0707311157s5cdd770fw96acaed00785bc73@mail.gmail.com> References: <4a7f84ac0707311157s5cdd770fw96acaed00785bc73@mail.gmail.com> Message-ID: <1185910527.3370.29.camel@dot.uniqsys.com> On Tue, 2007-07-31 at 14:57 -0400, G wrote: > Hi, > > Could somebody please point me to a good resource to read about > the contexts, context managers, and with_statement > There's PEP 343 at http://www.python.org/dev/peps/pep-0343/. I don't know if that fits your definition of "good," but it should at least get you started. HTH, -- Carsten Haese http://informixdb.sourceforge.net From carl.dhalluin at gmail.com Wed Jul 25 05:30:49 2007 From: carl.dhalluin at gmail.com (carl.dhalluin at gmail.com) Date: Wed, 25 Jul 2007 09:30:49 -0000 Subject: Interactive remote debugging by redirecting sys.stdin and sys.stdout to a socket or pipe Message-ID: <1185355849.205492.211290@w3g2000hsg.googlegroups.com> Hi I want a simple way to interactively remote debug a running python script which has no tty terminal attached to it. The scripts are running standalone (i.e. they are automatically started and have no terminal) and very infrequently come into error conditions which i want to understand and debug. The idea is that I do the debugging as shown below. Is that a good way of solving my problem? Do I need anything special for terminal emulation? What type of client should I use? I want things like tab completion and syntax coloring of ipshell (or similar) to work. if : # If I come here I did something wrong. Send an event or email that the failure has happened startRemoteDebugging() def startRemoteDebugging(): # open a TCP listen socket and start listening # as soon as someone connects to the socket, do authentication check (e.g. username/pwd) # redirect sys.stdin and sys.stdout to the socket # start interactive python e.g. ipython ipshellembed() # put sys.stdin and sys.stdout back to what they were # debugging session is done From bignose+hates-spam at benfinney.id.au Fri Jul 13 21:58:41 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 14 Jul 2007 11:58:41 +1000 Subject: MaildirMessage References: <1184287592.509355.310110@g4g2000hsf.googlegroups.com> <874pk8kedo.fsf@benfinney.id.au> Message-ID: <87vecniw4u.fsf@benfinney.id.au> Steve Holden writes: > Ben Finney wrote: > > Which is a bug in the 'email.message' module, in my view. If it's > > attempting to support a mapping protocol, it should allow > > iteration the same way standard Python mappings do: by iterating > > over the keys. > > Stop assuming that everyone sees requirements the same as you - the > author of the email module has long years of experience, and has > provided an excellent and overall usable piece of software. I don't see that this fact (which I agree is the case) in any way makes the code immune from bugs, nor from the discussion of the possibility. > Criticisms such as yours are easy (we can all experess our opinions, > to which we are all entitled), but mere expression of an opinion > isn't going to change anything. It can, though, lead to a discussion about whether it *is* a bug or not. Care to contribute something other than the lashing you put into your message? -- \ "Dyslexia means never having to say that you're ysror." -- | `\ Anonymous | _o__) | Ben Finney From info at wingware.com Tue Jul 31 15:34:47 2007 From: info at wingware.com (Wingware) Date: Tue, 31 Jul 2007 15:34:47 -0400 Subject: Wing IDE for Python v. 3.0 beta1 released Message-ID: <46AF8ED7.2070206@wingware.com> Hi, I'm happy to announce the first beta release of Wing IDE 3.0. It is available from http://wingware.com/wingide/beta Wing IDE is a commercial IDE designed specifically for Python programmers. More information about the product and free trials are available at http://wingware.com/ 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 (*)'d items are available in Wing IDE Professional only. The CHANGELOG.txt file in the installation provides additional details. 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). 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 normal price to upgrade. Thanks! The Wingware Team Wingware | Python IDE Advancing Software Development www.wingware.com From Envelope.Salad at gmail.com Mon Jul 9 11:19:42 2007 From: Envelope.Salad at gmail.com (Pomato) Date: Mon, 09 Jul 2007 15:19:42 -0000 Subject: compressing consecutive spaces In-Reply-To: <1183991894.508562.16430@g4g2000hsf.googlegroups.com> References: <1183991894.508562.16430@g4g2000hsf.googlegroups.com> Message-ID: <1183994382.300137.52450@57g2000hsv.googlegroups.com> On Jul 9, 7:38 am, Beliavsky wrote: > How can I replace multiple consecutive spaces in a file with a single > character (usually a space, but maybe a comma if converting to a CSV > file)? Ideally, the Python program would not compress consecutive > spaces inside single or double quotes. An inelegant method is to > repeatedly replace two consecutive spaces with one. You can use re.sub(): re.sub(pattern, substitution, string) import re re.sub(r'\ +', ' ', 'foo bar') From walterbyrd at iname.com Wed Jul 25 16:55:04 2007 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 25 Jul 2007 13:55:04 -0700 Subject: Why PHP is so much more popular for web-development In-Reply-To: References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> Message-ID: <1185396904.642985.141300@z24g2000prh.googlegroups.com> On Jul 25, 2:12 pm, Carsten Haese wrote: > Also, CherryPy's requirements are very > minimal. In terms of memory and CPU, maybe. But I think that *requires* apache 2.x and a very recent version of mod_python. By web-hosting standards, those are very steep requirements. From twisted0n3 at gmail.com Sat Jul 7 21:00:42 2007 From: twisted0n3 at gmail.com (Twisted) Date: Sun, 08 Jul 2007 01:00:42 -0000 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1183841277.333384.188950@g4g2000hsf.googlegroups.com> Message-ID: <1183856442.027967.272530@g4g2000hsf.googlegroups.com> On Jul 7, 6:12 pm, Lew wrote: > Twisted wrote: > Edward Dodge wrote: > >> So -- what magical computer app illuminates the entire room and shows > >> you how to use everything at the flip of a switch? This brilliant > >> discovery would put Sam's, O'Reilly, the for-Dummies series, and > >> virtually every other computer book publisher out of business in weeks. > >> Naturally, this would include the publishers of books on "easy-to-use" > >> Microsoft products. > > > I don't know, but it sure as hell isn't emacs. > > The reason you don't know, and Edward Dodge's point, is that there is no such > app, whether emacs or not. Translation: since perfection is unattainable, we shouldn't even try, and just foist upon our poor users whatever awkward and hard-to-learn interface pops into our heads first? From gagsl-py2 at yahoo.com.ar Sun Jul 15 15:33:27 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 15 Jul 2007 16:33:27 -0300 Subject: Dict Help References: Message-ID: En Sun, 15 Jul 2007 11:39:24 -0300, Robert Rawlins escribi?: > I'm looking for some help expanding on a dictionary I've got and storing > multiple values per key and the best way to do it. I'm guessing that I > need to store a list inside the value of the dictionary, but I'm not > quite sure how that can be achieved, and also how to check for values in > that list. > Here is a brief example of what I want to be able to build: > Key Value > 00:0F:DE:A8:AB:6F > 6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg,01DBB592-F7EB-B000-7F250FD8A2CE158F.gif,533EAE0F-B211-B2D8-4C2DB662CCECFBD7.3gp > 00:17:B0:A0:E7:09 > 6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg,01DBB592-F7EB-B000-7F250FD8A2CE158F.gif > 00:1B:98:16:21:E4 > 6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg There are a few ways to do it. Just translating your own words into Python, use a dictionary with a list of values. > Now I really need to have two functions, one of which appends a value to > the list for a specified key, so I have the key and the new value as > strings, I then want to locate that key and append the list with the new > value. The simplest way: d = {} # add a pair key, value if key not in d: d[key] = [value] else: d[key].append(value) > The second function I need, is to check for the existence of a value in > the list of a particular key, again I have the key and the value and I > want to do something like: > if value in list of values for key: > do something here... # check for a key, value exists = key in d and value in d[key] > The final function that would be helpful to me would to be able to > remove a value from the list for a specific key. # remove value from key's values if key in d and value in d[key]: d[key].remove(value) > I'm not sure if a list as the value in a dict is possible, or if its the > best way to achieve this, It just made logic sense to me so thought I'd > come and get your thoughts on this. If anyone has any better suggestions It's perfectly possible as you can see. Now, depending on how many values you have, or how often do you test, you might replace the list with a set. Sets are unordered collections (you will loose the insertion order) but are better suited for a "contains" test (O(1) instead of O(n) for a list) And you might replace the dictionary with a defaultdict. The insertion would become: from collections import defaultdict d = defaultdict(set) # add a pair key, value d[key].add(value) The existence check and remove method do not change. Dicts, lists and sets are documented here: and defaultdict -- Gabriel Genellina From bravo.loic at gmail.com Mon Jul 16 15:03:03 2007 From: bravo.loic at gmail.com (bravo.loic at gmail.com) Date: Mon, 16 Jul 2007 19:03:03 -0000 Subject: Bug with make altinstall ? Message-ID: <1184612583.704313.281800@q75g2000hsh.googlegroups.com> I've made a local installation of Python2.5 with the following instruction : export BASE=/usr/local/python251 cd Python.2.5.1 ./configure --prefix=${BASE}/\ LDFLAGS="-L\${BASE}/lib/"\ PPFLAGS="-I\${BASE}/include/"\ make make test make altinstall It works fine on Linux except this little inconsistency : --------------------- % /usr/local/python251/bin/idle zsh: ./idle: bad interpreter: /usr/local/python25/bin/python: aucun fich ier ou r?pertoire de ce type zsh: exit 127 ./idle -------------------- Indeed, the make altinstall instruction does not make the link from python2.5 to python, but idle contains the following code : --------------------- % more idle #!/usr/local/python251/bin/python from idlelib.PyShell import main if __name__ == '__main__': main() --------------------- Shouldn't the shebang be replaced with #!/usr/local/python251/bin/ python2.5 ? This pb doesn't appear with pydoc and pycolor, so it smells like a bug to me Bests, -- BL From arkanes at gmail.com Thu Jul 12 13:18:11 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 12 Jul 2007 12:18:11 -0500 Subject: storing pickles in sql data base In-Reply-To: <5flucrF3cnokrU1@mid.uni-berlin.de> References: <592087469.jZQWuvoN0q@teancum> <5flucrF3cnokrU1@mid.uni-berlin.de> Message-ID: <4866bea60707121018m454bd7e8vaa21d6c38874aca1@mail.gmail.com> On 12 Jul 2007 06:00:59 GMT, Marc 'BlackJack' Rintsch wrote: > On Wed, 11 Jul 2007 17:14:43 -0500, Chris Mellon wrote: > > > [pickle] > > > > Protocol 0 (the default) is a text protocol, it's safe to store in a > > text field or write to a text file. > > It's not really a text protocol it's more a binary protocol that uses just > the ASCII range of byte values. You have to write and read the "text" > files in binary mode or they break if taken across platform boundaries > because of the different line endings in Linux and Windows for instance. > It's fine as long as you use universal line endings mode. From steve at holdenweb.com Thu Jul 5 20:28:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Jul 2007 20:28:28 -0400 Subject: None returned? In-Reply-To: <1183677572.648960.49070@m37g2000prh.googlegroups.com> References: <1183677572.648960.49070@m37g2000prh.googlegroups.com> Message-ID: robinsiebler at gmail.com wrote: > I can't figure out -what- is going wrong here. When the code reaches > the 'return' line, there is data to be returned, but when it exits out > to the calling function, 'None' is returned! > > import mx.DateTime > > def get_weeks(weeks, year, dates, date_list={}): > if dates.has_key(year): > date_list[year] = dates[year].keys()[-weeks:] > if len(dates[year].keys()) >= weeks: > return date_list > else: > weeks = weeks - len(dates[year].keys()) > get_weeks(weeks, str(int(year) -1), dates, date_list) > So if the else branch is taken here you end up dropping of the end of the function's code, which will return None. > def get_report_dates(weeks, dates): > today = mx.DateTime.now() > this_week = today.iso_week[1] > rpt_dates = get_weeks(weeks, str(today.year), dates) > print rpt_dates > > def main(): > > dates = {'2006': {'50': [50, 'This is the 50th week'], > '51': [51, 'This is the 51st week'], > '52': [52, 'This is the 52nd week']}, > '2007': {'25': [1, 'This is the 1st week'], > '26': [2, 'This is the 2nd week'], > '27': [3, 'This is the 3rd week'], > '28': [4, 'This is the 4th week'], > '29': [5, 'This is the 5th week']}} > > get_report_dates(6, dates) > 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 kelybrown at gmail.com Mon Jul 23 17:14:29 2007 From: kelybrown at gmail.com (K. Brown) Date: Mon, 23 Jul 2007 14:14:29 -0700 Subject: =?utf-8?B?4pa64pa6IEdFVCBGUkVFIFNhdGVsbGl0ZSBUViBvbiB5b3VyIFBDIC0gRG93bmxvYWQgTm93ISDil4Til4Q=?= Message-ID: <1185225269.218941.183490@m37g2000prh.googlegroups.com> SATELLITE TV for PC - Amazing Software which Instantly Turns your Computer into a Super TV! Get over 3000 Stations. Watch all your favorite shows on your Computer! Save 1000's of $$$ over many years on cable and satellite bills INSTANT DOWNLOAD Know More About It: http://tvonpc.xt.cx From george.sakkis at gmail.com Wed Jul 25 16:02:14 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 25 Jul 2007 20:02:14 -0000 Subject: is_iterable function. In-Reply-To: <5uNpi.36822$G23.3430@newsreading01.news.tds.net> References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> <5uNpi.36822$G23.3430@newsreading01.news.tds.net> Message-ID: <1185393734.214020.211780@g4g2000hsf.googlegroups.com> On Jul 25, 3:26 pm, Neil Cerutti wrote: > Speaking of the iter builtin function, is there an example of the > use of the optional sentinel object somewhere I could see? # iterate over random numbers from 1 to 10; use 0 as a sentinel to stop the iteration for n in iter(lambda:random.randrange(10), 0): print n More generally, iter(callable, sentinel) is just a convenience function for the following generator: def iter(callable, sentinel): while True: c = callable() if c == sentinel: break yield c George From zentraders at gmail.com Tue Jul 31 21:58:45 2007 From: zentraders at gmail.com (Zentrader) Date: Tue, 31 Jul 2007 18:58:45 -0700 Subject: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why? In-Reply-To: <1185841560.223868.285110@z24g2000prh.googlegroups.com> References: <1185791793.141118.44080@x35g2000prf.googlegroups.com> <5h5ufoF3hmufcU4@mid.uni-berlin.de> <1185814119.604341.204100@z28g2000prd.googlegroups.com> <1185838264.101543.246150@g12g2000prg.googlegroups.com> <1185841560.223868.285110@z24g2000prh.googlegroups.com> Message-ID: <1185933525.942752.282190@i38g2000prf.googlegroups.com> > In the utter absence of any clues from the OP, Marc was demonstrating > one possible way that the puzzling [Can't subtract one Decimal > instance from another???] error message could have been caused. Ah yes. Until this is no longer true, "In the utter absence of any clues from the OP", we can do no more. My appologies to Marc for misinterpretation. From byte8bits at gmail.com Tue Jul 31 11:14:14 2007 From: byte8bits at gmail.com (brad) Date: Tue, 31 Jul 2007 11:14:14 -0400 Subject: get directory and file names In-Reply-To: <1185891786.452267.57120@57g2000hsv.googlegroups.com> References: <1185891786.452267.57120@57g2000hsv.googlegroups.com> Message-ID: Alchemist wrote: > I am working with Python 2.5 on Windows XP (SP2). > > How can I traverse a folder, loop through a list of files and get > their file name and extension in an elegant, pythonic way? > > Thank you. > try this: for root, dirs, files in os.walk('.'): for f in files: print os.path.splitext(os.path.join(root,f)) From robert.rawlins at thinkbluemedia.co.uk Wed Jul 4 06:09:49 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 4 Jul 2007 11:09:49 +0100 Subject: Which Python Version Message-ID: <000001c7be23$7d676790$783636b0$@rawlins@thinkbluemedia.co.uk> Hello Chaps, Is there a command I can run to confirm which version of python I'm running? Another thing I've always wondered, should i be running my applications using './MyFile.py' or 'Python MyFile.Py' what are the benefits of each method? One thing I have noticed is that when I used 'Python MyFile.Py' my processor usage was a lot higher, is that normal? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjkk73 at gmail.com Mon Jul 2 16:41:00 2007 From: jjkk73 at gmail.com (jj kk) Date: Mon, 2 Jul 2007 22:41:00 +0200 Subject: python script for monitoring input/output parameters of online gaming client Message-ID: Hi, I'd like to be able to capture parameters of online gaming client applications (the kind of client software you install to play poker, backgammon... online) with the aim of writing python software that analyzes this data. I'm clueless, as I know next to nothing about python networking. Could anyone please point out in what direction I should look to solve this, what libraries I should look at, etc. ? Thanks a lot. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rrr at ronadam.com Tue Jul 17 22:18:41 2007 From: rrr at ronadam.com (Ron Adam) Date: Tue, 17 Jul 2007 21:18:41 -0500 Subject: Break up list into groups In-Reply-To: <9e95df10707171408k2dfc8e08wd4056b80fcbe309b@mail.gmail.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> <1184694533.380918.169640@m37g2000prh.googlegroups.com> <469D09CC.3080402@ronadam.com> <9e95df10707171408k2dfc8e08wd4056b80fcbe309b@mail.gmail.com> Message-ID: <469D7881.6030504@ronadam.com> Matt McCredie wrote: > That certainly is fast, unfortunately it doesn't pass all of the tests. > I came up with those tests so I don't know how important they are to the > original poster. I modified it and came up with a generator and a > non-generator version based (roughly) on your algorithm, that are almost > as quick, and pass all of the tests. Some of the modifications were done > just to make it quicker, so it would be fair when comparing against the > other methods. I hard-coded the comparison instead of using a function > and created a function that directly generates and returns a list > instead of a generator. I would probably use the generator version in my > code, but wrapping `list' around a generator adds about 4us (on my > machine). Anyway, getgroups7 passes all of the tests I mentioned and it > was timed at 10.37usec/pass. The down side: the code doesn't seem nearly > as elegant. > > Matt In most cases you wouldn't wrap the generator version in a list(), but use it directly as a loop iterator. A little renaming of variables helps it be a bit more elegant I think ... def getgroups8(seq): groups = [] iseq = iter(xrange(len(seq))) for start in iseq: if seq[start] & 0x80: for stop in iseq: if seq[stop] & 0x80: groups.append(seq[start:stop]) start = stop groups.append(seq[start:]) return groups This passes all the tests and runs about the same speed. Cheers, Ron > > def gengroups7(seq): > iseq = iter(xrange(len(seq))) > start = 0 > for i in iseq: > if seq[i]&0x80: > start = i > break > else: > return > for i in iseq: > if seq[i]&0x80: > yield seq[start:i] > start = i > yield seq[start:] > > > def getgroups7(seq): > groups = [] > iseq = iter(xrange(len(seq))) > start = 0 > for i in iseq: > if seq[i]&0x80: > start = i > break > else: > return groups > for i in iseq: > if seq[i]&0x80: > groups.append(seq[start:i]) > start = i > groups.append(seq[start:]) > return groups > > > > > > From steve at REMOVE.THIS.cybersource.com.au Thu Jul 19 04:09:59 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 19 Jul 2007 18:09:59 +1000 Subject: class C: vs class C(object): References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> Message-ID: On Thu, 19 Jul 2007 07:31:06 +0000, nvictor wrote: > Hi, > > I'm not an experienced developer, and I came across this statement by > reading a code. I search for explanation, but can't find anything > meaningful. I read the entire document written by python's creator > about the features of version 2.2 The one named unifying types and > classes. But This document only blew my head away. > > I ended here and think somebody can explain me more about this. The > only thing I have noticed is that when you do dir(C) on a classic > class you get a bunch of attributes; and when you do the same thing on > a class defined using class C(object), you get less attributes. > > Thanks for all replies. The short answer is, unless you are writing code that has to be backwards compatible with very old versions of Python, always use new style classes by inheriting from object instead of old-style classes. It isn't wrong to use the old style, but it is deprecated, and they will eventually go away. Old style classes are the way classes used to be, back in Ancient Days. You couldn't inherit from built-in types like str or int, which used a different mechanism under the hood. Certain very useful features simply will not work correctly with old-style classes, like properties and slots. Also, multiple inheritance works better with new-style classes: there is a subtle design flaw in the way it works for old-style classes, which can lead to bugs. For the technical answer about the difference, go back and read the document about unifying classes and types. -- Steven. From larry.bates at websafe.com Thu Jul 12 18:17:15 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 12 Jul 2007 17:17:15 -0500 Subject: Function parameter type safety? In-Reply-To: <1184277163.803229.318660@g4g2000hsf.googlegroups.com> References: <1184277163.803229.318660@g4g2000hsf.googlegroups.com> Message-ID: <4OmdnbO92dPDNQvbnZ2dnUVZ_iydnZ2d@comcast.com> Robert Dailey wrote: > Hi, > > Is there a way to force a specific parameter in a function to be a > specific type? For example, say the first parameter in a function of > mine is required to be a string. If the user passes in an integer, I > want to notify them that they should pass in a string, not an integer. > There is, but be careful. What about a string-like object, why would you want to fail on that. It is better to attempt to do whatever you want to do with the string and catch the exception. Possible solution that I don't really like, but meets your explicit requirement: def foo(arg1): if isinstance(arg1, (basestring, unicode): print "is string" else: print "is NOT string" return -Larry From wbrehaut at mcsnet.ca Sat Jul 14 15:34:07 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Sat, 14 Jul 2007 13:34:07 -0600 Subject: Can a low-level programmer learn OOP? References: <1i17kzo.1kphm951d3jl5dN%aleax@mac.com> Message-ID: <6r2i93dcthg5j47nr8nuds5apeomseb2dr@4ax.com> On Sat, 14 Jul 2007 19:18:05 +0530, "Rustom Mody" wrote: >On 7/14/07, Alex Martelli wrote: >> >> OOP can be abused (particularly with deep or intricate inheritance >> structures). But the base concept is simple and clear: you can bundle >> state and behavior into a stateful "black box" (of which you may make as >> many instances, with independent state but equal behavior, as you need). >> > >Many years ago (86??) Wegner wrote a paper in OOPSLA called Dimensions >of Object Orientation in which he called the 'base concept' of 'bundle >of state and behavior' as 'object based' programming and >'object-oriented' as object-based + inheritance. Not quite--according to him: object-based + classes => class-based class-based + class inheritance => object-oriented I.e., "object-oriented = objects + classes + inheritance". This was not the, by then, standard definition: to be OO would require all four of: 1. modularity (class-based? object-based?) 2. inheritance (sub-classing) 3. encapsulation (information hiding) 4. polymorphism ((sub-) class-specific response to a message, or processing of a method) Unfortunately, most of the "definitions" (usually just hand-waving, loosey-goosey descriptions) found on the web include none--or only one or two--of these fundamental requirements by name, and are so loose that almost any proramming paradigm or style would be OO. >What Alex is saying is (in effect) that object-based is simple and >clear (and useful) whereas the object-orientation is subject to abuse. But OO is also simple and clear (if clearly defined and explained and illustrated and implemented), and ANY programming style is subject to abuse. During the hey-day of Pascal as an introductory programming language (as often misused as more than that) I found many often spent much of their time defining the data types their program would use. >This anyway is my experience: C++ programmers are distinctly poorer >programmers than C programmers -- for some strange reason closeness to >the machine has a salutary effect whereas the encouragment of >uselessly over-engineered programs makes worse programmers. But this is a tautology: "over-engineered" programs are, by definition or terminology, not a good thing--independent of what PL or style they're finally implemented in (assuming that by "engineering" you mean "design" or similar). Many of my Pascal students over-engineered their solutions to simple problems too? >GUI is one of those cases wherein inheritance actually helps people >produce better code but this is something of an exception. This seems to imply that the list of applications you have in mind or have worked on includes fewer domains that might profit from full OO instead of just OB. My guess is that there are many application domains in which analysts and programmers often think in an "OO way", but implement in just an OB way because of the PL they or their employer requires or prefers: in some--perhaps many--of these cases they have to do "manually" what OO would have automated. There is a problem, though, of (especially university and college) education and training in OOP "talking about" how glorious OO is, and requiring students to use OO techniques whether they're most appropriate or not (the "classes early" pedagogical mindset). And this problem is compounded by teaching introductory programming using a language like Java that requires one to use an OO style for even trivial programs. And by using one of the many very similar introductory texbooks that talk a lot about OO before actually getting started on programming, so students don't realize how trivial a program is required to solve a trivial problem, and hence look for complexity everywhere--whether it exists or not--and spend a lot of time supposedly reducing the complexity of an already simple problem and its method of solution. But as I noted above, a similar problem occurred with the crop of students who first learned Pascal: they often spent much of their time defining the data types their program would use, just as OO (especially "classes early") graduates tend to waste time "over-subclassing" and developing libraries of little-used classes. The answer is always balance, and having an extensive enough toolkit that one is not forced or encouraged to apply a programming model that isn't appropriate and doesn't help in any way (including maintainability). And starting with a language that doesn't brainwash one into believing that the style it enforces or implies is always the best--and texbooks that teach proper choice of programming style instead of rigid adherence to one. wwwayne From simon.hibbs at gmail.com Fri Jul 13 13:59:09 2007 From: simon.hibbs at gmail.com (Simon Hibbs) Date: Fri, 13 Jul 2007 10:59:09 -0700 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: <1184349549.484402.214860@o61g2000hsh.googlegroups.com> Chris, I can fully relate to your post. I trained as a programmer in the 80s when OOP was an accademic novelty, and didn't learn OOP untill around 2002. However now I find myself naturaly thinking in OOP terms, although I'm by no means an expert - I'm a sysadmin that writes the occasional utility. I found learning OOP with Python very easy because it has such a stripped-down and convenient syntax. The advantages of OOP aren't in performance or memory, they're in the fact that OOP simplifies the ways in which we can think about and solve a problem. OOP packages up the functionality of a program into logical units (objects) which can be written, debugged and maintained independently of the rest of the programme almost as if they were completely seperate programmes of their own, with their own data and 'user inteface' in the form of callable functions (actualy methods). Here's a realy excellent tutorial on Python that's fun to follow. Downloading and installing python, and following this tutorial will probably take about as long as it took to write your post in the first place. At the end of it you'll have a good idea how OOP works, and how Python works. Learning OOp this way is easy and painless, and what you learn about the theory and principles of OOP in Python will be transferable to C++ if you end up going in that direction. I hope this was helpful. Simon Hibbs From half.italian at gmail.com Tue Jul 3 13:28:06 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: Tue, 03 Jul 2007 17:28:06 -0000 Subject: allow scripts to use .pth files? In-Reply-To: References: Message-ID: <1183483686.935115.285820@x35g2000prf.googlegroups.com> On Jul 3, 7:35 am, Alan Isaac wrote: > Suppose I have a directory `scripts`. > I'd like the scripts to have access to a package > that is not "installed", i.e., it is not on sys.path. > On this list, various people have described a variety > of tricks they use, but nobody has proposed a > pretty way to allow this. > I am therefore assuming there is not one. (?) > > How about allowing a `scripts.pth` file in such a `scripts` > directory, to work like a path configuration file? > (But to be used only when __name__=="__main__".) > Drawbacks? > > Alan Isaac import sys sys.path.append("../scripts") import Module_from_scripts_dir ~Sean From exarkun at divmod.com Fri Jul 20 11:55:36 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 20 Jul 2007 11:55:36 -0400 Subject: Pickled objects over the network In-Reply-To: <9c8d48280707200827h66d32ffcxe68978590efd3e97@mail.gmail.com> Message-ID: <20070720155536.4947.302498406.divmod.quotient.13831@ohm> On Fri, 20 Jul 2007 08:27:13 -0700, Walker Lindley wrote: >It doesn't interface well because the string you end up with often doesn't >fit into a single packet. Therefore you have to add a layer of protocol on >top of it that allows you to check to make sure you have the whole string >received before trying to unpickle it. This the case even if you use >socket's makefile() method to make a file descriptor. This is somewhat misleading. TCP doesn't guarantee any minimum packet size larger than a single byte. Any messaging system which uses strings longer than one byte must have a framing protocol to be reliable. So, this isn't really specific to pickle. Basically, all protocols have to address this. Jean-Paul From duncan.booth at invalid.invalid Tue Jul 17 09:53:09 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 Jul 2007 13:53:09 GMT Subject: a=0100; print a ; 64 how to reverse this? References: <1184670575.205759.115360@i13g2000prf.googlegroups.com> <1184673934.660465.228280@i13g2000prf.googlegroups.com> Message-ID: John Machin wrote: > Here's a sketch; I'll leave you to fill in the details -- you may wish > to guard against interesting input like b < 2. > >>>> def anybase(n, b, digits='0123456789abcdef'): > ... tmp = [] > ... while n: > ... n, d = divmod(n, b) > ... tmp.append(digits[d]) > ... return ''.join(reversed(tmp)) > ... Nice. Here's a one-line version based on your code (with added check for negative n): def anybase(n, b, digits='0123456789abcdef'): return ('-'+anybase(-n,b) if n < 0 else '0' if n==0 else ''.join([digits[d] for (n,d) in iter(lambda:divmod(n,b), (0,0))])[::-1]) From ptmcg at austin.rr.com Thu Jul 26 22:54:15 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 26 Jul 2007 19:54:15 -0700 Subject: pyparser and recursion problem In-Reply-To: References: <1185479408.520124.40670@k79g2000hse.googlegroups.com> Message-ID: <1185504855.745706.241590@d55g2000hsg.googlegroups.com> On Jul 26, 3:27 pm, Neil Cerutti wrote: > > Hopefully I'll have time to help you a bit more later, or Paul > MaGuire will swoop down in his pyparsing powered super-suit. ;) > There's no need to fear...! Neil was dead on, and your parser is almost exactly right. Congratulations for delving into the arcane Dict class, not an easy element for first time pyparsers! Forward() would have been okay if you were going to have your macros defined in advance of referencing them. However, since you are defining them after-the-fact, you'll have to wait until all the text is parsed into a tree to start doing the macro substitution. Your grammar as-is was almost exactly right (I've shown the minimal mod needed to make this work, plus an alternative grammar that might be a bit neater-looking). To perform some work after the tree is built, you attach a parse action to the top-level doc element. This parse action's job is to begin with the "Start" element, and recursively replace words in all caps with their corresponding substitution. As you surmised, the Dict class automagically builds the lookup dictionary for you during the parsing phase. After the parse action runse, the resulting res["Start"] element gives the desired results. (This looks vaguely YAML-ish, am I right?) -- Paul Here is your working code: from pyparsing import Word, Optional, OneOrMore, Group, alphas, \ alphanums, Suppress, Dict, Combine, delimitedList, traceParseAction, \ ParseResults import string def allIn( as, members ): "Tests that all elements of as are in members""" for a in as: if a not in members: return False return True def allUpper( as ): """Tests that all strings in as are uppercase""" return allIn( as, string.uppercase ) def getItems(myArray, myDict): """Recursively get the items for each CAPITAL word""" myElements=[] for element in myArray: myWords=[] for word in element: if allUpper(word): items = getItems(myDict[word], myDict) myWords.append(items) else: myWords.append(word) myElements.append(myWords) return myElements testData = """ :Start: first SECOND THIRD fourth FIFTH :SECOND: second1_1 second1_2 | second2 | second3 :THIRD: third1 third2 | SIXTH :FIFTH: fifth1 | SEVENTH :SIXTH: sixth1_1 sixth1_2 | sixth2 :SEVENTH: EIGHTH | seventh1 :EIGHTH: eighth1 | eighth2 """ #> original grammar - very close! #> just needed to enclose definition of data in a Group label = Suppress(":") + Word(alphas + "_") + Suppress(":") words = Group(OneOrMore(Word(alphanums + "_"))) + \ Suppress(Optional("|")) #~ data = ~label + OneOrMore(words) data = Group( OneOrMore(words) ) line = Group(label + data) doc = Dict(OneOrMore(line)) #> suggested alternative grammar #> - note use of Combine and delimitedList #~ COLON = Suppress(":") #~ label = Combine( COLON + Word(alphas + "_") + COLON ) #~ entry = Word(alphanums + "_") #~ data = delimitedList( Group(OneOrMore(entry)), delim="|" ) #~ line = Group(label + data) #~ doc = Dict(OneOrMore(line)) # recursive reference fixer-upper def fixupRefsRecursive(tokens, lookup): if isinstance(tokens, ParseResults): subs = [ fixupRefsRecursive(t, lookup) for t in tokens ] tokens = ParseResults( subs ) else: if tokens.isupper(): tokens = fixupRefsRecursive(lookup[tokens], lookup) return tokens #> add this parse action to doc, which invokes recursive #> reference fixer-upper def fixupRefs(tokens): tokens["Start"] = fixupRefsRecursive( tokens["Start"], tokens ) doc.setParseAction( fixupRefs ) res = doc.parseString(testData) # This prints out what pyparser gives us #~ for line in res: #~ print line #> not really interested in all of res, just the fixed-up #> "Start" entry print res["Start"][0].asList() print startString = res["Start"] items = getItems([startString], res)[0] # This prints out what we want for line in items: print line Prints: ['first', [['second1_1', 'second1_2'], ['second2'], ['second3']], [['third1', 'third2'], [[['sixth1_1', 'sixth1_2'], ['sixth2']]]], 'fourth', [['fifth1'], [[[[['eighth1'], ['eighth2']]], ['seventh1']]]]] ['first', [['second1_1', 'second1_2'], ['second2'], ['second3']], [['third1', 'third2'], [[['sixth1_1', 'sixth1_2'], ['sixth2']]]], 'fourth', [['fifth1'], [[[[['eighth1'], ['eighth2']]], ['seventh1']]]]] From stefan.behnel-n05pAM at web.de Tue Jul 24 03:40:39 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Tue, 24 Jul 2007 09:40:39 +0200 Subject: Parsing XML with ElementTree (unicode problem?) In-Reply-To: <1185256646.060652.199740@d55g2000hsg.googlegroups.com> References: <1185200976.082516.105420@57g2000hsv.googlegroups.com> <1185256646.060652.199740@d55g2000hsg.googlegroups.com> Message-ID: <46A5ACF7.6040303@web.de> oren.tsur at gmail.com wrote: > On Jul 23, 4:46 pm, "Richard Brodie" wrote: >> wrote in message >> >> news:1185200976.082516.105420 at 57g2000hsv.googlegroups.com... >> >>> so what's the difference? how comes parsing is fine >>> in the first case but erroneous in the second case? >> You may have guessed the encoding wrong. It probably >> wasn't utf-8 to start with but iso8859-1 or similar. >> What actual byte value is in the file? > > I tried it with different encodings and it didn't work. Anyways, I > would expect it to be utf-8 since the XML response to the amazon query > indicates a utf-8 (check it with > http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=189P5TE3VP7N9MN0G302&Operation=ItemLookup&ItemId=1400079179&ResponseGroup=Reviews&ReviewPage=166 > > in your browser, the first line in the source is encoding="UTF-8"?>) > > but the thing is that the parser parses it all right from the web (the > amazon response) but fails to parse the locally saved file. Then how did you save it to a file? Using your browser? Maybe that messed it up? Or did you edit it with an Editor that doesn't understand UTF-8? If you want to extract the interesting stuff programmatically, you can use lxml.etree. It's ElementTree compatible, but it can parse right from HTTP URLs and it supports XPath for selecting stuff. http://codespeak.net/lxml/ Stefan From python at jayloden.com Tue Jul 31 19:53:48 2007 From: python at jayloden.com (Jay Loden) Date: Tue, 31 Jul 2007 19:53:48 -0400 Subject: Iteration over strings In-Reply-To: <46AFA1D9.1010707@gmx.net> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> <46AF7A49.3040804@jayloden.com> <46AF8046.7090702@gmx.net> <496954360707311307y7d503b8eybd72795c8e699104@mail.gmail.com> <46AF9B2D.8040501@jayloden.com> <46AF9F55.20105@gmx.net> <46AFA1D9.1010707@gmx.net> Message-ID: <46AFCB8C.9060800@jayloden.com> Hexamorph wrote: > Hexamorph schrieb: >> Jay Loden schrieb: >>> I have to agree with you WRT to the Python documentation, it does tend >>> to be lacking and difficult to find things at times. > > Hmm, I find the Python documentation just excellent. You are > searching for a *string* related problem? Then just check the > *string* class. Also try the dir() function, like > dir(some_string_variable) > > If you come from a C++ background this should be familar to you. > Check the appropriate class before trying some "procedural" way. > > Anyway, glad we could help :) Well, I don't want to start a flamewar or anything like that - after all, I'm on a Python mailing list, I love coding in Python, and I think it's a great language. I've just personally been repeatedly frustrated when programming on the lack of documentation for some modules (including some in the standard library). Don't get me wrong, I love the documentation concepts like docstrings, pydoc, the online HTML docs, etc. What I don't like is how frequently I run into things that just aren't documented *well* ;) As an example, reading the docs for the "socket" module repeatedly tells you things like 'see the UNIX manual' instead of just documenting the appropriate information. I realize these are simply thin wrappers for C sockets, but that still assumes your audience is rather intimately familiar with socket programming in C on UNIX. 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. One of the items on my very long TODO list is to submit bug reports for items like the above but it's a long list and I just haven't gotten there yet ;) -Jay From horpner at yahoo.com Mon Jul 2 16:56:26 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 02 Jul 2007 20:56:26 GMT Subject: Pretty Scheme, ??? Python References: <46895e12$0$5078$ba4acef3@news.orange.fr> Message-ID: <_Ddii.36114$G23.10348@newsreading01.news.tds.net> On 2007-07-02, Laurent Pointal wrote: > Neil Cerutti wrote: >> How can I make the Python more idiomatic Python? > > Have you taken a look at pyparsing ? Yes, I have it. PyParsing has, well, so many convenience features they seem to shout down whatever the core features are, and I don't know quite how to get started as a result. Hardest of all was modifying a working PyParsing program. As a result, I've found writing my own recursive descent parsers much easier. I'm probably wrong, though. ;) -- Neil Cerutti From deets at nospam.web.de Mon Jul 9 07:19:28 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jul 2007 13:19:28 +0200 Subject: What is the most efficient way to test for False in a list? References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <7x7ipajvst.fsf@ruckus.brouhaha.com> <5fejp2F3cp3igU1@mid.individual.net> Message-ID: <5feju0F3c7pd1U1@mid.uni-berlin.de> Bjoern Schliessmann wrote: > Paul Rubin wrote: >> lex writes: > >>> list = [1, True, True, False, False, True] >>> status = True >>> for each in list: >>> status = status and each >>> >>> but what is your best way to test for for False in a list? >> >> status = all(list) > > Am I mistaken, or is this no identity test for False at all? You are mistaken. all take an iterable and returns if each value of it is true. Diez From sturlamolden at yahoo.no Mon Jul 30 00:49:04 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Sun, 29 Jul 2007 21:49:04 -0700 Subject: Why no maintained wrapper to Win32? In-Reply-To: References: <46ab694e$0$17577$9b622d9e@news.freenet.de> <59kna3p8r0cu2gk6hs5lbig8cjj8klatju@4ax.com> <1185762820.496821.298530@19g2000hsx.googlegroups.com> Message-ID: <1185770944.301464.85060@b79g2000hse.googlegroups.com> On Jul 30, 6:07 am, Gilles Ganault wrote: > For people who don't konw the Win32 API and don't know C... is the > O'Reilly book above the best source of information on how to write > Win32 GUI apps in Python? Why inflict suffering on yourself with MFC when you can use wxPython or PyGTK? Sure, you could use ctypes to make calls into user32.dll, gdi32.dll and kernel32.dll. Then you can program Python GUIs using the plain Win32 API, avoiding PyWin32's MFC or wxPython. But who would do such a thing? From memracom at yahoo.com Sun Jul 22 16:05:10 2007 From: memracom at yahoo.com (memracom at yahoo.com) Date: Sun, 22 Jul 2007 13:05:10 -0700 Subject: idiom for RE matching In-Reply-To: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> Message-ID: <1185134710.574141.106490@57g2000hsv.googlegroups.com> On 19 Jul, 05:52, Gordon Airporte wrote: > I have some code which relies on running each line of a file through a > large number of regexes which may or may not apply. Have you read and understood what MULTILINE means in the manual section on re syntax? Essentially, you can make a single pattern which tests a match against each line. -- Michael Dillon From rex at no_spam.dicad.de Fri Jul 6 07:56:31 2007 From: rex at no_spam.dicad.de (Rex Turnbull) Date: Fri, 06 Jul 2007 13:56:31 +0200 Subject: list.append not working? In-Reply-To: References: <1183651138.209079.37620@q75g2000hsh.googlegroups.com> Message-ID: Wildemar Wildenburger wrote: > Abhishek Jain wrote: >> with every iteration your previous values are overwritten ('md' is a >> dictionary) so thats why your are observing this ouput.. >> >> check if the following patch solves your problem >> >> for entity in temp: >> md['module']= entity.addr.get('module') >> md['id']=entity.addr.get('id') >> md['type']=entity.addr.get('type') >> #print md >> mbusentities.append(md) >> md = {} >> #print mbusentities >> >> >> Regards >> Abhi > This will work, but may I suggest putting the md = {} line at the > *beginning* of the loop? > I find seeing it at the end HIGHLY confusing. Declaring it in the > beginning makes sense, because you declare/initialize, then use it. But > using and *then* initializing it for the next iteration is kind of > quirky, because it breaks the logical encapsulation I would like to see > in *one* loop iteration. > > /W Hear, hear! to the declaration at the beginning. Just went through a long bug search due to a similar behaviour. Terrible. I try to view the body of a loop as if it were a separate function/method. If it makes sense from that point of view, it will make sense in 3 months. I mean, why would you want ot initialize something when you're done with it? Cheers, Rex From tommy.nordgren at comhem.se Fri Jul 6 12:30:53 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Fri, 6 Jul 2007 18:30:53 +0200 Subject: Expandable 2D Dictionaries? In-Reply-To: <1183736635.415927.208450@57g2000hsv.googlegroups.com> References: <1183736635.415927.208450@57g2000hsv.googlegroups.com> Message-ID: <480418BA-ECDE-49F1-A2E8-D034740EAFC8@comhem.se> On 6 jul 2007, at 17.43, Robert Dailey wrote: > Hi, > > I am interested in creating an expandable (dynamic) 2D dictionary. For > example: > > myvar["cat"]["paw"] = "Some String" > > The above example assumes "myvar" is declared. In order for this to > work, I have to know ahead of time the contents of the dictionary. For > the above to work, my declaration must look like: > > myvar = {"cat": {"paw":""} } > > I would like to not have to declare my dictionary like this, as it > does not allow it to be expandable. I'm very new to Python (I'm a > professional C++ programmer. Any comparisons to C++ would help me > understand concepts). > > Is there a way that when I index into my dictionary using an "unknown" > index (string), that python will dynamically add that key/value pair? > > Thanks. > The best way to do this, is probably to implement your own class. As far as I know, Python supports operator overloads, although the syntax is different than C++. ------ 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 kyosohma at gmail.com Tue Jul 3 17:27:25 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 03 Jul 2007 14:27:25 -0700 Subject: Restarting a Python Application Message-ID: <1183498045.092504.229250@m36g2000hse.googlegroups.com> Hi, I packaged up an application I am developing into an executable. In the application, it has user configurable options. I would like a way to restart the application so that the new options the user chooses can be applied. Firefox can restart itself. Does anyone know how to accomplish this in Python? Here is what I tried: exePath = os.path.join(os.getcwd(), 'myprogram.exe') subprocess.Popen(exePath) sys.exit() This didn't work. It closed the program, but another instance did not appear. Tips would be appreciated. Mike From stefan.behnel-n05pAM at web.de Sun Jul 1 07:17:06 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 01 Jul 2007 13:17:06 +0200 Subject: Reversing a string In-Reply-To: References: <1182997438.541012.54100@o61g2000hsh.googlegroups.com> Message-ID: <46878D32.8060904@web.de> Martin Durkin wrote: > Duncan Booth wrote in > news:Xns996067AFF71DDduncanbooth at 127.0.0.1: > >> Martin Durkin wrote: >> >>>>>>> def rev(x): >>>> mylist = [] >>>> for char in x: >>>> mylist.append(char) >>>> mylist.reverse() >>>> for letter in mylist: >>>> print letter >>>> >>>> However, compare the incredible difference in clarity and elegance >>>> between that and: >>>> >>>>>>>> print "\n".join("spam"[::-1]) >>> OK, maybe I'm missing the point here as I'm new to Python. The first >>> one seems clearer to me. What am I missing? >>> >> I think all you are missing is familarity with Python, but I too don't >> like one-liners simply for their own sake. >> > > I guess that's it. The first one reads more like a textbook example which > is about where I am at. Is there any speed benefit from the one liner? Almost definitely. But you can check yourself by using the timeit module. Stefan From bj_666 at gmx.net Tue Jul 10 11:57:59 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 10 Jul 2007 15:57:59 GMT Subject: Need Help References: <1184081285.869000.75460@i38g2000prf.googlegroups.com> Message-ID: <5fhok7F3c0ts7U2@mid.uni-berlin.de> On Tue, 10 Jul 2007 08:28:05 -0700, pycraze wrote: > In the above code what does " > 000\000\000\000\000\000\000\000\000 " signify ? Which form of > representation is this ? \nnn is the octal representation of a byte. The snippet you've shown contains mostly zero bytes: In [10]: a = '\000' In [11]: a Out[11]: '\x00' In [12]: ord(a) Out[12]: 0 Ciao, Marc 'BlackJack' Rintsch From george.sakkis at gmail.com Wed Jul 25 16:12:30 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 25 Jul 2007 20:12:30 -0000 Subject: first, second, etc line of text file In-Reply-To: References: Message-ID: <1185394350.032814.262990@d55g2000hsg.googlegroups.com> On Jul 25, 3:44 pm, "Daniel Nogradi" wrote: > A very simple question: I currently use a cumbersome-looking way of > getting the first, second, etc. line of a text file: > > for i, line in enumerate( open( textfile ) ): > if i == 0: > print 'First line is: ' + line > elif i == 1: > print 'Second line is: ' + line > ....... > ....... > > I thought about f = open( textfile ) and then f[0], f[1], etc but that > throws a TypeError: 'file' object is unsubscriptable. > > Is there a simpler way? If all you need is sequential access, you can use the next() method of the file object: nextline = open(textfile).next print 'First line is: %r' % nextline() print 'Second line is: %r' % nextline() ... For random access, the easiest way is to slurp all the file in a list using file.readlines(). HTH, George From jelleferinga at gmail.com Thu Jul 26 13:48:12 2007 From: jelleferinga at gmail.com (jelle) Date: Thu, 26 Jul 2007 17:48:12 -0000 Subject: adding a docstring to an instancemethod In-Reply-To: <1185438522.978804.118010@19g2000hsx.googlegroups.com> References: <1185361537.733690.238280@k79g2000hse.googlegroups.com> <1185438522.978804.118010@19g2000hsx.googlegroups.com> Message-ID: <1185472092.427646.266270@g4g2000hsf.googlegroups.com> Hi Gabriella, thanks for pointing me in the right direction: eo.eoTruncatedSelectOne.setup.im_func.func_doc = 'method string goes here' works beautifully! cheers, -jelle From greg at cosc.canterbury.ac.nz Wed Jul 4 21:29:04 2007 From: greg at cosc.canterbury.ac.nz (greg) Date: Thu, 05 Jul 2007 13:29:04 +1200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> Message-ID: <5f301fF3a3vqvU1@mid.individual.net> Roy Smith wrote: > greg wrote: > > Then you get a bug report, you fix it, and you add a test > > for it so that particular bug can't happen again. > The TDD zealots would tell you you've got the order wrong. Instead of > "fix, then write a test", it should be "write a failing test, then fix it". Yes, I'm aware of that. I said "and", not "then". :-) -- Greg From horpner at yahoo.com Wed Jul 25 14:49:10 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 25 Jul 2007 18:49:10 GMT Subject: Flatten a list/tuple and Call a function with tuples References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <1185379218.286977.124040@19g2000hsx.googlegroups.com> <1185384306.104549.287510@19g2000hsx.googlegroups.com> <1185384793.577650.256310@d55g2000hsg.googlegroups.com> Message-ID: On 2007-07-25, Neil Cerutti wrote: > On 2007-07-25, Jeff wrote: >> Here's a quick flatten() function: >> >> def flatten(obj): >> if type(obj) not in (list, tuple, str): >> raise TypeError("String, list, or tuple expected in >> flatten().") >> if len(obj) == 1: >> if type(obj[0]) in (tuple, list): >> return flatten(obj[0]) >> else: >> return [obj[0]] >> else: >> return [obj[0]] + flatten(obj[1:]) >> >> x = [1, 2, (3, 4)] >> y = (1, 2, [3, 4]) >> z = "It even works with strings!" >> d = {"foo": "bar", "baz": "bat"} > > e = [[1], 2, 3, , 4] Please excuse my bad typography. The above should've been e = [[1], 2, 3, 4]. -- Neil Cerutti It isn't pollution that is hurting the environment; it's the impurities in our air and water that are doing it. --Dan Quayle From gregpinero at gmail.com Wed Jul 4 16:27:56 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Wed, 04 Jul 2007 20:27:56 -0000 Subject: Does Python work with QuickBooks SDK? In-Reply-To: <1183575085.446434.13410@z28g2000prd.googlegroups.com> References: <1183575085.446434.13410@z28g2000prd.googlegroups.com> Message-ID: <1183580876.475984.92860@q69g2000hsb.googlegroups.com> On Jul 4, 2:51 pm, walterbyrd wrote: > My guess is that it would, but I can find no mention of python in the > intuit developers site. I can find some references to PHP and Perl, > but no Python. > > I looks to me like Intuit develops have a strong preference for visual- > basic, then c/c++, then delphi. > > I find it just a little bit surprising, since Python does work > with .Net and all. I've been using the QuickBooks SDK with Python for years. There was an example somewhere on Intuit's site to get you started. I just built off of that. But now I can't locate that sample anywhere! Basically you just access it via the COM interface. Use the Python win32 extentions. Email me and I can probably help you more. -Greg From beliavsky at aol.com Mon Jul 9 10:38:14 2007 From: beliavsky at aol.com (Beliavsky) Date: Mon, 09 Jul 2007 07:38:14 -0700 Subject: compressing consecutive spaces Message-ID: <1183991894.508562.16430@g4g2000hsf.googlegroups.com> How can I replace multiple consecutive spaces in a file with a single character (usually a space, but maybe a comma if converting to a CSV file)? Ideally, the Python program would not compress consecutive spaces inside single or double quotes. An inelegant method is to repeatedly replace two consecutive spaces with one. From p.c.j.kleiweg at rug.nl Sun Jul 22 16:33:08 2007 From: p.c.j.kleiweg at rug.nl (Peter Kleiweg) Date: Sun, 22 Jul 2007 22:33:08 +0200 Subject: space / nonspace Message-ID: >>> import re >>> s = u'a b\u00A0c d' >>> s.split() [u'a', u'b', u'c', u'd'] >>> re.findall(r'\S+', s) [u'a', u'b\xa0c', u'd'] This isn't documented either: >>> s = ' b c ' >>> s.split() ['b', 'c'] >>> s.split(' ') ['', 'b', 'c', ''] -- Peter From erik at myemma.com Mon Jul 16 17:10:30 2007 From: erik at myemma.com (Erik Jones) Date: Mon, 16 Jul 2007 16:10:30 -0500 Subject: How to organize control access to source code ? In-Reply-To: <1184618776.798929.98960@57g2000hsv.googlegroups.com> References: <1184618776.798929.98960@57g2000hsv.googlegroups.com> Message-ID: <47B35AAB-3DA5-4E2E-A0C0-8D4041AAB7ED@myemma.com> On Jul 16, 2007, at 3:46 PM, Succelus at gmail.com wrote: > Hello, > How can we organize development team with code source control policy, > that limit access to some portion of code ? The specifics largely depend on the system(s) you're working with but, basically (sic), you need to read up on filesystem level permissions. 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 mark_s_robey at hotmail.com Wed Jul 18 02:20:05 2007 From: mark_s_robey at hotmail.com (gravey) Date: Tue, 17 Jul 2007 23:20:05 -0700 Subject: Open HTML file in IE Message-ID: <1184739605.732844.321180@m37g2000prh.googlegroups.com> Hello. Apologies if this is a basic question, but I want to open a HTML file from my local drive (is generated by another Python script) in Internet Explorer. I've had a look at the webbrowser module and this doesn't seem to be what I need. Any help much appreciated. From the.mindstorm.mailinglist at gmail.com Fri Jul 20 15:39:45 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Fri, 20 Jul 2007 19:39:45 +0000 (UTC) Subject: Pythonic way for missing dict keys References: Message-ID: Neil Cerutti wrote in news:slrnfa2325.n4.horpner at FIAD06.norwich.edu: > On 2007-07-20, Alex Popescu wrote: >> Hi all! >> >> I am pretty sure this has been asked a couple of times, but I >> don't seem to find it on the archives (Google seems to have a >> couple of problems lately). >> >> I am wondering what is the most pythonic way of dealing with missing >> keys and default values. >> >> According to my readings one can take the following approaches: > > There's also the popular collections.defaultdict. > > Usually, the get method of normal dicts is what I want. I use a > defaultdict only when the implicit addition to the dictionary of > defaulted elements is what I really want. > This looks like the closest to my needs, but in my case the default value involves the creation of a custom object instance that is taking parameters from the current execution context, so I am not very sure I can use it. ./alex -- .w( the_mindstorm )p. From jstroud at mbi.ucla.edu Sat Jul 14 02:49:56 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 14 Jul 2007 06:49:56 GMT Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: Chris Carlen wrote: > Hi: > > From what I've read of OOP, I don't get it. I have also found some > articles profoundly critical of OOP. I've also found articles critical of Darwinism--but we can chalk that up to religious zealotry can't we? Any gui more complicated than a few entry fields and some checkbuttons is going to lend itself to OOP--so if you want to do GUI, learn OOP. The time you spend learning OOP will be about 1/10th the time required to debug a modestly complicated gui. This is especially true of guis that require real-time feedback behavior. If you just want to enter some values and set some flags and then hit "go", you could always program the GUI in HTML and have a cgi script process the result. This has a lot of benefits that are frequently overlooked but tend to be less fun than using a bona-fide toolkit like WX or QT. James From goldtech at worldpost.com Sun Jul 22 19:07:02 2007 From: goldtech at worldpost.com (leegold) Date: Sun, 22 Jul 2007 16:07:02 -0700 Subject: Sort lines in a text file In-Reply-To: References: <1185073397.821811.143260@k79g2000hse.googlegroups.com> Message-ID: <1185145622.682624.291860@g4g2000hsf.googlegroups.com> ...snip... > > Do your own homework. Hush troll. From arkanes at gmail.com Mon Jul 9 09:48:39 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 9 Jul 2007 08:48:39 -0500 Subject: Broken MUA interactions (was: Restarting a Python Application) In-Reply-To: <87vecvmqw5.fsf_-_@benfinney.id.au> References: <1183498045.092504.229250@m36g2000hse.googlegroups.com> <94ccbe710707071511o3beee718wc12f15082b3c6e18@mail.gmail.com> <87vecvmqw5.fsf_-_@benfinney.id.au> Message-ID: <4866bea60707090648v772e81d2r261e8d927310591c@mail.gmail.com> On 7/8/07, Ben Finney wrote: > "Peter Decker" writes: > > > Imagine if you wrote applications where the default behavior did not > > do what was needed 99% of the time: how long do you think you'd be > > in business? > > You seem to be complaining about the functionality of your mail user > agent (MUA) software. The mailing list processor is doing its job > fine. > It's working as instructed, but that doesn't mean that it's doing the best thing. It's common practice for mailing lists to set the reply-to to the list itself, because that's the common case, and because it's encouraged to keep discussion on the list. If whoever manages the python lists doesn't want to do it, either because they have some practical reason or because they've got a bug up their ass about mail readers without list support, thats fine. But it's hardly incorrect to configure it with the reply-to set to the list, either. From steve at REMOVE.THIS.cybersource.com.au Wed Jul 18 23:47:01 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 19 Jul 2007 13:47:01 +1000 Subject: Implementaion of random.shuffle References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> <87d4ys9z46.fsf@mulj.homelinux.net> <1184787155.773575.303080@d30g2000prg.googlegroups.com> Message-ID: On Wed, 18 Jul 2007 19:32:35 +0000, George Sakkis wrote: > On Jul 16, 10:51 pm, Steven D'Aprano > wrote: >> On Mon, 16 Jul 2007 16:55:53 +0200, Hrvoje Niksic wrote: >> > 2**19937 being a really huge number, it's impossible to exhaust the >> > Mersenne twister by running it in sequence. >> >> "Impossible"? >> >> Surely this will do it: >> >> for n in xrange(2**19937 + 1): >> random.random() >> >> Admittedly, if each call to random() took a picosecond, it would still >> take 1e5982 centuries to run through the lot. You might want to go make a >> coffee or something while you're waiting... > > Wow, can you make a coffee in.. 57ms ? [snip demonstration of xrange raising an exception] Of course! Can't you? And if I use a microwave oven, the coffee is made so quickly that I actually go backwards in time... -- Steven. From phishboh at gmail.com Fri Jul 13 14:56:21 2007 From: phishboh at gmail.com (phishboh at gmail.com) Date: Fri, 13 Jul 2007 11:56:21 -0700 Subject: Numpy array index handling Message-ID: <1184352981.493615.18040@k79g2000hse.googlegroups.com> Being a Matlab user wanting to switch to Python/SciPy, I'd like to know how the following Matlab code would be written in Python: % First, just some artificial data N = 1000000 ; input = sign(randn(1, N)) ; a = (1 : N) ; % This is what I'd like to do; % for indices where the input has a certain value, compute and store something % for indices where the input has another certain value, compute and store something else output(input < 0) = 10 * a(input < 0) ; output(input > 0) = 20 * a(input > 0) ; I have tried the following in Python: N = 1000000 input = sign(randn(N)) a = arange(N) output = zeros(N) output[input < 0] = 10 * a[input < 0] output[input > 0] = 20 * a[input > 0] However, that gives me in IndexError. Of course I could use a for-loop, but I assume that there is another way (although I haven't been able to find it in any documentation). Many thanks in advance! From http Thu Jul 26 02:45:53 2007 From: http (Paul Rubin) Date: 25 Jul 2007 23:45:53 -0700 Subject: Pickled objects over the network References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com> <011401c7caa0$3e3e5900$03000080@hendrik> <012901c7cb60$5ba530c0$03000080@hendrik> <00c601c7cc38$d826ba00$03000080@hendrik> <00bd01c7ccf6$8fa62540$03000080@hendrik> Message-ID: <7x4pjrbr32.fsf@ruckus.brouhaha.com> "Hendrik van Rooyen" writes: > But more seriously - is there any need for a simple serialiser that will > be able to be used to transfer a subset of the built in types over an > open network in a safe manner, for the transfer of things like lists of > parameters? > > Or am I the only person in the squad that hears this particular drum? This has been open for 5+ years: http://sourceforge.net/tracker/index.php?func=detail&aid=467384&group_id=5470&atid=355470 Related: http://sourceforge.net/tracker/index.php?func=detail&aid=471893&group_id=5470&atid=105470 From tn.pablo at gmail.com Sat Jul 21 02:18:45 2007 From: tn.pablo at gmail.com (Pablo Torres) Date: Fri, 20 Jul 2007 23:18:45 -0700 Subject: Permutations with generators In-Reply-To: <1184997910.266858.4550@e9g2000prf.googlegroups.com> References: <1184996537.069416.211730@g4g2000hsf.googlegroups.com> <1184997910.266858.4550@e9g2000prf.googlegroups.com> Message-ID: <1184998725.333012.79840@q75g2000hsh.googlegroups.com> > > list.insert returns None. Thus, except in the one-element case, your > generator is yielding None all the time. > Oh god...silly me. Thank you guys for the help :) P.S I'm dead stubborn, so here's what I did to fix my code: def perm(seq): "Reshuffles the elements of seq in every possible way" if len(seq) == 1: yield seq else: for i in range(len(seq)): for p in perm(seq[1:]): # Here: p.insert(i, seq[0]) yield p From http Mon Jul 2 00:12:37 2007 From: http (Paul Rubin) Date: 01 Jul 2007 21:12:37 -0700 Subject: Tiny/small/minimalist Python? References: <1183332951.122782.212720@o11g2000prd.googlegroups.com> Message-ID: <7xved3satm.fsf@ruckus.brouhaha.com> rtk writes: > I'm looking for information on building a tiny/small/minimalist/ > vanilla python interpreter. One that implements the core language and > a few of the key modules but isn't tied to any specific operating > system. You've gotten good suggestions about Python configurations. Depending on your application you might look at alternative languages as well. Lua and Hedgehog Lisp both come to mind as small embedded interpreters. From jarausch at skynet.be Wed Jul 4 15:13:18 2007 From: jarausch at skynet.be (Helmut Jarausch) Date: Wed, 04 Jul 2007 21:13:18 +0200 Subject: ReSTedit ported to Linux? Message-ID: <468bf14e$0$13850$ba620e4c@news.skynet.be> Hi, does anybody know if ReSTedit (originally for Mac OS X) has been ported to Linux? Many thanks for a hint, Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From borud-news at borud.no Sun Jul 8 12:18:56 2007 From: borud-news at borud.no (Bjorn Borud) Date: 08 Jul 2007 18:18:56 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1183841277.333384.188950@g4g2000hsf.googlegroups.com> <1183856442.027967.272530@g4g2000hsf.googlegroups.com> Message-ID: [Twisted ] | | Translation: since perfection is unattainable, we shouldn't even try, | and just foist upon our poor users whatever awkward and hard-to-learn | interface pops into our heads first? uh, I think the point here is that some think it might be an idea to force *their* idea of the ideal interface upon others, refusing to understand that people might have their own preferences. -Bj?rn From tim.hochberg at gmail.com Wed Jul 11 23:14:44 2007 From: tim.hochberg at gmail.com (tah) Date: Thu, 12 Jul 2007 03:14:44 -0000 Subject: bool behavior in Python 3000? In-Reply-To: References: <5ficp9F3cram2U2@mid.individual.net> <469472f4$0$1293$9b622d9e@news.freenet.de> <1184140795.974059.302830@22g2000hsm.googlegroups.com> <9v4li.8359$MV6.308@trnddc01> Message-ID: <1184210084.671732.123520@k79g2000hse.googlegroups.com> On Jul 11, 1:30 pm, Nick Craig-Wood wrote: > Alan Isaac wrote: > > Miles wrote: > > > What boolean operation does '-' represent? > > > Complementation. > > And as usual, a-b is to be interpreted as a+(-b). > > In which case the desired behavior is > > False-True = False+(-True)=False+False = False > > If you want to do algebra with bools in python then use the logical > operators (and or not) and not the arithmetical operators. > > Eg > > >>> False or not True > False Let me comment on what I suspect is Alan's Hidden Agenda (tm). Since this question surfaced earlier on the numpy list, I suspect that part of the motivation here has to do with trying to come up with a natural way to work with arrays of booleans. The operators and,or,not don't work for this purpose since they can't be overloaded to return an arbitrary value. You can almost make this work with &,|,^: >>> a = np.array([True, False, False]) >>> b = np.array([True, True, False]) >>> a & b array([ True, False, False], dtype=bool) >>> a | b array([ True, True, False], dtype=bool) >>> a ^ b array([False, True, False], dtype=bool) This is meshes well with the behavior of True and False: >>> True & True True >>> True | True True >>> True ^ True False This doesn't leave you with anything equivalent to 'not' however. Or nothing consistent. Currently '~a' will complement a boolean array,: >>> ~a array([False, True, True], dtype=bool) However that's less than ideal since it doesn't mesh up with the behavior of booleans on their own: >>> ~True -2 That's potentially confusing. It's not any skin of my nose since I use, and will likely continue to use, boolean arrays in only the most rudimentary ways. However, I thought I'd offer some additional context. -tim From steve at holdenweb.com Mon Jul 16 15:35:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 16 Jul 2007 15:35:49 -0400 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: Chris Carlen wrote: > Hendrik van Rooyen wrote: >> "Chris Carlen" wrote: >>> Form 2: Use Python and PySerial and TkInter or wxWidgets. >>> Pro: Cross-platform goal will likely be achieved fully. Have a >>> programmer nearby with extensive experience who can help. >>> Con: Must learn new language and library. Must possibly learn a >>> completely new way of thinking (OOP) not just a new language syntax. >>> This might be difficult. >> This is the way to go. - Trust me on this. >> When you describe your history, it is almost an exact parallel to mine. >> In my case, I have been doing real low level stuff (mostly 8031 assembler) >> since 1982 or so. And then I found python in a GSM module (Telit), and >> I was intrigued. >> I really appreciate your comments on OO - it parallels a lot of what I feel >> as there is a lot of apparent BS that does not seem to "do anything" at first >> sight. >> However- for the GUI stuff, there is an easily understood relationship between >> the objects and what you see on the screen - so its a great way of getting >> into OO - as far as people like you and me will go with it, which is not very >> far, as we tend to think in machine instructions... >> And for what its worth - you can programme assembler-like python, and it also >> works. >> >> The best thing to do is just to spend a few days playing with say Tkinter. >> I use a reference from the web written by John W Shipman at New Mexico >> Tech - it is succinct and clear, and deserves more widespread publicity. >> >> Google for it - I have lost the link, although I still have the pdf file. > [edit] > > Thanks for the tip. The next poster provides the link, which I've got > bookmarked now. > > The more I play with Python, the more I like it. Perhaps I will > understand OOP quicker than I thought. What I've learned so far about > names binding to objects instead of values stored in memory cells, etc. > has been interesting and fascinating. > > > I'm happy you are proceeding with so little trouble. Without wishing to confuse you, however, I should point out that this aspect of Python has very little to do with its object-orientation. There was a language called Icon, for example, 20 years ago, that used similar semantics but wasn't at all object-oriented. 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 Jul 4 03:09:53 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 04 Jul 2007 17:09:53 +1000 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> <7x645al8kc.fsf@ruckus.brouhaha.com> <1182894003.920335.317620@a26g2000pre.googlegroups.com> <7x7ipoy6cf.fsf@ruckus.brouhaha.com> <1183041149.275562.114490@o11g2000prd.googlegroups.com> <7xbqethpr8.fsf@ruckus.brouhaha.com> <468AD888.6A023A0E@yahoo.com> Message-ID: <87tzskoda6.fsf@benfinney.id.au> CBFalconer writes: > "Peter J. Holzer" wrote: > > Hardly. That hasn't been in use for over 35 years (according to > > Wikipedia). > > I am glad to see you depend on absolutely reliable sources. Wikipedia is not an absolutely reliable source. I know of no "absolutely resliable source". We work with imperfect human-provided data all the time. -- \ "If you ever teach a yodeling class, probably the hardest thing | `\ is to keep the students from just trying to yodel right off. | _o__) You see, we build to that." -- Jack Handey | Ben Finney From m at rtij.nl.invlalid Mon Jul 23 16:45:21 2007 From: m at rtij.nl.invlalid (Martijn Lievaart) Date: Mon, 23 Jul 2007 22:45:21 +0200 Subject: The Modernization of Emacs: exists already References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272678.877166.209640@j4g2000prf.googlegroups.com> <1184764620.778937.264760@m37g2000prh.googlegroups.com> Message-ID: On Wed, 18 Jul 2007 06:17:00 -0700, Xah Lee wrote: > About a month ago, i posted a message about modernization of emacs. I > enlisted several items that i think emacs should adapt. And you are posting this to compl.lang.perl because.....?????? F'up set. M4 From sturlamolden at yahoo.no Fri Jul 13 16:10:50 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 13 Jul 2007 13:10:50 -0700 Subject: Numpy array index handling In-Reply-To: <1184352981.493615.18040@k79g2000hse.googlegroups.com> References: <1184352981.493615.18040@k79g2000hse.googlegroups.com> Message-ID: <1184357450.172425.26480@n60g2000hse.googlegroups.com> >>> from numpy import * >>> from numpy.random import * >>> N = 1000000 >>> input = sign(randn(N)) >>> a = arange(N) >>> output = zeros(N) >>> output[input < 0] = 10 * a[input < 0] >>> output[input > 0] = 20 * a[input > 0] >>> Worked fine for me. S.M. From bbxx789_05ss at yahoo.com Mon Jul 2 14:19:05 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 02 Jul 2007 11:19:05 -0700 Subject: subprocess -- broken pipe error In-Reply-To: <1183397577.959518.264230@g4g2000hsf.googlegroups.com> References: <1183396350.429008.185200@n2g2000hse.googlegroups.com> <1183397577.959518.264230@g4g2000hsf.googlegroups.com> Message-ID: <1183400345.202323.133750@k29g2000hsd.googlegroups.com> On Jul 2, 11:32 am, "holden... at gmail.com" wrote: > On Jul 2, 1:12 pm, 7stud wrote: > > > > > Hi, > > > Can someone explain what a broken pipe is? The following produces a > > broken pipe error: > > > ---------- > > import subprocess as sub > > > p = sub.Popen(["ls", "-al", "../"], stdin=sub.PIPE, stdout=sub.PIPE) > > > print p.stdout.read() > > #outputs the files correctly > > > p.stdin.write("ls\n") > > #IOError: [Errno 32] Broken pipe > > ----------- > > You are seeing this error because sub.Popen closes both stdin and > stdout once the subprocess terminates (which it must have done for > p.stdout.read() to return a result). > > Consequently you are trying to write to a pipeline whose reader has > already closed it, hence the error message. > > regards > Steve Hi, Thanks for the response. So are you saying that the only way you can get data out of a pipe is when the subprocess has terminated? From kyosohma at gmail.com Tue Jul 3 09:16:43 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 03 Jul 2007 06:16:43 -0700 Subject: what is wrong with that r"\" In-Reply-To: References: Message-ID: <1183468603.714314.241430@n60g2000hse.googlegroups.com> On Jul 3, 7:15 am, alf wrote: > question without words: > > >>> r"\" > File "", line 1 > r"\" > ^ > SyntaxError: EOL while scanning single-quoted string > >>> r"\ " > '\\ ' One slash escapes the following character, so the proper way of writing it is either r"\\" or r"\"" See http://docs.python.org/ref/strings.html for more information. Mike From duncan.booth at invalid.invalid Mon Jul 2 16:24:23 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Jul 2007 20:24:23 GMT Subject: howto resend args and kwargs to other func? References: <1183279997.244378.105810@n60g2000hse.googlegroups.com> <1183282733.179683.174350@c77g2000hse.googlegroups.com> <5er6doF31bulkU1@mid.individual.net> Message-ID: Sion Arrowsmith wrote: > Frank Swarbrick wrote: >>dmitrey wrote: >>> Thanks all, I have solved the problem. >>Why do people do this without posting what the actual solution is!!!! > > Hey, if we're expected to magically deduce what the problem is > without being told an error messages, surely we can magically > deduce the discovered solution too? > Quite so. Meanwhile the OP is killfiled so can't expect any help from me in the future. From rts.cts at gmail.com Tue Jul 10 14:24:12 2007 From: rts.cts at gmail.com (Daryl) Date: Tue, 10 Jul 2007 18:24:12 -0000 Subject: C Extension Seg Faults In-Reply-To: <7x7ip8gm2d.fsf@ruckus.brouhaha.com> References: <1184090600.764290.160210@d30g2000prg.googlegroups.com> <7x7ip8gm2d.fsf@ruckus.brouhaha.com> Message-ID: <1184091852.235574.252560@z28g2000prd.googlegroups.com> > It's not worth staring at code to try to figure out things like that. > Run it under gdb, examine the relevant data objects when it crashes > and see what's broken (e.g. some pointer is unexpectedly null), then > set a conditional breakpoint that stops execution when that incorrect > condition happens (e.g. the pointer gets set to null), run the program > til the breakpoint triggers, see what other condition X caused the > condition that caused the crash, set another breakpoint that triggers > when X occurs, etc. Work backwards systematically til you find the bug. Yeah, not 30 seconds after I posted it I found the problem. Under some (funny) conditions the extension would be called with a list instead of a tuple. My debug case (of course) worked fine but the full test would fail. Sorry for the noise, -Daryl From jjl at pobox.com Sat Jul 14 08:54:26 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 14 Jul 2007 12:54:26 GMT Subject: Can a low-level programmer learn OOP? References: <4697d9f0$0$7614$426a74cc@news.free.fr> Message-ID: <87ps2vywl9.fsf@pobox.com> [Chris Carlen] > From what I've read of OOP, I don't get it. I have also found some > articles profoundly critical of OOP. I tend to relate to these > articles. If you want to know the truth, and opt to neither trust a friend or colleague, nor spend the time to try it yourself, here's a third way: Compile Qt (a toolkit like wx or Tk) and watch the list of source file names scroll past. Beautiful! Perhaps there's some better way of doing GUIs, but watching that list of source files, one realises that that's an academic question: practically, OOP fits GUIs -- and much of the other code in Qt -- so well, and so much effort has been put into these GUI toolkit libraries, that one would be a fool not to use them right now. A somewhat separate issue: You'd also be a fool not to apply OOP to the GUI code *you* write *using* one of those OOP GUI toolkits. Though you won't learn that all at once or without conscious effort, that's not an obstacle with Python -- you can start small. Of course there's some level of experience / project size / project longevity / number of people involved below which dashing it off using what you know right now will be quicker, but the break-even point is not far off in your case, I think. [chris] > However, those articles were no more objective than the descriptions > of OOP I've read in making a case. Ie., what objective > data/studies/research indicates that a particular problem can be > solved more quickly by the programmer, or that the solution is more > efficient in execution time/memory usage when implemented via OOP > vs. procedural programming? [bruno] > None. Definitively. wrt/ developper time and memory, it's mostly a > matter of fit-your-brains. If it does, you'll find it easier, else [...] How do we have confidence that that's true without doing experiments? AFAIK, only a few such experiments have been done (not counting research that does not meet basic standards of competence or is not peer-reviewed). I think some programming techniques are simply better than others for certain tasks, even when including the variation in people's abilities (but excluding the cost of people learning those techniques, which can of course be significant). Of course, measurement is tricky because of differences between programmers, but it's not impossible. John From timid.Gentoo at gmail.com Thu Jul 5 14:23:10 2007 From: timid.Gentoo at gmail.com (_spitFIRE) Date: Thu, 05 Jul 2007 18:23:10 -0000 Subject: SMTP server w/o using Twisted framework Message-ID: <1183659790.338100.199900@g4g2000hsf.googlegroups.com> Is it possible to run a SMTP server that sends mail to recipients using standard libraries, without using twisted framework, and also without using any relay server? From JHoover at fbi.gov Thu Jul 19 15:05:46 2007 From: JHoover at fbi.gov (Gordon Airporte) Date: Thu, 19 Jul 2007 15:05:46 -0400 Subject: A way to re-organize a list In-Reply-To: <1184857535.033057.49150@m3g2000hsh.googlegroups.com> References: <1184857535.033057.49150@m3g2000hsh.googlegroups.com> Message-ID: beginner wrote: > > 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: itertools.groupby has already been mentioned, but it has a very specific and complex behavior which may not be exactly what you need. I found this handy class: class groupby(dict): def __init__(self, seq, key=lambda x:x): for value in seq: k = key(value) self.setdefault(k, []).append(value) __iter__ = dict.iteritems which you would use like this: byfirst = groupby(l, lambda x: x[0]) print byfirst['A'] print byfirst['B'] bysecond = groupby(l, lambda x: x[1]) print bysecond['a'] print bysecond['b'] From irnyad at gmail.com Tue Jul 31 17:19:29 2007 From: irnyad at gmail.com (Jason Ward) Date: Tue, 31 Jul 2007 23:19:29 +0200 Subject: Nasm_with_C++_With_Python Message-ID: <1ea031080707311419g5d6433dcx159e96bc2bf689c1@mail.gmail.com> I am interested in writing a library in Nasm and calling it from python. Python can call C++ libraries. Nasm can be made into an inc file and can be included in C++. So I was wondering if this combination is possible or if there is a better way. If it can be done please explain how I can do this. -------------- next part -------------- An HTML attachment was scrubbed... URL: From aafshar at gmail.com Fri Jul 27 05:42:38 2007 From: aafshar at gmail.com (Ali) Date: Fri, 27 Jul 2007 09:42:38 -0000 Subject: Comparing Dictionaries In-Reply-To: References: Message-ID: <1185529358.128424.52450@19g2000hsx.googlegroups.com> On Jul 26, 10:18 pm, Kenneth Love wrote: > Hello, > > I am new to Python, but not programming. I would like to start my > Python career by developing programs according to the "best practices" > of the industry. Right now, that appears to be unit tests, patterns, > and source code control. I am not sure about "best", but one of my "favourite practices" is to not re-write code that other people have written, and have released under licenses that allow you to do anything with it. > So, I am trying to write a unit test for some code that reads a Windows > style INI file and stores the section, key, and values in a dictionary So, in the standard library: http://docs.python.org/lib/module-ConfigParser.html And if you want a more involved approach: http://www.voidspace.org.uk/python/configobj.html Ali From duncan.booth at invalid.invalid Wed Jul 4 07:47:33 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Jul 2007 11:47:33 GMT Subject: what is wrong with that r"\" References: Message-ID: Nick Craig-Wood wrote: > Does anyone know the justification for a)? Maybe we should remove it > in py3k? > I think at least part of the justification is that it keeps the grammar simple. The tokenising happens identically irrespective of any modifiers. The r modifier doesn't actually change the syntax of the string at all, just the interpretation of the token. If you changed this then the grammar would become slightly more complex. From exarkun at divmod.com Wed Jul 11 10:20:46 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 11 Jul 2007 10:20:46 -0400 Subject: Best architecture for proxy? In-Reply-To: <1184162418.341166.160580@n60g2000hse.googlegroups.com> Message-ID: <20070711142046.4947.1505782544.divmod.quotient.10454@ohm> On Wed, 11 Jul 2007 07:00:18 -0700, Andrew Warkentin wrote: >On Jul 10, 8:19 pm, Steve Holden wrote: >> Bjoern Schliessmann wrote: >> > Andrew Warkentin wrote: >> >> >> I am going to write a general-purpose modular proxy in Python. It >> >> will consist of a simple core and several modules for things like >> >> filtering and caching. I am not sure whether it is better to use >> >> multithreading, or to use an event-driven networking library like >> >> Twisted or Medusa/ Asyncore. Which would be the better >> >> architecture to use? >> >> > I'd definitely use an event-driven approach with Twisted. >> >> > Generally, multithreading is less performant than multiplexing. High >> > performance servers mostly use a combination of both, though. >> >> Converselt I'd recommend Medusa - not necessarily because it's "better", >> but becuase I know it better. There's also a nice general-purpose proxy >> program (though I'd be surprised if Twisted didn't also have one). >> >> >Would an event-driven proxy be able to handle multiple connections >with large numbers of possibly CPU-bound filters? I use The >Proxomitron (and would like to write my own proxy that can use the >same filter sets, but follows the Unix philosophy) and some of the >filters appear to be CPU-bound, because they cause The Proxomitron to >hog the CPU (although that might just be a Proxomitron design flaw or >something). Wouldn't CPU-bound filters only allow one connection to be >filtered at a time? On the Medusa site, it said that an event-driven >architecture only works for I/O-bound programs. > Handling all of your network traffic with a single OS thread doesn't necessarily mean that all of your filters need to run in the same thread (or even in the same process, or on the same computer). Typically, however, a filtering rule should only need to operate on a small number of bytes (almost always only a few kilobytes). Is it the case that handling even this amount of data incurs a significant CPU cost? If not, then there's probably nothing to worry about here, and you can do everything in a single thread. If it is the case, then you might want to keep around a thread pool (or process pool, or cluster) and push the filtering work to it, reserving the IO thread strictly for IO. This is still a win, since you end up with a constant number of processes vying for CPU time (and you can tune this to an ideal value given your available hardware), rather than one per connection. This translates directly into reduced context switch overhead. Jean-Paul From vp_rajan at yahoo.com Tue Jul 17 12:52:03 2007 From: vp_rajan at yahoo.com (vp_rajan at yahoo.com) Date: Tue, 17 Jul 2007 09:52:03 -0700 Subject: Hi friends see my webpage and open the weblinks in that page it consists of 1.latest antivirussoftware 2.library softwares 3.software projects 4.software cracks 5.download accelerator plus 6.mobile themes 7.mobile softwares(for nokia, samsung, sonyericsson) 8.mobile videos(.3gp) 9...........ALL SOFTWARES PROVIDED BY GOOGLE IN SEPERATE ICONS and many more useful.................. ....................................open it and make use of it www.freewebs.com/usefulsite Message-ID: <1184691123.238460.175500@d30g2000prg.googlegroups.com> Hi friends see my webpage and open the weblinks in that page it consists of 1.latest antivirussoftware 2.library softwares 3.software projects 4.software cracks 5.download accelerator plus 6.mobile themes 7.mobile softwares(for nokia,samsung,sonyericsson) 8.mobile videos(.3gp) 9...........ALL SOFTWARES PROVIDED BY GOOGLE IN SEPERATE ICONS and many more useful.................. ....................................open it and make use of it www.freewebs.com/usefulsite From seandavi at gmail.com Wed Jul 18 23:40:53 2007 From: seandavi at gmail.com (Sean Davis) Date: Thu, 19 Jul 2007 03:40:53 -0000 Subject: odbc module for python Message-ID: <1184816453.519242.187940@g12g2000prg.googlegroups.com> What are the alternatives for accessing an ODBC source from python (linux 64-bit, python 2.5)? It looks like mxODBC is the only one available? Thanks, Sean From andreengels at gmail.com Thu Jul 12 10:23:33 2007 From: andreengels at gmail.com (Andre Engels) Date: Thu, 12 Jul 2007 16:23:33 +0200 Subject: web page text extractor In-Reply-To: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> References: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> Message-ID: <6faf39c90707120723t8f8188chb131779e66eaf971@mail.gmail.com> 2007/7/12, kublai : > For a project, I need to develop a corpus of online news stories. I'm > looking for an application that, given the url of a web page, "copies" > the rendered text of the web page (not the source HTNL text), opens a > text editor (Notepad), and displays the copied text for the user to > examine and save into a text file. Graphics and sidebars to be > ignored. The examples I have come across are much too complex for me > to customize for this simple job. Can anyone lead me to the right > direction? def textonly(url): # Get the HTML source on url and give only the main text f = urllib2.urlopen(url) text = f.read() r = re.compile('\<[^\<\>]*\>') newtext = r.sub('',text) while newtext != text: text = newtext newtext = r.sub('',text) return text -- Andre Engels, andreengels at gmail.com ICQ: 6260644 -- Skype: a_engels From nagle at animats.com Tue Jul 3 12:36:52 2007 From: nagle at animats.com (John Nagle) Date: Tue, 03 Jul 2007 09:36:52 -0700 Subject: mysteries of urllib/urllib2 In-Reply-To: <1183470239.153444.244700@j4g2000prf.googlegroups.com> References: <1183470239.153444.244700@j4g2000prf.googlegroups.com> Message-ID: <6Quii.386$m%.42@newssvr17.news.prodigy.net> Adrian Smith wrote: > I'm trying to use urllib2 to download a page (I'd rather use urllib, > but I need to change the User-Agent header to look like a browser or > G**gle won't send it to me, the big meanies). The following (pinched > from Dive Into Python) seems to work perfectly in Idle, but falls at > the final hurdle when run as a cgi script - can anyone suggest > anything I may have overlooked? > > request = urllib2.Request(some_URL) > request.add_header('User-Agent', 'some_plausible_string') > opener = urllib2.build_opener() > data = opener.open(request).read() I doubt that's the problem here, but don't use a USER-AGENT string that ends in "m" without a preceding "m" when the USER-AGENT string is the last element of the header. Coyote Point load balancers will drop the packet. (Coyote Point uses regular expressions to parse HTTP headers, and I think somebody wrote "\m" where they meant "\n".) John Nagle From urbangabo at gmail.com Tue Jul 31 09:33:37 2007 From: urbangabo at gmail.com (Gabor Urban) Date: Tue, 31 Jul 2007 15:33:37 +0200 Subject: Simple question about logging module. Message-ID: Thx guys.... You gave me good ideas. At the moment I do not have time for it, but I would like to write a summary. Have fun -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten at uniqsys.com Mon Jul 30 10:40:15 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 30 Jul 2007 10:40:15 -0400 Subject: Detecting __future__ features In-Reply-To: References: <1185800016.950517.43240@g4g2000hsf.googlegroups.com> <5h68ggF3idk61U1@mid.uni-berlin.de> Message-ID: <1185806415.3415.8.camel@dot.uniqsys.com> On Mon, 2007-07-30 at 14:10 +0000, Neil Cerutti wrote: > On 2007-07-30, Diez B. Roggisch wrote: > > Making the switch between different parser-implementations on > > the fly isn't technically impossible - but really, really, > > really complicated. But then, if it's lameness sucks so much, > > you might wanna take a stab at it? > > I was considering the following specific quote: > > What if you are designing a module meant to be imported, and > used by other programs over which you have no control? You > can't use "from __future__ import" in your module." > > If that were true, I think it would indeed be lame. Of course, it > isn't true, right? Correct, the statement you're referring to is not true. See my earlier reply on this thread for details. -- Carsten Haese http://informixdb.sourceforge.net From http Fri Jul 20 04:28:09 2007 From: http (Paul Rubin) Date: 20 Jul 2007 01:28:09 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <468565a0$0$3686$426a74cc@news.free.fr> <7xvecumrte.fsf@ruckus.brouhaha.com> <1i13w96.kyyobph71qxrN%aleax@mac.com> <7xwsx63we6.fsf@ruckus.brouhaha.com> <878x9llv5x.fsf@benfinney.id.au> <5fovr8F3eglkfU1@mid.uni-berlin.de> <7x1wf8kc6l.fsf@ruckus.brouhaha.com> <5gb5u1F3fip9cU1@mid.uni-berlin.de> Message-ID: <7xr6n3pjhi.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > What does that buy you - where is "I'm crashed becaus I ran out of > memory trying to evade the seventh mig" better than "sorry, you will > be shot down because I'm not capable of processing more enemie > fighters - but hey, at least I'm still here to tell you!" Come on, this is real-time embedded software, not some Visual Basic app running in Windows. The internal table sizes etc. are chosen based on the amount of physical memory available, which has tended to be pretty small until maybe fairly recently. From jon at turnthepage.org Thu Jul 12 10:22:51 2007 From: jon at turnthepage.org (Jon Rosebaugh) Date: Thu, 12 Jul 2007 09:22:51 -0500 Subject: web page text extractor References: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> Message-ID: <2007071209225175249-jon@turnthepageorg> On 2007-07-12 04:42:25 -0500, kublai said: > For a project, I need to develop a corpus of online news stories. I'm > looking for an application that, given the url of a web page, "copies" > the rendered text of the web page (not the source HTNL text), opens a > text editor (Notepad), and displays the copied text for the user to > examine and save into a text file. Graphics and sidebars to be > ignored. The examples I have come across are much too complex for me > to customize for this simple job. Can anyone lead me to the right > direction? You may find BeautifulSoup or templatemaker to be of assistance: http://www.crummy.com/software/BeautifulSoup/ http://www.holovaty.com/blog/archive/2007/07/06/0128 From steve at holdenweb.com Mon Jul 16 08:53:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 16 Jul 2007 08:53:40 -0400 Subject: Implementaion of random.shuffle In-Reply-To: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> Message-ID: shabda raaj wrote: > I was going through the docs for module-random > And I came through this, > > * shuffle*( x[, random]) > > > Shuffle the sequence x in place. The optional argument random is a > 0-argument function returning a random float in [0.0, 1.0); by > default, this is the function random(). > > Note that for even rather small |len(x)|, the total number of > permutations of x is larger than the period of most random number > generators; this implies that most permutations of a long sequence > can never be generated. > > Why would we need to generate the total number of permutations for the > list while trying to shuffle it? Should not we just use a knuth shuffle > which > does not require us to generate the total number of permutations. As > long as len(x) is smaller than period of random number generator, a > permutation can be generated. > > A quick first draft of implemetation might be, > > import random > > def shuffle(list_): > for i in range(len(list_)): > j = random.randint(i, len(list_)-1) > list_[i], list_[j] = list_[j], list_[i] > if __name__ == '__main__': > a = range(100) > shuffle(a) > print a > > This is my first post to the list, I am not sure if this is the correct > place to ask these questions. Please advise if this is not the correct > place. > This is an excellent place to post the question. If it were to turn out that your concerns were genuine that you might end up posting a patch to the issue tracker and possibly then involving the developers. Until your suspicions are confirmed, however, let the developers get on with development. You, like all (or most) Python users, have the source of the standard library at your disposal. Had you looked at .../Lib/random.py you would have found that the implementation of shuffle() reads as follows: def shuffle(self, x, random=None, int=int): """x, random=random.random -> shuffle list x in place; return None. Optional arg random is a 0-argument function returning a random float in [0.0, 1.0); by default, the standard random.random. """ if random is None: random = self.random for i in reversed(xrange(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = int(random() * (i+1)) x[i], x[j] = x[j], x[i] So it would appear that the developers chose the Knuth algorithm (with a slight variation) for *their* implementation. Now you have to ask yourself whether your surmise is genuinely correct (in which case the documentation may contain a bug) or whether the documentation is indeed correct and you are in error. Note that there is no intent to generate all permutations of the list and then choose one (that would indeed be a sub-optimal solution). The documentation is only talking about whether the algorithm can in theory produce all possible permutations of all possible input lists. It's possible that the comment in the documentation is left over from an earlier version. What do you 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 thq at ahc.hrcoxmail.com Sat Jul 28 10:55:34 2007 From: thq at ahc.hrcoxmail.com (Obrien Benedict) Date: Sat, 28 Jul 2007 16:55:34 +0200 Subject: No subject Message-ID: <46AB58E6.6070700@infinito.it> -------------- next part -------------- A non-text attachment was scrubbed... Name: Message.pdf Type: application/pdf Size: 7133 bytes Desc: not available URL: From http Thu Jul 26 22:29:26 2007 From: http (Paul Rubin) Date: 26 Jul 2007 19:29:26 -0700 Subject: zip() function troubles References: <1185492336.850090.279190@b79g2000hse.googlegroups.com> <7xir86wx0p.fsf@ruckus.brouhaha.com> <1185499500.807041.60580@g4g2000hsf.googlegroups.com> <7xzm1ieils.fsf@ruckus.brouhaha.com> <1185502539.598349.159330@l70g2000hse.googlegroups.com> Message-ID: <7x3aza37g9.fsf@ruckus.brouhaha.com> Istvan Albert writes: > Now it takes over two minutes to do this: > > size = 10**7 > a = [ 0 ] * size > b = zip(a,a) OK, I'm getting similar results under 64 bit Pytnon 2.4.4c1 and also under 2.5. About 103 seconds for 10**7 and 26 seconds for 5*10**6. So it looks like zip is using quadratic time. I suggest entering a bug report. From bsneddon at yahoo.com Sun Jul 8 14:42:35 2007 From: bsneddon at yahoo.com (bsneddon) Date: Sun, 08 Jul 2007 11:42:35 -0700 Subject: Pretty Printing Like Tidy for HTML In-Reply-To: <1183917234.730744.123410@n60g2000hse.googlegroups.com> References: <1183833340.610662.197060@o11g2000prd.googlegroups.com> <87ejjjlz4p.fsf@pobox.com> <1183917234.730744.123410@n60g2000hse.googlegroups.com> Message-ID: <1183920155.987603.267730@22g2000hsm.googlegroups.com> On Jul 8, 1:53 pm, bsneddon wrote: > On Jul 8, 10:59 am, j... at pobox.com (John J. Lee) wrote: > > > > > David writes: > > > Is there a pretty printing utility for Python, something like Tidy for > > > HTML? > > > > That will change: > > > > xp=self.uleft[0]+percentx*(self.xwidth) > > > > To: > > > > xp = self.uleft[0] + percentx * (self.xwidth) > > > > And other formatting issues. > > > Googled and found these; no idea if they're any good (latter is > > commercial): > > >http://cheeseshop.python.org/pypi/PythonTidy/1.11 > > >http://python.softalizer.com/ > > > See also: > > >http://svn.python.org/view/python/trunk/Tools/scripts/reindent.py?vie... > > > John > > I did this useing the BeautifulSoup module. > Used it on XML created by msWord which had no formating was > all on one line. > > >>> import BeautifulSoup > >>> soupStr = open('c:/data/quotes.xml').read() > >>> soup = BeautifulSoup.BeautifulSoup(soupStr) > >>> pSoup = soup.prettify() > >>> outFile = open('c:/data/quotesTidy.xml','w') > >>> outFile.write(pSoup) > >>> outFile.close() Sorry, I answered the wrong question. You wanted to format code not HTML. From alanwilter at gmail.com Thu Jul 26 06:18:10 2007 From: alanwilter at gmail.com (Alan) Date: Thu, 26 Jul 2007 11:18:10 +0100 Subject: python static with Numeric Message-ID: Hi List! Does anyone here knows how to compile python with Numeric in a static way? Many thanks in advance. Cheers, Alan From steve at holdenweb.com Wed Jul 11 21:30:35 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 11 Jul 2007 21:30:35 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <5dveb4F360un0U1@mid.individual.net> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: Donn Cave wrote: > In article , > Steve Holden wrote: > >> Paul Rubin wrote: >>> Steven D'Aprano writes: >>>> As far as I can see, the only difference is that the list comp variable >>>> isn't explicitly created with a statement of the form "name = value". Why >>>> is that a problem? >>> I don't know that listcomp vars are worse problem than other vars; >>> however there is an easy workaround for the listcomp vars so I use it. >>> If there was a way to restrict the scope of other local vars (I gave >>> examples from other languages of how this can be done), I'd use that too. > > Someday we will look at "variables" like we look at goto. > How very functional. I believe some people naturally think in terms of state transformations and some in terms of functional evaluation. I am pretty firmly in the former camp myself, so variables are a natural repository for state to me. >> Maybe we just have different styles, and I naturally tend to write in >> smaller scopes than you do. > > I've wondered if programmers might differ a lot in how much they > dread errors, or how they react to different kinds of errors. > For example, do you feel a pang of remorse when your program > dies with a traceback - I mean, what a horrible way to die? > Do you resent the compiler's reprimands about your code errors, > or nagging about warnings? Maybe the language implementation's > job has as much to do with working around our feelings as anything > else. > That's an interesting point of view. I certainly don't take the somewhat anthropomorphic approach you describe above. My first response to any "error" message is to ask myself "what did I do wrong *now*?" - the very fact that we talk about "error messages" implies a point of view that's discouraging to new users: "you did something wrong, fix it and try again". I do think that most language implementations could spend more time, and more sympathetic thought, on creating messages that were less pejorative and more indicative of the required corrective actions. But after forty years programming I know myself well enough to understand that I am the most likely cause of incorrect results. It's always amusing to see a newbie appear on this list and suggest that there's a bug in some long-standing feature of the language. It's always a possibility, but the probability is pretty low. 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 Tue Jul 24 13:20:57 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Tue, 24 Jul 2007 10:20:57 -0700 Subject: code indentation In-Reply-To: References: Message-ID: <1185297657.186852.136950@k79g2000hse.googlegroups.com> On 24 srp, 05:20, "Gabriel Genellina" wrote: > En Mon, 23 Jul 2007 16:53:01 -0300, ...:::JA:::... > escribi?: > > > > >> If you are using the tokenize module as suggested some time ago, try to > >> analyze the token sequence you get using { } (or perhaps begin/end pairs > >> in your own language, that are easier to distinguish from a dictionary > >> display) and the sequence you get from the "real" python code. Then > >> write > >> a script to transform one into another: > > >> from tokenize import generate_tokens > >> from token import tok_name > > >from cStringIO import StringIO > > >> def analyze(source): > > > g = generate_tokens(StringIO(source).readline) > > > for toknum, tokval, _, _, _ in g: > > > print tok_name[toknum], repr(tokval) > > >> I think you basically will have to ignore INDENT, DEDENT, and replace > >> NAME+"begin" with INDENT, NAME+"end" with DEDENT. > > > So......how can I do this????????????? > > I will appreciate any help!!!!! > > Try with a simple example. Let's say you want to convert this: > > for x in range(10): > begin > print x > end > > into this: > > for x in range(10): > print x > > Using the analyze() function above, the former block (pseudo-python) gives > this sequence of tokens: > > NAME 'for' > NAME 'x' > NAME 'in' > NAME 'range' > OP '(' > NUMBER '10' > OP ')' > OP ':' > NEWLINE '\n' > NAME 'begin' > NEWLINE '\n' > NAME 'print' > NAME 'x' > NEWLINE '\n' > NAME 'end' > ENDMARKER '' > > The latter block ("real" python) gives this sequence: > > NAME 'for' > NAME 'x' > NAME 'in' > NAME 'range' > OP '(' > NUMBER '10' > OP ')' > OP ':' > NEWLINE '\n' > INDENT ' ' > NAME 'print' > NAME 'x' > DEDENT '' > ENDMARKER '' > > If you feed this token sequence into untokenize, in response you get a > source code equivalent to the "real" python example above. So, to convert > your "pseudo" python into the "real" python, it's enough to convert the > first token sequence into the second - and from that, you can reconstruct > the "real" python code. Converting from one sequence into the other is a > programming exercise and has nothing to do with the details of the > tokenize module, nor is very Python-specific - looking at both sequences > you should figure out how to convert one into the other. (Hint: a few > additional newlines are not important) > > It is even simpler than the example given in the tokenize documentation: > - which transforms > 3.1416 into Decimal("3.1416") by example. > > Once you get this simple case working, you may try what happens with this: > > for x in range(10): > begin > print x > end > > and this: > > for x in range(10): begin > print x > end > > and later this: > > for x in range(10): > begin > print x > end > > You are now using explicit begin/end pairs to group statements, so > indentation is no more significant. You may want to preprocess the > pseudo-python source, stripping any leading blanks, before using tokenize > - else you'll get indentation errors (which are bogus in your > pseudo-python dialect). > > Since this will be your own Python dialect, don't expect that someone else > will do the work for you - you'll have to do it yourself. But it's not too > dificult if you do the things in small steps. In case you get stuck at any > stage and have specific questions feel free to ask. > > -- > Gabriel Genellina Hello, Sorry, now I become very nuisance and stupid but please I really need this.Do you remember my topic "python changing keywords name" ,and do you remember example that you give me for translate keywords? Can you give me some example script of this? Please!!! PS: THANKS FOR YOUR TIME!!!!!!!!!! Regards, Vedran From nogradi at gmail.com Wed Jul 25 16:33:36 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 25 Jul 2007 22:33:36 +0200 Subject: first, second, etc line of text file In-Reply-To: <1185393628.573678.27040@k79g2000hse.googlegroups.com> References: <1185393628.573678.27040@k79g2000hse.googlegroups.com> Message-ID: <5f56302b0707251333s3464e81eva4daf19d4beb1b1a@mail.gmail.com> Thanks all! I think I will stick to my original method because the files can be quite large and without reading the whole file into memory probably enumerate( open( textfile ) ) is the only way to access an arbitrary Nth line. From steve at holdenweb.com Mon Jul 16 21:18:16 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 16 Jul 2007 21:18:16 -0400 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: <1184627293.763822.255220@g4g2000hsf.googlegroups.com> References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> <1184351416.166930.290710@k79g2000hse.googlegroups.com> <1184362323.476796.22570@w3g2000hsg.googlegroups.com> <1184627293.763822.255220@g4g2000hsf.googlegroups.com> Message-ID: mensanator at aol.com wrote: > On Jul 15, 4:37 pm, Steve Holden wrote: >> Wayne Brehaut wrote: >>> On Fri, 13 Jul 2007 14:32:03 -0700, "mensana... at aol.com" >> [...] >>> But I digress (but only because provoked!)... >>>>> [for purposes of this argument, at least] >>> This statement is the informal equivalent to saying "Define a base-1 >>> number system as...", as I noted above. If you'd noted this, and >>> understood it, or were willing to accept it whether or not you >>> understood it, you'd have saved us both some bother--but me more than >>> you I guess, so maybe you were just trolling? >> wwway to beat a response to a pulp. > > Crackpot math is the way to beat a response to a pulp? > > And why does the response need to be beaten to a pulp? > Well, having just seen your posted reply to the same message I'd have to acknowledge you as the expert at flogging dead horses. > Isn't the purpose of comp.lang.python to promote knowledge, > not ignorance? > About Python, specifically, yes. > When someone posts > > x = [] > for i in range(255): > x.append(i) > > are you being a troll when you point out this could be > done better using list comprehension? > Nope, but you don;t have to write a 3,500-word essay to do it. >> Sometimes it's easier and better for >> your blood pressure just to let someone else have the last word, however >> ill-informed > > What was ill-informed? That there's no base 1? > > >>> x = int('1111',1) > > Traceback (most recent call last): > File "", line 1, in > x = int('1111',1) > ValueError: int() base must be >= 2 and <= 36 > > Or that Roman numerals aren't equivalent to tallying? > >> or hostile. > > What hostility? > I was addressing someone else's expressed opinions of your contribution rather than my opinions of it. Anyway, I was trying to persuade someone to shorten his responses. Do I have to start on *you* 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 itkovian at gmail.com Tue Jul 10 07:53:12 2007 From: itkovian at gmail.com (itkovian) Date: Tue, 10 Jul 2007 04:53:12 -0700 Subject: xmlrpclib hangs execution In-Reply-To: References: <45AC0631.8080601@ctw.utwente.nl><465A9DC7.2010708@gmail.com> <465d9040$0$326$e4fe514c@news.xs4all.nl> <1182162228.246643.135210@u2g2000hsc.googlegroups.com> Message-ID: <1184068392.683491.48920@22g2000hsm.googlegroups.com> Arno, > Your patches solves the problem too. Thanks! > > One thing: if I use the unpatched xmlrpclib.py, the printed output of > xml calls look like: > > {'state': 0, 'str': 'Info_RT'} > > But if I use your patch, they look like: > > state0strInfo_RT > > I prefer the former, as it is easier to extract the info. Why did this > change with your patch? I've no idea, I'll look into this as soon as possible. Thanks for letting me know. I want to point you to another possible solution, which is using a derived transport class. I've posted this on my blog, see http://www.itkovian.net/base/transport-class-pythons-xml-rpc-lib I'm not sure if this might solve the problem you pointed out. -- Andy From steve at holdenweb.com Sun Jul 22 09:12:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 22 Jul 2007 09:12:21 -0400 Subject: problem with exec In-Reply-To: References: <1185099810.772825.284620@m3g2000hsh.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Sun, 22 Jul 2007 03:23:30 -0700, vedrandekovic wrote: > >> Thanks for everything previously, but just to I ask about code >> indentation,this with { and } doesn't >> employed, here is my example how can I solve this about code >> indentation: >> >>>>> n=90 >>>>> if n==90: >> {print "bok kjai ma'} >> File "", line 2 >> {print "bok kjai ma'} >> ^ >> SyntaxError: invalid syntax > > > Steve Holden was playing silly games. You can't use { } for indentation. > You have to use indentation. > I wasn't playing silly games at all, and I did prefix that part ofmy answer with "I'm afraid I don't understand this question". The OP is writing a program to "translate" a Python-like language that uses non-English keywords into Python. Since the application is transforming its input, it could transform braces into indentation. Of course *Python* doesn't use braces, but the question was how to write "pseudo-Python" without using indentation to indicate grouping. 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 Thu Jul 19 13:04:00 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 19 Jul 2007 17:04:00 GMT Subject: Copy List References: <-29831789359750479@unknownmsgid> <6a2ccd190707180544k4909ad3enc6a962917a26f43d@mail.gmail.com> <1184862114.094387.257580@i13g2000prf.googlegroups.com> Message-ID: <5g9js0F3eddssU1@mid.uni-berlin.de> On Thu, 19 Jul 2007 09:21:54 -0700, Falcolas wrote: > On Jul 18, 6:56 am, "Rustom Mody" wrote: >> This is shallow copy >> If you want deep copy then >> from copy import deepcopy > > What will a "deep copy" of a list give you that using the slice > notation will not? Well, a deep copy of course. ;-) In [6]: import copy In [7]: a = [[1, 2], [3, 4]] In [8]: b = a[:] In [9]: c = copy.deepcopy(a) In [10]: a[0][1] = 42 In [11]: a Out[11]: [[1, 42], [3, 4]] In [12]: b Out[12]: [[1, 42], [3, 4]] In [13]: c Out[13]: [[1, 2], [3, 4]] Ciao, Marc 'BlackJack' Rintsch From malaclypse2 at gmail.com Tue Jul 31 21:33:57 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 31 Jul 2007 21:33:57 -0400 Subject: Iteration over strings In-Reply-To: <46AFCB8C.9060800@jayloden.com> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> <46AF7A49.3040804@jayloden.com> <46AF8046.7090702@gmx.net> <496954360707311307y7d503b8eybd72795c8e699104@mail.gmail.com> <46AF9B2D.8040501@jayloden.com> <46AF9F55.20105@gmx.net> <46AFA1D9.1010707@gmx.net> <46AFCB8C.9060800@jayloden.com> Message-ID: <16651e80707311833x79dac1cfgda531809d473b2bc@mail.gmail.com> On 7/31/07, Jay Loden 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: You picked out two specific examples as being bad, so I thought I'd go take a look at them. They don't seem nearly as bad as you make them sound. The online docs for os.stat (http://docs.python.org/lib/os-file-dir.html) seem pretty complete, including examples. The docs for the socket module (http://docs.python.org/lib/module-socket.html) are fairly large too. I mean, the traditional socket textbook is still 'Unix Network Programming, Vol. 1', which weighs in at over a thousand pages, so I'm sure more could be said in the docs, but I'm not sure exactly how much. It does point you to the platform specific docs as useful resources for platform specific behavior, but that seems reasonable too, especially considering that it lays out exactly which docs you might want to look at. I haven't tried to implement anything using these docs, so I don't know I'm not saying that the docs couldn't use improvement, I'm sure more details and more examples are always welcome. Still, these particular bits just don't seem that bad. -- Jerry From tom.and at tiscalinet.it Sat Jul 28 07:29:38 2007 From: tom.and at tiscalinet.it (Andrea Tomadin) Date: Sat, 28 Jul 2007 13:29:38 +0200 Subject: interpreter in the background Message-ID: <51D13D69-EEA7-42B3-B05D-B18716F6F24D@tiscalinet.it> Hi, I need to use the Python interpreter as if it were a Matlab or Mathematica "kernel", i.e. running in the background while I use an interface program to send commands and get output. Ideally, I would pipe some text "to" the interpreter (through a fifo, a socket...?) and got all the output back to the calling program, or appended to a text file, etc. Say: # cat pythonInput.txt 1 + 1 # cat pythonInput.txt | myInterface > pythonOutput.txt # cat pythonOutput.txt 2 or similar. Note that I need the *same* interpreter to run between consecutive calls of myInterface, to preserve the memory stack. Moreover, if I run a python script in the background, and not the bare interpreter, an input error could force the termination of the program, while I want the background "kernel" to keep up running. At first I thought it was a trivial task, just change default input and output instead of tty, but I could not find out a solution! Any help or hint is greatly appreciated! Best, Andrea -------------- next part -------------- A non-text attachment was scrubbed... Name: smime.p7s Type: application/pkcs7-signature Size: 2425 bytes Desc: not available URL: From bscrivener42 at gmail.com Tue Jul 24 07:56:56 2007 From: bscrivener42 at gmail.com (BartlebyScrivener) Date: Tue, 24 Jul 2007 11:56:56 -0000 Subject: how to get next month string? In-Reply-To: References: Message-ID: <1185278216.225757.195290@d55g2000hsg.googlegroups.com> On Jul 24, 5:31 am, "Yinghe Chen" wrote: > Hi, > Could someone help on how to use python to output the next month string like > this? > > "AUG07", suppose now is July 2007. > I usually find time and date answers somewhere in here: http://pleac.sourceforge.net/pleac_python/datesandtimes.html rd From Bulkan at gmail.com Mon Jul 9 21:40:04 2007 From: Bulkan at gmail.com (placid) Date: Tue, 10 Jul 2007 01:40:04 -0000 Subject: path backslash escaping trouble Message-ID: <1184031604.157526.45120@c77g2000hse.googlegroups.com> Hi All, I have these files; which are Merge Request (ClearCase) files that are created by a Perl CGI script (being re-written in Python, as the HTML/ JavaScript have been mixed with Perl, maintainability is zero) MergeType::::codefromlabel:::: BLname::::BUILDMODS:::: OldLname:::::::: BaseVersion::::6.9.1.24A:::: RequiredRelease::::6.10.1.3:::: Description:::::::: FixRelation:::::::: Dependencies:::::::: LpAffected::::No:::: CodeReview::::FirstName LastName:::: Testing::::Compile/Build;Designer;Smoketests;:::: OtherTesting:::::::: Vobs::::ipsupport;:::: Elements::::\ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3:::: i read this whole file into a string so i can search for the value of Elements which is \ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3 but this path is escaped \\ipsupport\\ipbuild\\Wizard\\build.pl@@\\main\\buildmods\\3 so when i try to escape a string containing that same path using any of the os.path escaping methods doesnt result in the correct escaped path. It either appends "C:\\" in front of the string with all the backslashes escaped or it converts the three(3) at then end to "x03" and a match doesnt occur! My question is, is there a function in Python that only escapes backslashes? Cheers From gentoodev at gmail.com Sun Jul 8 21:39:43 2007 From: gentoodev at gmail.com (Rob Cakebread) Date: Sun, 08 Jul 2007 18:39:43 -0700 Subject: Tool for finding external dependencies Message-ID: <1183945183.147231.120180@z28g2000prd.googlegroups.com> Hi, I need to find external dependencies for modules (not Python standard library imports). Currently I use pylint and manually scan the output, which is very nice, or use pylint's --ext-import-graph option to create a .dot file and extract the info from it, but either way can take a very long time. I'm aware of Python's modulefinder.py, but it doesn't find external dependencies (or at least I don't know how to make it do them). Thanks, Rob From will at willNOmcguganSPAM.com Mon Jul 9 08:57:02 2007 From: will at willNOmcguganSPAM.com (Will McGugan) Date: Mon, 09 Jul 2007 13:57:02 +0100 Subject: Per thread data Message-ID: <469230a0$0$5856$da0feed9@news.zen.co.uk> Hi, Is there a canonical way of storing per-thread data in Python? Will McGugan From gh at gregor-horvath.com Fri Jul 6 01:50:02 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Fri, 06 Jul 2007 07:50:02 +0200 Subject: The best platform and editor for Python In-Reply-To: <1183670009.035673.256680@w5g2000hsg.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183646799.400176.144570@k79g2000hse.googlegroups.com> <1183655933.475488.157270@m36g2000hse.googlegroups.com> <1183670009.035673.256680@w5g2000hsg.googlegroups.com> Message-ID: <6660e$468dd80a$547078de$16129@news.chello.at> Kay Schluehr schrieb: > The problem is simply that the Python community has failed in this > respect. There are many platform dependent and ideology driven ways to > do deal with code editing / debugging but not actually a recommend or > "pythonic" way. Other than Smalltalk, Python has not created an own Again, that's how Open Source or a Toolkit driven development (Unixy) works. For every problem there are 5 solutions. One size does not fit all. It's no fault that for example Linux Distributions do not have only one GUI but a lot of them. It's a great fortune. Gregor From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jul 16 10:54:18 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 16 Jul 2007 16:54:18 +0200 Subject: Private functions and inheritance References: <1184596318.146981.242830@n60g2000hse.googlegroups.com> Message-ID: <5g1f4rF3f0hneU1@mid.individual.net> Maciej Blizi?ski wrote: > calling B::call_bar(): B::bar() > calling B::call___bar(): A::__bar() (BTW, there is no :: operator in Python. It should be, e. g., B.bar().) > In the latter case, it calls the base class' implementation. It > probably goes along with Python's spec, but I found it surprising. __-prepended names are dynamically mangled to include the class name. Hence, B.__bar doesn't overwrite A.__bar in B. > I don't want to expose the __bar() function outside, In principle, you do. Always. Public or Private is just convention in Python. Even __-prepended names can be accessed from outside. Couldn't find it in the docs though. Quite inconcise. Regards, Bj?rn -- BOFH excuse #120: we just switched to FDDI. From torriem at chem.byu.edu Thu Jul 26 16:16:16 2007 From: torriem at chem.byu.edu (Michael L Torrie) Date: Thu, 26 Jul 2007 14:16:16 -0600 Subject: code indentation In-Reply-To: <1185478366.910475.110490@19g2000hsx.googlegroups.com> References: <1185297657.186852.136950@k79g2000hse.googlegroups.com> <87lkd5jt83.fsf@benfinney.id.au> <1185357861.989194.117000@r34g2000hsd.googlegroups.com> <1185387723.155661.311510@b79g2000hse.googlegroups.com> <1185478366.910475.110490@19g2000hsx.googlegroups.com> Message-ID: <46A90110.4000406@chem.byu.edu> vedrandekovic at v-programs.com wrote: > > .....so maybe if you can help me with this? If I understand you correctly, you're trying to make a "pretty-printer" in python, right? Something that will take arbitrary python source code, recognize the blocks and so forth, and then emit clean python code (text) with tabs for indents instead of spaces? > > Regards, > > Vedran > > (http://www.v-programs.com) > From the.mindstorm.mailinglist at gmail.com Wed Jul 4 19:17:33 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Wed, 04 Jul 2007 16:17:33 -0700 Subject: MethodType/FunctionType and decorators In-Reply-To: <1183589529.198694.109440@m36g2000hse.googlegroups.com> References: <1183589529.198694.109440@m36g2000hse.googlegroups.com> Message-ID: <1183591053.434640.119550@o61g2000hsh.googlegroups.com> On Jul 5, 1:52 am, Alex Popescu wrote: > Hi all! > > I am pretty new to Python, so please excuse me if I am missing > something. Lately, I've been playing with decorators and I am a bit > confused about some behavior. Here is the code that puzzles me: > > in python shell: > > def function(): > pass > > class A(object): > def method(self): > pass > > from types import MethodType > from types import FunctionType > > if type(function) is FunctionType: > print "this is what I expect" > > if type(A.method) is MethodType: > print "this is what I expect" > > so far so good... everything seems logical. > > But if a decorator is declared things are becoming different: > > def deco(function): > if type(function) is MethodType: > print "MethodType" > elif type(function) is FunctionType: > print "FunctionType" > > @deco > def function2(): > pass > > # ==> this prints out FunctionType (oke) > > class A(object): > @deco > def method(self): > pass > > # ==> this prints out FunctionType (???) > > Can somebody shed some light on why I am seeing this? > > (Using Python 2.5.1 on Win XP). > > TIA, > > ./alex > -- > .w( the_mindstorm )p. First of all I should correct my example to use isinstance(function_or_method, builtin_factory_function). Secondly, I guess what is happening is the following: - when testing from outside the class definition, the function is already attached to the class instance and this is the reason why its type is instancemethod - for decorators, my test is executed before the class is defined and so at that moment the function is still a function; it will become a methodinstance only after the class definition is closed Is this correct or am I just fabulating here? TIA, ./alex -- .w( the_mindstorm )p. From arkanes at gmail.com Thu Jul 5 12:42:41 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 5 Jul 2007 11:42:41 -0500 Subject: Where is the syntax for the dict() constructor ?! In-Reply-To: <468D1D9D.6060002@gmail.com> References: <468D1D9D.6060002@gmail.com> Message-ID: <4866bea60707050942p3a3f23f0ge3ff170283dc4ada@mail.gmail.com> On 7/5/07, Captain Poutine wrote: > I'm simply trying to read a CSV into a dictionary. > > (if it matters, it's ZIP codes and time zones, i.e., > 35983,CT > 39161,CT > 47240,EST > > > > Apparently the way to do this is: > > import csv > > dictZipZones = {} > > reader = csv.reader(open("some.csv", "rb")) > for row in reader: > # Add the row to the dictionary > > > But how to do this? > > Apparently there is no dict.append() nor dict.add() > > But what is there? I see vague references to "the dict() constructor" > and some examples, and news that it has been recently improved. But > where is the full, current documentation for the dict() constructor? > There's no dict.append or dict.add because a dict doesn't require them. You insert keys via the normal indexing interface: somedict[somekey] = somevalue. Depending on which direction your mapping is, you may be interested in the setdefault method. The dict constructor is described in section 2.1, built in functions (even though it's not a function anymore). The other dict methods are described in section 3.8, mapping types. From mattheww at chiark.greenend.org.uk Thu Jul 12 15:40:13 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 12 Jul 2007 20:40:13 +0100 (BST) Subject: profiling a C++ python extension References: <1184113272.962640.41240@22g2000hsm.googlegroups.com> Message-ID: rasmus wrote: > I have used gprof to profile stand alone C++ programs. I am also > aware of pure python profilers. However, is there a way to get > profile information on my C++ functions when they are compiled in a > shared library (python extension module) and called from python. > Any suggestions or tips would be helpful. You didn't say what platform you're using. If you're using linux and have root access, oprofile should be able to do what you need. -M- From max at alcyone.com Tue Jul 10 03:05:49 2007 From: max at alcyone.com (Erik Max Francis) Date: Tue, 10 Jul 2007 00:05:49 -0700 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: References: Message-ID: Jim Langston wrote: > Gah! Python goes right to left? Dang, I haven't seen that since APL. For the ** operator, and with good reason: Left-associative ** doesn't really serve much useful purpose, since (a**b)**c == a**(b*c), so if one writes a**b**c, one usually means a**(b**c), or they would have written it more efficiently and clearly. -- 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 Men with empires in their purpose / And new eras in their brains -- Lamya From Xin.Zheng at jpl.nasa.gov Wed Jul 11 13:43:44 2007 From: Xin.Zheng at jpl.nasa.gov (Jason Zheng) Date: Wed, 11 Jul 2007 10:43:44 -0700 Subject: os.wait() losing child? In-Reply-To: <4694903B.8000105@cosc.canterbury.ac.nz> References: <4694903B.8000105@cosc.canterbury.ac.nz> Message-ID: <469516D0.3030507@jpl.nasa.gov> Greg, That explains it! Thanks a lot for your help. I guess this is something they do to prevent zombie threads? ~Jason greg wrote: > Jason Zheng wrote: >> Hate to reply to my own thread, but this is the working program that >> can demonstrate what I posted earlier: > > I've figured out what's going on. The Popen class has a > __del__ method which does a non-blocking wait of its own. > So you need to keep the Popen instance for each subprocess > alive until your wait call has cleaned it up. > > The following version seems to work okay. > > import os > from subprocess import Popen > > pids = {} > counts = [0,0,0] > p = [None, None, None] > > for i in xrange(3): > p[i] = Popen('sleep 1', shell=True) > pids[p[i].pid] = i > print "Starting child process %d (%d)" % (i,p[i].pid) > > while (True): > (pid,exitstat) = os.wait() > i = pids[pid] > del pids[pid] > counts[i]=counts[i]+1 > > #terminate if count>10 > if (counts[i]==10): > print "Child Process %d terminated." % i > if reduce(lambda x,y: x and (y>=10), counts): > break > continue > > print "Child Process %d (%d) terminated, restarting" % (i, pid), > p[i] = Popen('sleep 1', shell=True) > pids[p[i].pid] = i > print "(%d)" % p[i].pid > > -- > Greg From vriolk at gmail.com Mon Jul 16 19:09:16 2007 From: vriolk at gmail.com (coldpizza) Date: Mon, 16 Jul 2007 16:09:16 -0700 Subject: sqlite3 db update extremely slow In-Reply-To: References: <1184613750.873464.312390@r34g2000hsd.googlegroups.com> Message-ID: <1184627356.324577.257470@g4g2000hsf.googlegroups.com> Thanks a lot, Roel, adding a single commit() at the end did solve the speed problem. Another question is do I have to explicitly close the DB connection, or is it automatically garbage collected? Is it Ok to no have any cleanup code? Another question would be how to define the encoding for newly added records? And how do set the encoding for the retrieved records? Is it always utf-8 by default? On Jul 16, 11:21 pm, Roel Schroeven wrote: > coldpizza schreef: > > > I am trying to fill a sqlite3 database with records, and to this end I > > have written a class that creates the db, the table and adds rows to > > the table. > > > The problem is that the updating process is *extremely* slow, and > > occasionally I get the message "database locked". > > > I tried removing "self.con.commit()" in the add_record method, but > > then nothing is saved in the db. I don't know whether this has > > anything to do with it, but I have found no option to enable > > autocommit. > > Remove self.con.commit() from add_record(), and do it once after all > records are added. > > The reason that the process is slow with a commit after every INSERT is > that sqlite syncs the inserted data to disk before it continues. > > -- > If I have been able to see further, it was only because I stood > on the shoulders of giants. -- Isaac Newton > > Roel Schroeven From deets at nospam.web.de Mon Jul 23 11:24:34 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 23 Jul 2007 17:24:34 +0200 Subject: decorators tutorials References: <1185178383.499234.299850@z24g2000prh.googlegroups.com> <1185180112.321457.73170@n2g2000hse.googlegroups.com> <1185183257.471106.318070@x35g2000prf.googlegroups.com> <46a48245$0$19544$426a34cc@news.free.fr> <1185192282.331334.213730@x35g2000prf.googlegroups.com> Message-ID: <5gjvhiF3gm5ppU1@mid.uni-berlin.de> james_027 wrote: > hi bruno, > > That seems to be hard to read at all, or I am just very new to python? > > With that decorator how do I take advantage of it compare when I just > write a function that could do the same as what the decorator did? I > could translate the could from above into ... > > def check_login(msg): > #... > def my_func(toto, tata): > #... > > #call it like this > check_login('msg') > my_func('toto', 'tata') A decorator can alter the function _in place_ - it is not neccessary to alter code that calls my_func, as your example does. As an additional benefit, it separates concerns - my_func does some stuff, but mixing it with login-related logic is cumbersome: def my_func(parameters): if not logged_in(): do some redirection do_the_real_work() is much more error-prone than @check_login def my_func(parameters): do_the_real_work() because then you can just skim the decorator and concentrate on the actual code. What one often reaches with decorators is something referred to as "aspect orientied programming". Diez From aidechamp at yahoo.it Tue Jul 10 05:12:12 2007 From: aidechamp at yahoo.it (aidechamp at yahoo.it) Date: Tue, 10 Jul 2007 02:12:12 -0700 Subject: Get a filename list of a web site Message-ID: <1184058732.163303.96300@q75g2000hsh.googlegroups.com> Hi all, is it possible to get a filename directory list of a website (possibly with full path indication)? Using python & possibly wget? Bye. From nospam-abuse at ilyaz.org Thu Jul 12 00:15:26 2007 From: nospam-abuse at ilyaz.org (Ilya Zakharevich) Date: Thu, 12 Jul 2007 04:15:26 +0000 (UTC) Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: [A complimentary Cc of this posting was sent to Martin Gregorie ], who wrote in article : > Ilya Zakharevich wrote: > > My point is that attributing something to SH due to it appearing in > > ABHoT is like attributing it to you since it was mentioned in your > > post... > OK, so who should it be attributed to? *This* was my question; and with kitchentop book, one cannot expect to find such an answer. If interested, Wiki looks like a good place to look it up. Given how obsolete this conjecture is (it contradicts the now known data about uniformity of background radiation), I have no interest in looking it up. :-( Sorry, Ilya From samwyse at gmail.com Thu Jul 12 07:55:09 2007 From: samwyse at gmail.com (samwyse) Date: Thu, 12 Jul 2007 11:55:09 -0000 Subject: allow scripts to use .pth files? In-Reply-To: <1183928022.719873.49470@i38g2000prf.googlegroups.com> References: <1183899193.766331.13210@22g2000hsm.googlegroups.com> <1183928022.719873.49470@i38g2000prf.googlegroups.com> Message-ID: <1184241309.629557.226820@w3g2000hsg.googlegroups.com> On Jul 8, 3:53 pm, John Machin wrote: > I got the impression that the OP was suggesting that the interpreter > look in the directory in which it found the script. [...] > I got the impression that the problem was that the package was not > only not on sys.path but also not in the same directory as the script > that wanted to import it. Otherwise the OP's script.p?h file need only > contain ".\n" (or the path to the directory in which it resided!!), > and I doubt that he was proposing something so silly. And as I'm sure you realize, those two impression slightly contradict each other. Anyway, a small modification to my second approach would also work in the case looking for packages in a directory that's located somewhere relative to the one where the script was found: if __name__ == '__main__': import sys, os.path base = sys.path[0] for d in 'lib', 'modules': d2 = os.path.join(base, d) if os.path.isdir(d2): sys.path.append(d2) base = os.path.join(base, '..') for d in 'modules', 'lib': d2 = os.path.join(base, d) if os.path.isdir(d2): sys.path.append(d2) # for debugging print repr(sys.path) (BTW, this is such a fun script to type. My fingers keep typing 'os.path' where I mean 'sys.path' and vice versa.) From ladynikon at gmail.com Fri Jul 27 10:08:47 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Fri, 27 Jul 2007 10:08:47 -0400 Subject: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> <1185467914.814174.94600@22g2000hsm.googlegroups.com> Message-ID: <59f9c5160707270708m52769fc8ofdc16099c85fddb6@mail.gmail.com> Brad Wrote: In my experience, things have not changed at most PolySci Universities (Georgia Tech, NC State, Virginia Tech, etc). The Comp Engineering/CS/Math classes are still full of boys. Although there are some girls, but not a lot. If a girl is in the class (and that's a big if) no boy in the classs can focus. She distorts the atmosphere of the entire room (in a good way). She's like a giant, shiny, spherical magnet close to a lot of little, ordinary metal shards. Maybe if the boys got out more often. They wouldn't blame a girl for distracting them. Yes we are small in number in the computer world. But as the trend that a womans life is in the home. Woman are seeing that there is more and desiring more. I for one never saw computers as a "big boys" world. From python at jayloden.com Sat Jul 28 14:13:48 2007 From: python at jayloden.com (Jay Loden) Date: Sat, 28 Jul 2007 14:13:48 -0400 Subject: How to write a warning to my log file? In-Reply-To: <1185643331.804498.251550@g4g2000hsf.googlegroups.com> References: <1185643331.804498.251550@g4g2000hsf.googlegroups.com> Message-ID: <46AB875C.5000208@jayloden.com> MarkyMarc wrote: > Hi All, > > A small newbie Q. > > I have made a nice log function in me program. The program writes some > data to me mysql database. > When I write to the database I get som warnings back. > > Have do I write these to me log file? > I know I have to use the the warnings api. But I can not figure out > how to use it. > Is there anyone take might give me a small example. > > THX all :-) It looks like what you need to do is override the warnings module's showwarning function: showwarning(message, category, filename, lineno[, file]) Write a warning to a file. The default implementation calls formatwarning(message, category, filename, lineno) and writes the resulting string to file, which defaults to sys.stderr. You may replace this function with an alternative implementation by assigning to warnings.showwarning. Example: #!/usr/bin/python import warnings def mywarn(message, category, filename, lineno, file="warnings.log"): handle = open(file, 'a') handle.write(warnings.formatwarning(message, category, filename, lineno)) handle.close() warnings.showwarning = mywarn #now test it warnings.warn('test warn message') -Jay From duncan.booth at invalid.invalid Tue Jul 10 03:20:02 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Jul 2007 07:20:02 GMT Subject: What is the most efficient way to test for False in a list? References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <7x7ipajvst.fsf@ruckus.brouhaha.com> <5fejp2F3cp3igU1@mid.individual.net> <5feju0F3c7pd1U1@mid.uni-berlin.de> <7xsl7xmxcl.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Diez B. Roggisch" writes: >> >> status = all(list) >> > >> > Am I mistaken, or is this no identity test for False at all? >> >> You are mistaken. all take an iterable and returns if each value of >> it is true. > > all(list) does what the OP's code did, tests for the presence of a > false value in the list. If you want an identity test, use > > status = not (False in list) That is an equality test, not an identity test: >>> False in [0] True as others have said, if you need an identity test use: any(x is False for x in theList) From duncan.booth at invalid.invalid Fri Jul 27 08:16:21 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Jul 2007 12:16:21 GMT Subject: Why is "for line in f" faster than readline() References: <1185473637.817954.129660@o61g2000hsh.googlegroups.com> Message-ID: Alexandre Ferrieux wrote: > Now, *why* is such buffering gaining speed over stdio's fgets(), which > already does input buffering (though in a more subtle way, which makes > it still usable with pipes etc.) ? > Because the C runtime library has different constraints than Python's file iterator. In particular the stdio fgets() must not read ahead (because the stream might not be seekable), so it is usually just implemented as a series of calls to read one character at a time until it has sufficient characters. That inevitably has a lot more overhead than reading one 8k buffer and subsequently splitting it up into lines. It would probably be possible to do an implementation of fgets which looked at the underlying stream and used buffering and seeking when the stream was seekable and the cautious approach otherwise, but that isn't what is usually done, and the incentive to do it isn't there: fgets() exists and works as advertised even if it isn't very efficient. Anyone worried about speed won't use it anyway, so improving it on specific platforms wouldn't really help. A lot of the C runtime is like that: it needs to be robust in a very general purpose environment, but it doesn't need to be efficient. If you are worried about efficiency then you should look elsewhere. From wbrehaut at mcsnet.ca Mon Jul 16 13:51:02 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Mon, 16 Jul 2007 11:51:02 -0600 Subject: 2**2**2**2**2 wrong? Bug? References: <1184050285.997766.299860@d55g2000hsg.googlegroups.com> <1184351416.166930.290710@k79g2000hse.googlegroups.com> <1184362323.476796.22570@w3g2000hsg.googlegroups.com> <746l93p0mkhljcuc7qsdk7pl908qnpenni@4ax.com> Message-ID: On Mon, 16 Jul 2007 08:51:31 +0200, "Hendrik van Rooyen" wrote: > "Wayne Brehaut" wrote: > >> On Sun, 15 Jul 2007 17:37:13 -0400, Steve Holden >> wrote: >> >> >Wayne Brehaut wrote: >> >> On Fri, 13 Jul 2007 14:32:03 -0700, "mensanator at aol.com" > >8< ------------------------------------------------------------------------- > >> Also, I tend to follow the general Evolutionarily Stable Strategy >> generally called "Retaliator". In the simple game of Hawk vs. Dove a >> Hawk always attacks and defends to the death, whereas a Dove always >> runs. A mixed strategy would be to sometimes attack-and-defend and >> sometimes run, and a special case is to always run except when you're >> attacked--then defend to the death; i.e., behave like a Dove to a Dove >> and like a Hawk to a Hawk. >> >> In Game Theory, if not in practice, Retaliator is dominant over both >> pure Hawk and pure Dove, partly because some who present like Hawks >> are actually Bullies--who behave like Hawks until an opponent defends, >> then behave like Doves. > >*grin* - you realise of course, that this stated strategy leaves you wide >open to trolls of the "Lets see what we can provoke him into responding" >kind - from people whose sense of humour is either subtle, or evil... > >- Hendrik Subtle is good and generally easy enough to spot ("Never kid a kidder!"). As for evil, no problem--I'm also a bit of an Equivocator (perhaps even Prevaricator), and probably won't bother to respond to anyone who seems to be a waste of time or is beyond redemption. I seldom use a kill filter though since I'm too curious about what they're going to say next, but can just read and suffer silently when I choose to! And thanks for the sage advice! wwwayne From star.public at gmail.com Wed Jul 25 13:47:47 2007 From: star.public at gmail.com (star.public at gmail.com) Date: Wed, 25 Jul 2007 17:47:47 -0000 Subject: From D In-Reply-To: <1185384166.503862.236170@d55g2000hsg.googlegroups.com> References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> Message-ID: <1185385667.562090.252300@b79g2000hse.googlegroups.com> On Jul 25, 1:22 pm, "mensana... at aol.com" wrote: > > So, spaces will no longer be delimiters? Won't that cause > much wailing and gnashing of teeth? > I can't think of a circumstance in which 48 1906 is valid, so . . . I like it, too :) -- Star Weaver From deets at nospam.web.de Mon Jul 16 11:23:39 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 16 Jul 2007 17:23:39 +0200 Subject: how to read python-doc in ubuntu? References: Message-ID: <5g1grrF3ekaguU1@mid.uni-berlin.de> ZelluX wrote: > Hi all, > I'm a new comer to Python. > I've installed python-doc module, but just don't know how to open it. > Could you help me? > > Many thanks ^_^ dpkg -L will list the contents of the package at question. Doc packages usually reside under /usr/shar/doc/ diez From mikeyp at snaplogic.org Thu Jul 19 02:01:01 2007 From: mikeyp at snaplogic.org (Michael Pittaro) Date: Wed, 18 Jul 2007 23:01:01 -0700 Subject: Python related activities at OSCon 2007 next week Message-ID: <469EFE1D.7030506@snaplogic.org> I've been getting ready for OSCon 2007 next week, and theres quite a bit of Python related activity there. Based on a suggestion from Jeff Rush, (who can't be there), I've proposed a Python Advocacy BoF on Monday, from 6:30pm - 7:30pm. For anyone arriving early, this will be a great opportunity to coordinate Python advocacy activites at OSCon. Theres also a regular Python BoF on Wednesday from 8:30pm - 9:30pm. Apart from those, I've tagged [1] a bunch of sessions I felt were Python related. This list includes sessions outside the main Python track. [1] see: http://blog.snaplogic.org/?p=61 or http://del.icio.us/mikeyp/oscon2007%2Boscon_python -- mikeyp at snaplogic.org http://www.snaplogic.org From mojocojo2000 at gmail.com Tue Jul 24 02:31:57 2007 From: mojocojo2000 at gmail.com (mojocojo2000 at gmail.com) Date: Tue, 24 Jul 2007 06:31:57 -0000 Subject: wxPython Internationalization Message-ID: <1185258717.905849.20330@q75g2000hsh.googlegroups.com> I know this may have a very simple answer, nonetheless. I am wishing to find the cleanest and most pythonic way of implementing the following: I am creating a internationalized application in wxPython and have sorted the directory structure in the following manner: start.py metamenus.py main.py [various files] [various files] Here's the code for the files shown above: # start.py if __name__ == '__main__': import .main app = .MyApp(0) app.MainLoop() # main.py import wx from metamenus import MenuBarEx class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(380, 250)) menu = \ [[ [_('&File')], [_('Open a new document')], [_('Save the document')] ], [ [_('&Edit')] ], [ [_('&View')] ], [ [_('&Quit\tCtrl+Q')], [_('Quit the Application')], [_('&Help')] ]] self.mainmenu = MenuBarEx(self, menu) def OnQuit(self, event): self.Close() class MyApp(wx.App): def OnInit(self): self.frame = MyFrame(None, -1, 'Title') self.frame.Raise() self.frame.Refresh() self.frame.Show(True) return True So here's my question. I wish to add the following code so that the _ method will become of use. Here is the code http://wiki.wxpython.org/Internationalization recommends: import wx import os import platform import codecs import sys import gettext def main(): # initialise language settings: path = sys.path[0].decode(sys.getfilesystemencoding()) try: langIni = codecs.open(os.path.join(path,u'language.ini'),'r', 'utf-8') except IOError: language = u'en' #defaults to english pass else: language = langIni.read() locales = { u'en' : (wx.LANGUAGE_ENGLISH, u'en_US.UTF-8'), u'es' : (wx.LANGUAGE_SPANISH, u'es_ES.UTF-8'), u'fr' : (wx.LANGUAGE_FRENCH, u'fr_FR.UTF-8'), } mylocale = wx.Locale(locales[language][0], wx.LOCALE_LOAD_DEFAULT) langdir = os.path.join(path,u'locale') Lang = gettext.translation(u'messages', langdir, languages=[language]) Lang.install(unicode=1) if platform.system() == 'Linux': try: # to get some language settings to display properly: os.environ['LANG'] = locales[language][1] except (ValueError, KeyError): pass #-> Code to launch application goes here. <-# if __name__ == '__main__': if 'unicode' not in wx.PlatformInfo: print "\nInstalled version: %s\nYou need a unicode build of wxPython to run this application.\n"%version else: main() So my question is, where would the best place be to implement the code above? In start.py, main.py, in a separate file altogether? The problem I seem to be having is needing an instance of wx.App before the code recommended by the http://wiki.wxpython.org/Internationalization can become of use. I've come up with solutions to my dilemma but none seem to be especially clean. Any recommendations would be great. Also if any clarifications are needed let me know. Thanks From wim.vogelaaratmc2worlddotorg Wed Jul 11 03:51:05 2007 From: wim.vogelaaratmc2worlddotorg (Wim Vogelaar) Date: Wed, 11 Jul 2007 09:51:05 +0200 Subject: Visualizing a wav file? References: Message-ID: <46948baa$0$79693$dbd41001@news.wanadoo.nl> Perhaps you can use parts/routines of Audacity. See: http://en.wikipedia.org/wiki/Audacity Wim Vogelaar, http://home.wanadoo.nl/w.h.vogelaar/ From Colin.Prepscius at morganstanley.com Tue Jul 24 13:24:39 2007 From: Colin.Prepscius at morganstanley.com (Prepscius, Colin (IT)) Date: Tue, 24 Jul 2007 13:24:39 -0400 Subject: exec and func_code Message-ID: Does anybody know how to pass parameters to 'exec somefunction.func_code'? def f1(): print 'this is f1' def f2(p): print 'this is f2, p =', str(p) exec f1.func_code THIS RESULTS IN: "this is nf1" WHICH IS NICE exec f2.func_code THIS RESULTS IN: TypeError: f2() takes exactly 1 argument (0 given) WHICH IS EXPECTED exec f2.func_code in {'p':34} THIS RESULTS IN: TypeError: f2() takes exactly 1 argument (0 given) ????? thanks! Colin -------------------------------------------------------- NOTICE: If received in error, please destroy and notify sender. Sender does not intend to waive confidentiality or privilege. Use of this email is prohibited when received in error. -------------- next part -------------- An HTML attachment was scrubbed... URL: From S.Mientki-nospam at mailbox.kun.nl Sat Jul 14 04:26:23 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 14 Jul 2007 10:26:23 +0200 Subject: interactive graphical script builder In-Reply-To: <1184196856.996182.25040@k79g2000hse.googlegroups.com> References: <1184196856.996182.25040@k79g2000hse.googlegroups.com> Message-ID: nik wrote: > Hi, > > I am looking for an interactive graphical script builder for python. > Basically, something like the os X automator. I have made a group of > methods that some non-programmers need to combine into a script. I > don't need a python IDE necessarially, but more of a sequence builder. > I am imagining a tool that could show graphical representations of my > different commands and then string them together in a single "script." > I've done a lot of googling, and the closest things that I can find > are apple automator or labview, but before I go through the process of > making one of those interact with python I would like to know if > anybody already knows of something like them that is more tuned to > python. > > Thanks, > Nik > there's already someone who made a start to create a "free python labview", it's called Pyxel form Erik Lechak, an ogl-like interface. cheers, Stef Mientki From marcpp at gmail.com Thu Jul 5 10:04:13 2007 From: marcpp at gmail.com (Marcpp) Date: Thu, 05 Jul 2007 07:04:13 -0700 Subject: WXPYTHON push button call a frame In-Reply-To: References: <1183626149.036739.281070@w5g2000hsg.googlegroups.com> Message-ID: <1183644253.916399.9350@w5g2000hsg.googlegroups.com> On 5 jul, 14:51, Steve Holden wrote: > Marcpp wrote: > > Hi I need to call a widget from a button in WXPYTHON. I've tried to > > this from a function like this, but when push the button, the program > > opens a window and do error. > > Any idea? > > Well, one *really* good idea would be to copy the error message and > paste it into your message. The readers of this list have amazing > psychic powers, but you can always help improve the answer quality by > providing relevant information. > > > > > ..... > > def DialogRRHH(self,event): > > prog = wx.PySimpleApp(0) > > wx.InitAllImageHandlers() > > DialogRRHH = MTRRHH(None, -1, "") > > prog.SetTopWindow(DialogRRHH) > > DialogRRHH.Show() > > prog.MainLoop() > > > class MTRRHH(wx.Frame): > > ....... > > if __name__ == "__main__": > > app = wx.PySimpleApp(0) > > wx.InitAllImageHandlers() > > tasques = tasques(None, -1, "") > > app.SetTopWindow(tasques) > > tasques.Show() > > app.MainLoop() > > Unfortunately your code extracts don't tell us what's going wrong, only > how the program is constructed. While that *is* useful information, by > itself it only paints half the picture. > > 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, the problem is No Error message, but the program continues running after I closed it (by the X). From d.dwag.nz at gmail.com Sun Jul 15 06:08:48 2007 From: d.dwag.nz at gmail.com (ddwagnz) Date: Sun, 15 Jul 2007 22:08:48 +1200 Subject: Font used in Logo Message-ID: Hi, I'm just wondering why Python did not choose a free font that they can redistribute with the logo instead of a commercial font which puts limitations on distrubiting the font to the public im not exactly sure where to put this, i was told to send a thing to the list so excuse me if ive got the wrong place :) Cheers David Linton (ddwagnz) -------------- next part -------------- An HTML attachment was scrubbed... URL: From rcdailey at gmail.com Fri Jul 6 12:22:35 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 06 Jul 2007 16:22:35 -0000 Subject: Expandable 2D Dictionaries? In-Reply-To: References: <1183736635.415927.208450@57g2000hsv.googlegroups.com> Message-ID: <1183738955.861587.186370@c77g2000hse.googlegroups.com> On Jul 6, 11:09 am, Jean-Paul Calderone wrote: > On Fri, 06 Jul 2007 15:43:55 -0000, Robert Dailey wrote: > >Hi, > > >I am interested in creating an expandable (dynamic) 2D dictionary. For > >example: > > >myvar["cat"]["paw"] = "Some String" > > >The above example assumes "myvar" is declared. In order for this to > >work, I have to know ahead of time the contents of the dictionary. For > >the above to work, my declaration must look like: > > >myvar = {"cat": {"paw":""} } > > >I would like to not have to declare my dictionary like this, as it > >does not allow it to be expandable. I'm very new to Python (I'm a > >professional C++ programmer. Any comparisons to C++ would help me > >understand concepts). > > >Is there a way that when I index into my dictionary using an "unknown" > >index (string), that python will dynamically add that key/value pair? > > This gets much easier if you change your structure around a bit: > > d = {} > d["cat", "paw"] = "some string" > > Jean-Paul I like this format. I'm not familiar with it however. In my research of python I was not aware it was legal to have comma operators inside of the brackets. What does this mean? Is there some terminology that I can search for to research this concept? Thanks. From crobc at BOGUS.sbcglobal.net Sun Jul 29 15:24:56 2007 From: crobc at BOGUS.sbcglobal.net (CC) Date: Sun, 29 Jul 2007 12:24:56 -0700 Subject: Hex editor display - can this be more pythonic? Message-ID: Hi: I'm building a hex line editor as a first real Python programming exercise. Yesterday I posted about how to print the hex bytes of a string. There are two decent options: ln = '\x00\x01\xFF 456\x0889abcde~' import sys for c in ln: sys.stdout.write( '%.2X ' % ord(c) ) or this: sys.stdout.write( ' '.join( ['%.2X' % ord(c) for c in ln] ) + ' ' ) Either of these produces the desired output: 00 01 FF 20 34 35 36 08 38 39 61 62 63 64 65 7E I find the former more readable and simpler. The latter however has a slight advantage in not putting a space at the end unless I really want it. But which is more pythonic? The next step consists of printing out the ASCII printable characters. I have devised the following silliness: printable = ' 1!2 at 3#4$5%6^7&8*9(0)aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ\ `~-_=+\\|[{]};:\'",<.>/?' for c in ln: if c in printable: sys.stdout.write(c) else: sys.stdout.write('.') print Which when following the list comprehension based code above, produces the desired output: 00 01 FF 20 34 35 36 08 38 39 61 62 63 64 65 7E ... 456.89abcde~ I had considered using the .translate() method of strings, however this would require a larger translation table than my printable string. I was also using the .find() method of the printable string before realizing I could use 'in' here as well. I'd like to display the non-printable characters differently, since they can't be distinguished from genuine period '.' characters. Thus, I may use ANSI escape sequences like: for c in ln: if c in printable: sys.stdout.write(c) else: sys.stdout.write('\x1B[31m.') sys.stdout.write('\x1B[0m') print I'm also toying with the idea of showing hex bytes together with their ASCII representations, since I've often found it a chore to figure out which hex byte to change if I wanted to edit a certain ASCII char. Thus, I might display data something like this: 00(\0) 01() FF() 20( ) 34(4) 35(5) 36(6) 08(\b) 38(8) 39(9) 61(a) 62(b) 63(c) 64(d) 65(e) 7E(~) Where printing chars are shown in parenthesis, characters with Python escape sequences will be shown as their escapes in parens., while non-printing chars with no escapes will be shown with nothing in parens. Or perhaps a two-line output with offset addresses under the data. So many possibilities! Thanks for input! -- _____________________ Christopher R. Carlen crobc at bogus-remove-me.sbcglobal.net SuSE 9.1 Linux 2.6.5 From bjornkri at gmail.com Wed Jul 25 07:53:44 2007 From: bjornkri at gmail.com (beertje) Date: Wed, 25 Jul 2007 04:53:44 -0700 Subject: 16-bit colour representation Message-ID: <1185364424.797757.84620@22g2000hsm.googlegroups.com> This has me a bit stumped... I'm trying to extract pictures from a file. So far I'm successfully retrieved the header and what I think is the colour for each pixel. Here's the description: """ 3) The picture data format: The color information is 15 bit data stored in 16 bit. This means the most significant bit is unused. The data is stored line for line in little endian Intel format starting with top left edge to bottom right edge. This is normally called chunky format. Bit 0.. 4 blue value Bit 5.. 9 green value Bit 10..14 red value """ So I've got a list of 16-bit numbers, but how to extract RGB info from those I'm a bit lost. I thought at first I should convert the decimal (say 23294) into a binary (say 0101101011111110) into something like this: blue: 01011 green: 01011 red: 11111 But encountered two problems: First, I don't know what the best way is to do this conversion, but more importantly I don't see how every colour could possibly be represented like this. 65535 is presumably white, but converting this into chunks of 5 gives me a 31, 31, 31, a dark shade of grey. I guess I'm on the wrong track completely? I'm a bit unsure about how to treat what the guide calls 'UWORD'... Here's the full guide: http://lists.kde.org/?l=kde-games-devel&m=105548792026813&w=1#2 (16-bit PC cards) Thanks alot. From gnewsg at gmail.com Wed Jul 25 08:32:02 2007 From: gnewsg at gmail.com (billiejoex) Date: Wed, 25 Jul 2007 05:32:02 -0700 Subject: Unable to abort a FTP command? In-Reply-To: <1185349701.504484.14370@m37g2000prh.googlegroups.com> References: <1185349701.504484.14370@m37g2000prh.googlegroups.com> Message-ID: <1185366722.171461.228100@w3g2000hsg.googlegroups.com> On 25 Lug, 09:48, _... at 163.com wrote: > Hi, > I write the following script to retrieve a part of a large file > from a FTP site: > > import ftplib > > class ftp_getter(object): > > def __init__(self): > self.handle = ftplib.FTP('ftp_server_address') > self.handle.set_debuglevel(2) > self.login() > > def login(self): > self.handle.login('user', 'pass') > self.handle.cwd('/temp1/') > > def quit(self, is_close = False): > self.handle.quit() > if is_close: > self.handle.close() > print 'ftp handle closed' > > def getpart_callback(self, received): > print "received a packet" > if self.cnt <= 0: > if not self.outf.closed: > self.outf.close() > if not self.aborted: > try: > self.handle.abort() > self.aborted = True > except Exception,ex: > pass > else: > print 'received packet, [0] = %x' % ord(received[0]) > self.outf.write(received) > self.cnt -= len(received) > > def getpart(self, ftp_filename, rest, cnt, out_filename): > self.outf = open(out_filename, 'wb') > self.cnt = cnt > self.aborted = False > self.handle.retrbinary('RETR ' + ftp_filename, > self.getpart_callback, 8192, rest) > if not self.outf.closed: > self.outf.close() > > if __name__ == '__main__': > g = ftp_getter() > g.getpart('FILE_TO_RETRIEVE.DAT', 50000, 20, 'out.dat') > g.quit(True) > print "all done." > > As the last four lines shown, I want to connect to my FTP server, > retrieve 20 bytes starting at offset 50000 from FILE_TO_RETRIEVE.DAT, > and stop retrieving after more than 20 bytes have been received. It's > quite simple, but to my suprise, this code does not work. > "self.handle.abort()" have been executed and I got the expected > response from server(426), but the RETR command does not seem to stop > at all. More and more data are received and getpart_callback method is > called again and again. > Why the RETR command is not actually aborted? Can anyone help me? > > Thanks > > Xu Wang I would *strongly* rencommend avoid using ABOR. The easiest way to abort the data transfer is to simply close the data connection. Instead of using ftp.retrbinary you could 'handle' the data connetion ('manually') by yourself. The code below starts RETRieving a file, and quit when more than 2^19 bytes are transmitted (not tested). Hope this helps. fd = open('retrieved_file', 'wb') ftp = ftplib.FTP() ftp.connect(host=host, port=port) ftp.login(user=user, passwd=pwd) # use binary transfer type ftp.voidcmd('TYPE I') conn = ftp.transfercmd('retr 1.tmp', rest=None) bytes_recv = 0 while 1: chunk = conn.recv(8192) # stop transfer while it isn't finished yet if bytes_recv >= 524288: # 2^19 break elif not chunk: break fd.write(chunk) bytes_recv += len(chunk) conn.close() # here we should get a 426 response ftp.voidresp() fd.close() ftp.close() From i3dmaster at gmail.com Fri Jul 6 03:40:04 2007 From: i3dmaster at gmail.com (i3dmaster) Date: Fri, 06 Jul 2007 07:40:04 -0000 Subject: converting datetime object in UTC to local time In-Reply-To: <1183508215.142322.282550@i38g2000prf.googlegroups.com> References: <1183508215.142322.282550@i38g2000prf.googlegroups.com> Message-ID: <1183707604.078924.315170@a26g2000pre.googlegroups.com> How about subclass datetime.tzinfo? That way you can use asttimezone to transfer utc to localtime. It requires an aware object though not naive. A bit more coding, but a lot less converting... Jim On Jul 3, 5:16 pm, Matt wrote: > Hi all, > > So a lot of digging on doing this and still not a fabulous solution: > > import time > > # this takes the last_modified_date naivedatetime, converts it to a > # UTC timetuple, converts that to a timestamp (seconds since the > # epoch), subtracts the timezone offset (in seconds), and then > converts > # that back into a timetuple... Must be an easier way... > mytime = time.localtime(time.mktime(last_modified_date.utctimetuple()) > - time.timezone) > > lm_date_str = time.strftime("%m/%d/%Y %I:%M %p %Z", mytime) > > last_modified_date is a naivedatetime.datetimeobject > > A previous version gave me something like: > > mytime =datetime.datetime.fromtimestamp(time.mktime(last_modified_date.utctimetuple()) > - time.timezone) > > lm_date_str = mytime.strftime("%m/%d/%Y %I:%M %p %Z") > > But this gave me no timezone since thedatetimeobject is still > naive. And I'm going from adatetimeto a timetuple to a timestamp > back to adatetime... > > All this seems like a lot of monkeying around to do something that > should be simple -- is there a simple way to do this without requiring > some other module? > > thx > > Matt From bdesth.quelquechose at free.quelquepart.fr Wed Jul 25 15:15:53 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 25 Jul 2007 21:15:53 +0200 Subject: Relative-importing * In-Reply-To: References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> <871weth2gg.fsf@benfinney.id.au> Message-ID: <46ae3894$0$19609$426a34cc@news.free.fr> Steven D'Aprano a ?crit : (snip) > I do take your point that importing * has the potential to unexpectedly > clobber names you didn't intend, Another problem is that it makes harder to know from which module a name comes from. > and that's a good reason to avoid it > unless you have a good reason to use it. But there are good reasons. > > The "from module import *" statement is very useful if you wish to export > all the public objects from a "private" module, e.g. emulate what the os > module does with platform specific functions. Indeed. (snip) > I certainly agree that "from module import *" is easily abused, but to go > from there to the conclusion that it is a blight that must be stamped out > is far too strong. As with any "you shall not..." programming rule (goto's, multiple return points, public attributes, etc, etc), it stands as long as you don't fully understand when and why it's ok to do it. From jthacher at unm.edu Thu Jul 12 11:47:08 2007 From: jthacher at unm.edu (Jennifer Thacher) Date: Thu, 12 Jul 2007 15:47:08 GMT Subject: Lists in classes In-Reply-To: <1184253811.052346.220470@22g2000hsm.googlegroups.com> References: <1184253811.052346.220470@22g2000hsm.googlegroups.com> Message-ID: <02sli.21491$RX.13700@newssvr11.news.prodigy.net> Jeremy Lynch wrote: > Hello, > > Learning python from a c++ background. Very confused about this: > > ============ > class jeremy: > list=[] > def additem(self): > self.list.append("hi") > return > > temp = jeremy() > temp.additem() > temp.additem() > print temp.list > > temp2 = jeremy() > print temp2.list > ============== > The output gives: > ['hi','hi'] > ['hi','hi'] > > Why does adding items to one instance produce items in a separate > instance? Doesn't each instance of jeremy have its' own "list"? > > Many thanks for clearing up this newbie confusion. > > Jeremy. > In this code, "list" (bad name) is a class attribute and all therefor in all instances, the "list" attribute is reference to the class attribute unless otherwise assigned, as in __init__. For instance, try: temp = jeremy() temp.additem() temp.additem() print temp.list temp2 = jeremy() temp2.list = [1,2,3] print temp.list, temp2.list, jeremy.list And see which ones look the same (same reference) or look different. James From nikbaer at gmail.com Fri Jul 6 01:58:14 2007 From: nikbaer at gmail.com (nik) Date: Fri, 06 Jul 2007 05:58:14 -0000 Subject: VB frontend to Python COM backend Message-ID: <1183701494.979323.301500@d30g2000prg.googlegroups.com> I have a VB6 application that I would like to attach to a python communications application. I have come across several discussions on using VB with a Python COM back-end, but no starting point. I haven't had anymore luck with google at finding out what this method is called and where to find more information or examples on it. I would really appreciate it if someone could point me in the right direction for using python objects from VB. Thank you, Nik From arkanes at gmail.com Mon Jul 9 09:23:47 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 9 Jul 2007 08:23:47 -0500 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <9uRhi.17027$xk5.14289@edtnps82> Message-ID: <4866bea60707090623i3c76a3a0md99297dd55db1784@mail.gmail.com> On 7/6/07, Douglas Alan wrote: > "Chris Mellon" writes: > > > Sure, but thats part of the general refcounting vs GC argument - > > refcounting gives (a certain level of) timeliness in resource > > collection, GC often only runs under memory pressure. If you're > > saying that we should keep refcounting because it provides better > > handling of non-memory limited resources like file handles, I > > probably wouldn't argue. But saying we should keep refcounting > > because people like to and should write code that relies on implicit > > scope level object destruction I very strongly argue against. > > And why would you do that? People rely very heavily in C++ on when > destructors will be called, and they are in fact encouraged to do so. > They are, in fact, encouraged to do so *so* much that constructs like > "finally" and "with" have been rejected by the C++ BDFL. Instead, you > are told to use smart pointers, or what have you, to clean up your > allocated resources. > For the record, C++ doesn't have a BDFL. And yes, I know that it's used all the time in C++ and is heavily encouraged. However, C++ has totally different object semantics than Python, and there's no reason to think that we should use it because a different language with different rules does it. For one thing, Python doesn't have the concept of stack objects that C++ does. > I so no reason not to make Python at least as expressive a programming > language as C++. > I have an overwhelming urge to say something vulgar here. I'm going to restrain myself and point out that this isn't a discussion about expressiveness. > >> > Relying on the specific semantics of refcounting to give > >> > certain lifetimes is a logic error. > >> > > >> > For example: > >> > > >> > f = some_file() #maybe it's the file store for a database implementation > >> > f.write('a bunch of stuff') > >> > del f > >> > #insert code that assumes f is closed. > > >> That's not a logic error if you are coding in CPython, though I agree > >> that in this particular case the explicit use of "with" would be > >> preferable due to its clarity. > > > I stand by my statement. I feel that writing code in this manner is > > like writing C code that assumes uninitialized pointers are 0 - > > regardless of whether it works, it's erroneous and bad practice at > > best, and actively harmful at worst. > > That's a poor analogy. C doesn't guarantee that pointers will be > initialized to 0, and in fact, they typically are not. CPython, on > other other hand, guarantees that the refcounter behaves a certain > way. > It's a perfect analogy, because the value of an uninitialized pointer in C is *implementation dependent*. The standard gives you no guidance one way or the other, and an implementation is free to assign any value it wants. Including 0, and it's not uncommon for implementations to do so, at least in certain configurations. The Python language reference explicitly does *not* guarantee the behavior of the refcounter. By relying on it, you are relying on an implementation specific, non-specified behavior. Exactly like you'd be doing if you rely on the value of uninitialized variables in C. > There are languages other than C that guarantee that values are > initialized in certain ways. Are you going to also assert that in > those languages you should not rely on the initialization rules? > Of course not. Because they *do* guarantee and specify that. C doesn't, and neither does Python. From deets at nospam.web.de Tue Jul 31 06:37:07 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 31 Jul 2007 12:37:07 +0200 Subject: simple string backspace question References: <1185875052.153091.23300@19g2000hsx.googlegroups.com> <1185876068.755101.316320@b79g2000hse.googlegroups.com> <1i246s3.vl3okdq1tdw2N%raims@dot.com> <1185876594.444535.69470@22g2000hsm.googlegroups.com> Message-ID: <5h8hmjF3jg3mbU1@mid.uni-berlin.de> vedrandekovic at v-programs.com wrote: > On 31 srp, 12:03, ra... at dot.com (Lawrence Oluyede) wrote: >> wrote: >> > If you mean on operating system then unfortunately Windows XP. >> >> I don't know for sure but maybe it doesn't support all ASCII escapes >> codes. >> >> Why do you care about \b anyway :-) ? >> >> -- >> 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 > > Hi, > > I need this inevitable for my "programming language", for code > indentation. I don't know how to write script with module tokenize > for code indentation. Still not giving up reinventing the wheel? You should take some lessons on syntax analysis before attempting this. But I know this words won't be heard... So, to your actual problem: that backspace is removing a character is something an editor or a terminal do, because they interpret the backspace. You wouldn't expect the string "foo" to be rendered blue by magic as well, wouldn't you? So what you need to do is: search the string for backspaces, and remove the BS as well as the character before. Something along these lines (untested): teststring = "abc\bcde\b" while teststring.find("\b") > -1: pos = teststring.find("\b") teststring = teststring[:pos-1] + teststring[pos+1:] Diez From edzietarski at hotmail.com Tue Jul 24 05:26:15 2007 From: edzietarski at hotmail.com (NetHead) Date: Tue, 24 Jul 2007 02:26:15 -0700 Subject: Python pearls required for iteration across fields of data structure Message-ID: <1185269175.966730.248470@o61g2000hsh.googlegroups.com> I want to apply a method (replaceFieldsAndIndices) in my class to a number of attributes of a data structure. Specifically, to give some context, in the variable j below, I want to replace wildcards with values. I wanted to avoid cluttering the code with multiple calls to the method replaceFieldsAndIndices. The code below is WRONG, but hopefully illustrates what I am trying to achieve. Any suggestions how to code this is an efficient and maintainable (and correct) manner? # BAD code begins wildcards = None if trap: for c in translation.expressionList: wildcards += (c.rpn, c.format) for c in translation.conditionList: wildcards += (c.match, c.min, c.max, c.format) else: for c in translation.conditionRuleList: wildcards += (c.format, c.condition, c.expression) for c in translation.rules: wildcards += (c.match, c.min, c.max, c.bit, c.format) for i in wildcards: for j in i: try: j = self.replaceFieldsAndIndices(j, rcn, rcu, rcp, indices) except: # Ignore errors if condition has no format. pass # BAD code ends From zyzhu2000 at gmail.com Thu Jul 19 11:05:35 2007 From: zyzhu2000 at gmail.com (beginner) Date: Thu, 19 Jul 2007 15:05:35 -0000 Subject: A way to re-organize a list Message-ID: <1184857535.033057.49150@m3g2000hsh.googlegroups.com> 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 From steve at REMOVE.THIS.cybersource.com.au Fri Jul 20 20:31:17 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 21 Jul 2007 10:31:17 +1000 Subject: Sorting dict keys References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> Message-ID: On Fri, 20 Jul 2007 15:27:51 -0700, montyphyton wrote: >>>> b = a.keys() >>>> b.sort() > [1, 2, 3] > > Works fine, but I would really like it if I could somehow do it in one > line. Why? Is the Enter key on your keyboard broken? Is there a global shortage of newline characters that I haven't been told about? Does your employer pay you less if you write more lines? -- Steven. From miles at gnu.org Thu Jul 12 19:10:03 2007 From: miles at gnu.org (Miles Bader) Date: Fri, 13 Jul 2007 08:10:03 +0900 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373419.522607.14500@g4g2000hsf.googlegroups.com> <1182374902.920671.171900@k79g2000hse.googlegroups.com> <85ir9ifgtx.fsf@lola.goethe.zz> <1182376044.852820.261530@n2g2000hse.googlegroups.com> Message-ID: <87myy1gqwk.fsf@catnip.gol.com> Twisted writes: > I won't dignify your insulting twaddle and random ad-hominem verbiage > with any more responses after this one. Something with actual logical > argumentation to rebut may be another matter of course. Er, why don't you just answer his question (what version)? He's asking for actual information, which will help us understand what you are (trying) to to say. If you continue to just make vague and unsupported (and rather hostile) assertions, without examples, version numbers, or other concrete information, do you expect anybody will continue listening to you? -miles -- The secret to creativity is knowing how to hide your sources. --Albert Einstein From mail at microcorp.co.za Tue Jul 10 03:48:31 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 10 Jul 2007 09:48:31 +0200 Subject: Where is the syntax for the dict() constructor ?! (OT) References: <468D1D9D.6060002@gmail.com><468D3445.2060408@gmail.com><1183675552.466967.136360@i13g2000prf.googlegroups.com><5f6fo1F3b25tsU1@mid.uni-berlin.de><5f8rrpF3c8qopU1@mid.uni-berlin.de> <1183853628.296224.107400@i13g2000prf.googlegroups.com><00bc01c7c13f$573770a0$03000080@hendrik> <003801c7c1ef$afcf6e60$03000080@hendrik> Message-ID: <02c201c7c2c6$e460a2c0$03000080@hendrik> "Steve Holden" wrote: > Sorry - dreadful joke. Since teeth chew, I wondered whether esteeth > might eschew. [Graon ...] > *grin* *Wonders if he can extend this troll to get Steve to explain what "teeth" are.* ; - ) - Hendrik From carsten at uniqsys.com Wed Jul 25 16:12:26 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 25 Jul 2007 16:12:26 -0400 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185392048.737400.290050@j4g2000prf.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> Message-ID: <1185394346.4432.85.camel@dot.uniqsys.com> On Wed, 2007-07-25 at 12:34 -0700, walterbyrd wrote: > On Jul 25, 12:40 pm, Carsten Haese wrote: > > > What exactly could Python learn from PHP? > > Remember, I'm a noob, I'm not trolling. I know. > When I posted "Python" I meant the Python web-developement world. In > particular, python frameworks, like CherryPy, have requirements that > are not realistic for most shared hosting plans. CherryPy is not a framework. Also, CherryPy's requirements are very minimal. You either need a "vanilla" Apache/mod_python setup (which is no harder to set up than a vanilla Apache/PHP setup), or just Python itself if you use the webserver that is in CherryPy. > Maybe I'm wrong, but I often get the idea that those who develop > python frameworks don't give a thought to the realities of shared > hosting. They seem to think that everybody has complete control over > the server. Things are very different in the PHP universe. Again, CherryPy is not a web programming framework. It is a web server that "publishes" object methods. Also, things are only easy in the PHP world if you only use the modules that the hosting provider pre-installed. I doubt you'll easily find a PHP hosting provider that will allow connections to Informix or Oracle databases. > To use codeignitor as an example, again. On the "why codeignitor" > part of the welcome page you will find: > > --- > CodeIgniter is right for you if... > * You need broad compatibility with standard hosting accounts that run > a variety of PHP versions and configurations. > * You want a framework that requires nearly zero configuration. > * You want a framework that does not require you to use the command > line. > --- > > I don't seem to see Python frameworks using those sorts of selling > points. Posting as a noob, who is struggling to get django configured > on dreamhost, I gotta tell 'ya: those selling points look awfully > attractive. > > The point is: PHP framework makers are very considerate of the > realities of shared hosting. It may look like that to you, but that's not a property of the PHP language. I haven't seen CodeIgniter, but I imagine it's easy for you to set up because it's already installed by the hosting provider, which is due to PHP's popularity. If you could find a provider that can give you an out-of-the-box Django or TG set up, you'd probably find that just as easy. Finding a hosting provider that'll do this is the problem, of course, but that's not because these frameworks are designed to be hard to install. It's just that most providers don't pre-install these frameworks because there isn't enough demand. > Python framework makers don't seem to > give it a thought. Python framework makers have no influence over what web hosting providers do. > Just maybe, that's something that Python could > learn from PHP. What is "that", and what can Python developers do to learn "that"? -- Carsten Haese http://informixdb.sourceforge.net From http Fri Jul 20 03:40:13 2007 From: http (Paul Rubin) Date: 20 Jul 2007 00:40:13 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <7x8x9lwka9.fsf@ruckus.brouhaha.com> <1184914601.872554.19720@n2g2000hse.googlegroups.com> Message-ID: <7x4pjzjzfm.fsf@ruckus.brouhaha.com> Kay Schluehr writes: > Sure. But knowing that memory is limited doesn't buy you much because > you achieve an existential proof at best: you can show that the > program must run out of memory but you have to run the program to know > where this happens for arbitrary input values. Moreover you get always > different values for different memory limits. So in the general case > you can't improve over just letting the program run and notice what > happens. Program verification is nothing like the halting problem. It's not done by dropping the program into some tool and getting back a proof of correctness or incorrectness. The proof is developed, by the programmer, at the same time the program is developed. Verifiability means that the programmer-supplied proof is precise enough to be checked by the computer. Think of when you first learned to program. Most non-programmers have an idea of what it means to follow a set of steps precisely. For example they could tell you an algorithm for sorting a shelf full of books alphabetically by author. Programming means expressing such steps in much finer detail than humans usually require, to the point where a machine can execute it; it takes a lot of patience and knowledge of special techniques, more than non-programmers know how to do, but we programmers are used to it and even enjoy it. Now think of something like a code review. There is a line of code in your program (maybe even an assert statement), that depends on some variable "x" being greater than 3. You must have had a reason for thinking x>3 there, so if the reviewer asks why you thought that, you can explain your argument until the reviewer is convinced. Do you see where this is going? Code verification means expressing such an argument in much finer detail than humans usually require, to the point where a machine can be convinced by it; it takes a lot of patience and knowledge of special techniques, more than most of us regular "practical" programmers currently know how to do, but the methods are getting more accessible and are regularly used in high-assurance software. In any case there is nothing magic about it--just like programming, it's a means of expressing precisely to a machine what you already know informally how to express to a human. From mike.klaas at gmail.com Fri Jul 13 19:56:12 2007 From: mike.klaas at gmail.com (Klaas) Date: Fri, 13 Jul 2007 16:56:12 -0700 Subject: Where does str class represent its data? In-Reply-To: <1184197025.491866.88110@r34g2000hsd.googlegroups.com> References: <1184196082.903895.176020@n60g2000hse.googlegroups.com> <1184197025.491866.88110@r34g2000hsd.googlegroups.com> Message-ID: <1184370972.023427.81910@i13g2000prf.googlegroups.com> On Jul 11, 4:37 pm, Miles wrote: > Since strings are immutable, you need to override the __new__ method. > Seehttp://www.python.org/download/releases/2.2.3/descrintro/#__new__ In case this isn't clear, here is how to do it: In [1]: class MyString(str): ...: def __new__(cls, value): ...: return str.__new__(cls, value.lower()) In [2]: s = MyString('Hello World') In [3]: s Out[3]: 'hello world' Note that this will not do fancy stuff like automatically call __str__() methods. If you want that, call str() first: In [5]: class MyString(str): ...: def __new__(cls, value): ...: return str.__new__(cls, str(value).lower()) -Mike From Graham.Dumpleton at gmail.com Sat Jul 14 22:34:42 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: Sun, 15 Jul 2007 02:34:42 -0000 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1184458002.961657.267830@x35g2000prf.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> <1184458002.961657.267830@x35g2000prf.googlegroups.com> Message-ID: <1184466882.446791.127670@x35g2000prf.googlegroups.com> On Jul 15, 10:06 am, Graham Dumpleton wrote: > On Jul 15, 2:47 am, 7stud wrote: > > > > > Themod_pythonmanual says this under section 2.1 Prerequisites: > > > ------ > > In order to compilemod_pythonyou will need to have the include files > > for both Apache and Python, as well as the Python library installed on > > your system. If you installed Python and Apache from source, then you > > already have everything needed. However, if you are using prepackaged > > software (e.g. Red Hat Linux RPM, Debian, or Solaris packages from > > sunsite, etc) then chances are, you have just the binaries and not the > > sources on your system. Often, the Apache and Python include files and > > libraries necessary to compilemod_pythonare part of separate > > ``development'' package. If you are not sure whether you have all the > > necessary files, either compile and install Python and Apache from > > source, or refer to the documentation for your system on how to get > > the development packages. > > ----- > > > I installed Apache from source using these instructions: > > >http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-o... > > > but I used a package to install python 2.4. The package was from > > here: > > >http://www.pythonmac.org/packages/ > > > and it's a "Universal binary version of Python that runs natively on > > PPC and Intel systems." > > > But my mac came with Python 2.3.5 pre-installed, so I wonder if I > > already have the necessary "include files for both Apache and Python, > > as well as the Python library" already installed. > > Have you actually tried to install mod_python? That would be the > quickest way of finding out. > > Because you are using an alternate Apache than the OS supplied one, > you will need to use the --with-apxs option to configure when building > Python. Whoops, --with-apxs option is to configure for mod_python, not Python. > Unless you really need Python 2.4, it is easier to use the OS > supplied version of Python. If you must use an alternate version, use > the --with-python option to configure for mod_python to tell it which > version. Depending on where that Python version is installed, you may > also have to fiddle the Apache 'envvars' file as well to get it to > work. > > Graham From semanticist at gmail.com Mon Jul 23 04:10:37 2007 From: semanticist at gmail.com (Miles) Date: Mon, 23 Jul 2007 04:10:37 -0400 Subject: URL parsing for the hard cases In-Reply-To: References: <1185138747.707836.69740@n2g2000hse.googlegroups.com> Message-ID: On 7/22/07, John Nagle wrote: > Is there any library function that correctly tests for an IP address vs. a > domain name based on syntax, i.e. without looking it up in DNS? import re, string NETLOC_RE = re.compile(r'''^ # start of string (?:([^@])+@)? # 1: (?:\[([0-9a-fA-F:]+)\]| # 2: IPv6 addr ([^\[\]:]+)) # 3: IPv4 addr or reg-name (?::(\d+))? # 4: optional port $''', re.VERBOSE) # end of string def normalize_IPv4(netloc): try: # Assume it's an IP; if it's not, catch the error and return None host = NETLOC_RE.match(netloc).group(3) octets = [string.atoi(o, 0) for o in host.split('.')] assert len(octets) <= 4 for i in range(len(octets), 4): octets[i-1:] = divmod(octets[i-1], 256**(4-i)) for o in octets: assert o < 256 host = '.'.join(str(o) for o in octets) except (AssertionError, ValueError, AttributeError): return None return host def is_ip(netloc): if normalize_IPv4(netloc) is None: match = NETLOC_RE.match(netloc) # IPv6 validation could be stricter if match and match.group(2): return True else: return False return True The first function, I'd imagine, is the more interesting of the two. -Miles From martin.clausen at gmail.com Mon Jul 9 19:11:24 2007 From: martin.clausen at gmail.com (Martin) Date: Mon, 09 Jul 2007 23:11:24 -0000 Subject: Error when trying to write unicode xml to zipfile Message-ID: <1184022684.557693.111890@n60g2000hse.googlegroups.com> I get below error when trying to write unicode xml to a zipfile. zip.writestr('content.xml', content.toxml()) File "/usr/lib/python2.4/zipfile.py", line 460, in writestr zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum UnicodeEncodeError: 'ascii' codec can't encode character u'\u25cf' in position 2848: ordinal not in range(128) Any ideas? Martin From omari at smileystation.com Tue Jul 17 19:11:22 2007 From: omari at smileystation.com (Omari Norman) Date: Tue, 17 Jul 2007 19:11:22 -0400 Subject: Lookup encoding aliases in Python 2.4 In-Reply-To: <20070717230459.GB15032@cameron> References: <20070717230459.GB15032@cameron> Message-ID: <20070717231122.GA15590@cameron> Forget about that--I then found /usr/lib/python2.5/encodings/aliases.py, which is also in Python 2.4. Sorry for the silly question! On Tue, Jul 17, 2007 at 07:04:59PM -0400, Omari Norman wrote: > My program creates new XML files (not through the DOM, but just by > simple file.write calls.) It would be nice if said files would > be in the default system encoding. So in Python 2.5 I use > > ENCODING = codecs.lookup(locale.getdefaultlocale()[1]).name > > locale.getdefaultlocale()[1] sometimes returns a non-canonical encoding > name, such as 'UTF8'. This gives the xml.sax parser a fit, so I use > codecs.lookup to convert the alias to the canonical encoding name. I > then write this encoding in the top line of the XML file. > > Python 2.4's codecs.lookup works differently--it does not return names. > Is there any way to accomplish this in Python 2.4? I went looking > through the codecs module in 2.5 to see if I could find a dict with the > aliases, to no avail. I suppose the worst-case scenario is that I make a > dict myself with common encodings in it (or, just tell people to use > Python 2.5.) > > Thanks, > Omari > > -- > Batteries not included; you put it together. -- Professional driver. Closed course. Do not attempt. From heikki at osafoundation.org Fri Jul 27 14:18:23 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 27 Jul 2007 11:18:23 -0700 Subject: ANN: M2Crypto 0.18 Message-ID: M2Crypto is the most complete Python wrapper for OpenSSL featuring RSA, DSA, DH, HMACs, message digests, symmetric ciphers (including AES); SSL functionality to implement clients and servers; HTTPS extensions to Python's httplib, urllib, and xmlrpclib; unforgeable HMAC'ing AuthCookies for web session management; FTP/TLS client and server; S/MIME; ZServerSSL: A HTTPS server for Zope and ZSmime: An S/MIME messenger for Zope. Download links on the homepage at http://chandlerproject.org/Projects/MeTooCrypto. Changelog: - Added EVP.pbkdf2 to derive key from password - X509_Store_Context.get1_chain added - Added X509_Name.__iter__, __getitem__, get_entries_by_nid which allow iterating over all X509_Name_Entries or getting just all commonName entries, for example - Added X509_Name_Entry.get_object, get_data, set_data - Added back PKCS7.get0_signers (was removed in 0.16) - X509_Extension.get_value accepts flag and indent parameters. - support multiple dNSName fields in subjectAltName - support multiple commonName fields for SSL peer hostname checking - Checking for erroneous returns from more OpenSSL EVP_* functions, which means that certain things that used to fail silently will now raise an EVP.EVPError; affected m2 functions are: digest_final, cipher_init, cipher_update, cipher_final and sign_update. sign_final will now raise EVP.EVPError instead of SystemError as well. - Fixed Pkey.verify_final to take a sign parameter - If a subjectAltName extension of type dNSName is present in peer certificate, use only the dNSNames when checking peer certificate hostname, as specified by RFC 2818. If no dNSNames are present, use subject commonName. - Fixed memory leaks in m2 functions ec_key_new_by_curve_name, pkey_get_modulus, ecdsa_verify, threading_init and X509.X509.verify, X509.X509_Stack (which manifested for example when calling X509.new_stack_from_der), SSL.Connection (which manifested with some connection errors or when connect was never called), twisted wrapper, SSL.Connection.makefile (in BIO.IOBuffer really) - Fixed threading regressions introduced in 0.16, by Aaron Reizes and Keith Jackson - Added SSL session caching support to HTTPSConnection, by Keith Jackson - Added the ability to save and load DER formatted X509 certificates and certificate requests, by Keith Jackson - m2xmlrpclib.py fixed to work with Python 2.5, by Miloslav Trmac - 64-bit correctness fixes, by Miloslav Trmac - Added X509_Name.as_hash, by Thomas Uram - Moved --openssl option from general setup.py option to build_ext option, meaning you need to do: python setup.py build build_ext --openssl=/path, by Philip Kershaw - Fixed build problem affecting certain systems where OpenSSL was built without EC support - M2CRYPTO_TEST_SSL_SLEEP environment variable controls how long to sleep after starting the test SSL server. Default is 0.5, but 0.1 or even 0.05 might work with modern computers. Makes tests finish significantly faster. -- Heikki Toivonen From mensanator at aol.com Thu Jul 26 00:51:03 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Wed, 25 Jul 2007 21:51:03 -0700 Subject: From D In-Reply-To: References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> Message-ID: <1185425463.796350.128550@i13g2000prf.googlegroups.com> On Jul 25, 8:54?pm, Steven D'Aprano wrote: > On Wed, 25 Jul 2007 10:22:46 -0700, mensana... at aol.com wrote: > > On Jul 24, 6:08 pm, Steven D'Aprano > > wrote: > >> On Tue, 24 Jul 2007 20:09:00 +0200, Bjoern Schliessmann wrote: > >> > Stargaming wrote: > >> >> On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote: > > >> >>> While in a syntax like: > >> >>> for i in xrange(1_000_000): > >> >>> my eyes help me group them at once. > > >> >> Sounds like a good thing to be but the arbitrary positioning > >> >> doesnt make any sense. > > >> > Checking underscore positions would only add complexity. Why not > >> > just ignore them, no matter where they are? > > >> Underscores in numerics are UGLY. Why not take a leaf out of implicit > >> string concatenation and allow numeric literals to implicitly concatenate? > > >> Python already does: > >> "hello-" "world" => "hello-world" > > >> Propose: > >> 123 456 789 => 123456789 > >> 123.456 789 => 123.456789 > > > So, spaces will no longer be delimiters? Won't that cause > > much wailing and gnashing of teeth? > > Did you miss the bit where Python ALREADY does this for strings? Did you miss the bit where I agreed this was a GOOD feature? You didn't miss it because I didn't say it. > > Yes, whitespace will still delimit tokens. No, it won't be a problem, > because two int tokens can be "concatenated" to make a single int token, > exactly as happens for strings. Any number of whitespace characters? Just spaces or all whitespace characters? > > (I say "no problem", but of course I don't know how much _actual_ coding > effort will be needed to Make This Work. It might be a little, it might be > a lot.) > > Currently, 234 567 is a syntax error in Python, so there are no problems > with backward compatibility or breaking code that relies on the meaning of > whitespace between two ints. That's the ONLY issue? What about searching source code files? What's the regular expression for locating a number with an arbitrary number of digits seperated into an arbitrary number of blocks of an arbitray number of digits with an arbitrary number of whitespace characters between each block? > > -- > Steven From gnewsg at gmail.com Wed Jul 25 09:57:43 2007 From: gnewsg at gmail.com (billiejoex) Date: Wed, 25 Jul 2007 06:57:43 -0700 Subject: How to tell when a socket is closed on the other end? Message-ID: <1185371863.622473.205010@19g2000hsx.googlegroups.com> Hi there. I'm setting up test suite for a project of mine. >From test suite, acting as a client, I'd like to know, in certain situations, if the socket is closed on the other end or not. I noticed that I can "detect" such state if a call to socket.read() returns 0 but it seems a little poor to me. :-\ Is there a reliable way to test such socket 'state'? From max at alcyone.com Fri Jul 13 18:26:13 2007 From: max at alcyone.com (Erik Max Francis) Date: Fri, 13 Jul 2007 15:26:13 -0700 Subject: Pass by reference or by value? In-Reply-To: References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> Message-ID: James Stroud wrote: > Robert Dailey wrote: >> I noticed in Python all function parameters seem to be passed by >> reference. This means that when I modify the value of a variable of a >> function, the value of the variable externally from the function is >> also modified. >> >> Sometimes I wish to work with "copies", in that when I pass in an >> integer variable into a function, I want the function to be modifying >> a COPY, not the reference. Is this possible? > > Not only is this possible, that is actually what happens with ints! But that's because ints are immutable, not because there is an explicit copy of anything being made. -- 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 Ipsa scientia potestas est. "Knowledge itself is power." -- a Latin proverb From bignose+hates-spam at benfinney.id.au Tue Jul 24 00:24:00 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 24 Jul 2007 14:24:00 +1000 Subject: pylint style convention References: <46a53823$0$3769$80265adb@spool.cs.wisc.edu> Message-ID: <87sl7ejuov.fsf@benfinney.id.au> mick at cs.wisc.edu (Mick Charles Beaver) writes: > Here's a snippet: pylint is reporting line numbers. Can you show us line numbers for this snippet? > #====================================================================== > if __name__ == '__main__': > parser = optparse.OptionParser(usage='usage: %prog [OPTIONS]') > parser.add_option('-c', '--config', > action='store', > type='string', > dest='configFilename', > help='config file containing defaults') > (options, args) = parser.parse_args() > #====================================================================== > > Now, PyLint reports the following convention warnings: > C:158: Invalid name "parser" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) > C:170: Invalid name "options" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) > C:170: Invalid name "args" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) These warnings are for line 158 and line 170, which covers a range of 13 lines. Your code snippet is only 8 lines long. So at least one of those two lines that have warnings reported are not in the code you've shown to us. -- \ "Too many Indians spoil the golden egg." -- Sir Joh | `\ Bjelke-Petersen | _o__) | Ben Finney From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jul 3 06:53:23 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 03 Jul 2007 12:53:23 +0200 Subject: newbie-question References: <468a2607$0$14903$9b622d9e@news.freenet.de> Message-ID: <5euo53F3abk5vU1@mid.individual.net> TK wrote: > how can I implement a socket timeout? What exactly do you mean by "socket timeout"? Which OS? > Thanx for help. Thanks for choosing an adequate subject next time. Regards, Bj?rn -- BOFH excuse #84: Someone is standing on the ethernet cable, causing a kink in the cable From mattheww at chiark.greenend.org.uk Wed Jul 11 14:25:51 2007 From: mattheww at chiark.greenend.org.uk (Matthew Woodcraft) Date: 11 Jul 2007 19:25:51 +0100 (BST) Subject: os.wait() losing child? References: <4694903B.8000105@cosc.canterbury.ac.nz> Message-ID: greg wrote: > I've figured out what's going on. The Popen class has a > __del__ method which does a non-blocking wait of its own. > So you need to keep the Popen instance for each subprocess > alive until your wait call has cleaned it up. I don't think this will be enough for the poster, who has Python 2.4: in that version, opening a new Popen object would trigger the wait on all 'outstanding' Popen-managed subprocesses. It seems to me that subprocess.py assumes that it will do all wait()ing on its children itself; I'm not sure if it's safe to rely on the details of how this is currently arranged. Perhaps a better way would be for subprocess.py to provide its own variant of os.wait() for people who want 'wait-for-any-child' (though it would be hard to support programs which also had children not managed by subprocess.py). -M- From kyosohma at gmail.com Tue Jul 3 13:54:51 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Tue, 03 Jul 2007 10:54:51 -0700 Subject: wxPython Cannot convert from the charset 'latin-1' In-Reply-To: <468a7659$0$13864$ba620e4c@news.skynet.be> References: <468a7659$0$13864$ba620e4c@news.skynet.be> Message-ID: <1183485291.752135.225200@g4g2000hsf.googlegroups.com> On Jul 3, 11:16 am, Helmut Jarausch wrote: > Hi, > > I'm trying to teach "dugui.py" (a tiny GUI for restructuredtext written in > wxPython) to accept files in isolatin-1 encoding. It displays e.g. German > umlauts correctly but then I get a popup window saying > Python Error > Cannot convert from the charset 'latin-1'! > > How can I find out where this did come from. Running it under pdb > isn't helpful either. > > Many thanks for a hint, > > Helmut Jarausch > > Lehrstuhl fuer Numerische Mathematik > RWTH - Aachen University > D 52056 Aachen, Germany Probably your best bet is to post wxPython specific questions to the wxPython user's group: http://www.wxpython.org/maillist.php But I did a little Google-fu and found this for you: http://wiki.wxpython.org/index.cgi/UnicodeBuild Mike From stargaming at gmail.com Wed Jul 11 02:04:33 2007 From: stargaming at gmail.com (Stargaming) Date: Wed, 11 Jul 2007 08:04:33 +0200 Subject: bool behavior in Python 3000? In-Reply-To: References: <5ficp9F3cram2U2@mid.individual.net> Message-ID: <469472f4$0$1293$9b622d9e@news.freenet.de> Steven D'Aprano wrote: > On Tue, 10 Jul 2007 23:42:01 +0200, Bjoern Schliessmann wrote: > > >>Alan G Isaac wrote: >> >> >>>My preference would be for the arithmetic operations *,+,- >>>to be given the standard interpretation for a two element >>>boolean algebra: >>>http://en.wikipedia.org/wiki/Two-element_Boolean_algebra >> >>>>>[bool(True+True), bool(True+False)] >> >>[True, True] >> >>Works for me, or did I misunderstand you? > > > It seems to me that you deliberately misunderstood him. Why else would you > type-cast the integers 2 and 1 to bools to supposedly demonstrate that > there's nothing wrong with operations between bools returning ints? [snip] No, I think Bjoern just wanted to point out that all those binary boolean operators already work *perfectly*. You just have to emphasize that you're doing boolean algebra there, using `bool()`. "Explicit is better than implicit." From larry.bates at websafe.com Wed Jul 25 13:20:36 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 25 Jul 2007 12:20:36 -0500 Subject: How to create a single executable of a Python program In-Reply-To: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> References: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> Message-ID: NicolasG wrote: > Dear fellows, > > I'm trying to create a executable file using py2exe . Unfortunately > along with the python executable file it also creates some other files > that are needed in order to the executable be able to run in a system > that doesn't have Python installed. Can some one guide me on how can I > merge all this files created by py2exe in a single exe file ? If I > have a python program that uses an image file I don't want this image > file to be exposed in the folder but only to be accessible through the > program flow.. > > Regards, > Nicolas. > You need to tell us why you "think" you need this and perhaps we can make a suggestion. Question: Have you installed ANY applications recently that consisted of only a single file on your hard drive? Answer: No. Most applications install many (sometimes hundreds) of files. So what is the problem. If you want a single file to distribute, look at Inno Installer. Use it to make a single, setup.exe out of all the files that come out of py2exe along with documentation, shortcuts, etc. that a good modern application needs. -Larry From fred at adventistcare.org Tue Jul 3 12:13:30 2007 From: fred at adventistcare.org (Sells, Fred) Date: Tue, 3 Jul 2007 12:13:30 -0400 Subject: MySQL -->Python-->XML for JSviz Message-ID: Sometimes sneaky is better than elegant. You could shell down to a command line invocation of mysql and specify -xml as the output format. I'm not sure how close that format is to what you need or how much you could leverage views (if using mysql 5.0). You could also use a command line xslt processor to then redefine your xml output. That way your data extraction is one task and you could have many xsl files to convert as needed. I have used parts of this technique and found it easy to create and debug; but I have not used the xml output option of mysql. I'm sure others will point out many excellent xml modules. > -----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 Picio > Sent: Tuesday, July 03, 2007 10:08 AM > To: python-list at python.org > Subject: MySQL -->Python-->XML for JSviz > > > Hello all, I need some advice to choose an xml generator for jsviz a > tool in javascript to create some wonderful graphs (SnowFlake or Force > directed). > > Starting from a SQL table (mysql) I need to create a XML file with a > structure like this: > > > > > > > > > > Where nodes attributes are the MySQL table fields (the PK will be the > attribute). > I know there are a lot of good tools to do this in pyhton (some maybe > is already shipped with pyton itself), but since I need a lot of > flexibility for the future I'd like to use an Object relational mapper > like SQLAlchemy or SQLObject todo the job. When I say flexibility, I > have in mind a solution to have multiple formats coming outside of the > ORM: > json, csv, plain text etc... > Am I wrong? > Can someone advice something? > > -- > http://mail.python.org/mailman/listinfo/python-list > From carsten at uniqsys.com Tue Jul 17 17:30:56 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 17 Jul 2007 17:30:56 -0400 Subject: sqlite tuples In-Reply-To: <20070717204903.GA3890@spookie1.spookiegate> References: <20070717204903.GA3890@spookie1.spookiegate> Message-ID: <1184707856.3400.8.camel@dot.uniqsys.com> On Tue, 2007-07-17 at 21:49 +0100, John K Masters wrote: > I am fairly new to Python and am trying to get to grips with pysqlite2. > >From what I have read data is returned as a list of tuples when using > SELECT via connection.cursor. But I have not, despite frantic googling, > found how to INSERT a list of tuples into a sqlite table. If I convert > the tuple to a string and concatenate it to the 'INSERT INTO table etc.' > string then it works, but only if all the tuple values are strings and > then only if all the table fields are of type TEXT. > > Is it possible to, and if so how can one, insert a list of tuples into a > sqlite table? Assuming that each tuple is the same length and goes into the same table and columns, something like this will do the trick: sql = "insert into tablename(column1,column2,column3) values(?,?,?)" cursor.executemany(sql, list_of_tuples) If you don't know the number of columns at design time, you'll need to fill the values(...) clause on the fly with the correct number of question marks, and you'll have to build the list of column names somehow, too, but the basic idea is the same. HTH, -- Carsten Haese http://informixdb.sourceforge.net From ssalvatori at gmail.com Tue Jul 31 22:49:55 2007 From: ssalvatori at gmail.com (stefano) Date: Wed, 01 Aug 2007 02:49:55 -0000 Subject: http client module Message-ID: <1185936595.262806.269290@19g2000hsx.googlegroups.com> 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/projects/httplib2/+httplib2+python&hl=es&ct=clnk&cd=1&gl=cl&client=firefox-a but is too old From martin at v.loewis.de Sun Jul 1 05:45:42 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 01 Jul 2007 11:45:42 +0200 Subject: shelve crashing under Win ME In-Reply-To: <1183271815.085382.251640@d30g2000prg.googlegroups.com> References: <1183193535.127098.299840@a26g2000pre.googlegroups.com> <200706301007.29992.inq1ltd@verizon.net> <1183257088.085647.280010@z28g2000prd.googlegroups.com> <1183271815.085382.251640@d30g2000prg.googlegroups.com> Message-ID: <468777c6$0$22426$9b622d9e@news.freenet.de> gluckj at gmail.com schrieb: > OK, here's my workaround for shelve -- it's primitive and obviously > much slower (it saves the entire dictionary each time), and you have > to manually save -- BUT: it works...even on the Win ME machine. And > it's possibly more universally portable in the long run than > shelve...Also, once you open the dictionary, it is just as fast > (perhaps faster?) than shelve for reading the contents (just not for > saving...) Notice that you don't need to use bsddb for shelve. Instead, you might use dumbdbm instead, passing the dbm directly to shelve.Shelf. It's probably slower than bsddb, however, updating a single key should be faster than pickling an entire dictionary. Regards, Martin From doug at alum.mit.edu Mon Jul 2 21:53:35 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Mon, 02 Jul 2007 21:53:35 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <9uRhi.17027$xk5.14289@edtnps82> Message-ID: Lenard Lindstrom writes: >> Also, any caught exception is automatically cleared when >> the catching procedure returns anyway, so it's not like Python has >> ever considered a caught exception to be precious information that >> ought to be preserved long past the point where it is handled. > That's the point. Python takes care of clearing the traceback. Calls > to exc_clear are rarely seen. But that's probably because it's very rare to catch an exception and then not return quickly. Typically, the only place this would happen is in main(), or one of its helpers. > If they are simply a performance tweak then it's not an issue *. I > was just concerned that the calls were necessary to keep resources > from being exhausted. Well, if you catch an exception and don't return quickly, you have to consider not only the possibility that there could be some open files left in the traceback, but also that there could be a large and now useless data structures stored in the traceback. Some people here have been arguing that all code should use "with" to ensure that the files are closed. But this still wouldn't solve the problem of the large data structures being left around for an arbitrary amount of time. > But some things will make it into ISO Python. Is there a movement afoot of which I'm unaware to make an ISO standard for Python? > Just as long as you have weighed the benefits against a future move > to a JIT-accelerated, continuation supporting PyPy interpreter that > might not use reference counting. I'll worry about that day when it happens, since many of my calls to the standard library will probably break anyway at that point. Not to mention that I don't stay within the confines of Python 2.2, which is where Jython currently is. (E.g., Jython does not have generators.) Etc. >> I think that Jython and IronPython, etc., should adopt these >> semantics, but I imagine they might not for performance reasons. I >> don't generally use Python for it's speediness, however, but rather >> for it's pleasant syntax and semantics and large, effective >> library. > Yet improved performance appeared to be a priority in Python 2.4 > development, and Python's speed continues to be a concern. I don't think the refcounting semantics should slow Python down much considering that it never has aimed for C-level performance anyway. (Some people claim it's a drag on supporting threads. I'm skeptical, though.) I can see it being a drag on something like Jython, though, were you are going through a number of different layers to get from Jython code to the hardware. Also, I imagine that no one wants to put in the work in Jython to have a refcounter when the garbage collector comes with the JVM for free. |>oug From george.sakkis at gmail.com Wed Jul 18 15:32:35 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Wed, 18 Jul 2007 19:32:35 -0000 Subject: Implementaion of random.shuffle In-Reply-To: References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> <87d4ys9z46.fsf@mulj.homelinux.net> Message-ID: <1184787155.773575.303080@d30g2000prg.googlegroups.com> On Jul 16, 10:51 pm, Steven D'Aprano wrote: > On Mon, 16 Jul 2007 16:55:53 +0200, Hrvoje Niksic wrote: > > 2**19937 being a really huge number, it's impossible to exhaust the > > Mersenne twister by running it in sequence. > > "Impossible"? > > Surely this will do it: > > for n in xrange(2**19937 + 1): > random.random() > > Admittedly, if each call to random() took a picosecond, it would still > take 1e5982 centuries to run through the lot. You might want to go make a > coffee or something while you're waiting... Wow, can you make a coffee in.. 57ms ? $ time python -c "for n in xrange(2**19937 + 1): random.random()" Traceback (most recent call last): File "", line 1, in OverflowError: long int too large to convert to int real 0m0.057s user 0m0.050s sys 0m0.000s Time-flies-like-an-arrow-ly y'rs ;-) George From alexandre.ferrieux at gmail.com Thu Jul 26 14:13:57 2007 From: alexandre.ferrieux at gmail.com (Alexandre Ferrieux) Date: Thu, 26 Jul 2007 18:13:57 -0000 Subject: Why is "for line in f" faster than readline() Message-ID: <1185473637.817954.129660@o61g2000hsh.googlegroups.com> Hi, In a recent thread I discovered why the "for line in f" idiom was not suitable for live sources (pipes, sockets, tty). The reason is that it uses buffering on input, blocking on a full buffer read before anything. When I asked why it did it this way, the answer came up that it made it faster. Now, *why* is such buffering gaining speed over stdio's fgets(), which already does input buffering (though in a more subtle way, which makes it still usable with pipes etc.) ? -Alex From no at no.no Wed Jul 25 17:33:21 2007 From: no at no.no (Daniel) Date: Thu, 26 Jul 2007 00:33:21 +0300 Subject: Why PHP is so much more popular for web-development References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> Message-ID: On Wed, 25 Jul 2007 20:42:54 +0300, walterbyrd wrote: > I'm fairly new to web-development, and I'm trying out different > technologies. Some people wonder why PHP is so popular, when the > language is flawed in so many ways. To me, it's obvious: it's because > it's much easier to get started with PHP, and once somebody gets > started with a particular language, that person is likely to stay with > that language. I think Python is the computer scientist based language, whereas PHP is for weekend hobbyists. Not to say you can't produce serious code with PHP (or quick and dirty code with Python). Having used both, I can tell you that Python will take 10 times the initial effort to produce the same functionality as a PHP implementation - since Python programmers will not opt for quick hacks and workarounds like PHP coders will. The trade off however is that Python code is much more readable and 100 times more maintainable in the long run, which I consider more important. However this is the problem: Web Development is not about being perfect, it's about getting your application to production as quick as possible, worrying about bugs and added functionality later on. No good putting your idea on the web 6 months after your competitor has taken all the market share. PHP lets you do this very quickly, Python does not. I find myself trying to 'finish' the Python app whereas in PHP I would have already gone live. Today I've found the best approach for me is a hybrid solution. Since database models are quite definitive - it doesn't matter if I use PHP or Python, the underlying datastructure for my app won't change. Therefore, using a library of custom helpers and framework-like tools for PHP, I can create a working site in less than a couple days in PHP. This is made live. Then I have the time to rewrite the app in Python, which will take me a couple weeks, but due to the much better language properties of Python, will mean that I can also maintain it a year after writing it. From steve at holdenweb.com Mon Jul 2 18:06:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Jul 2007 18:06:41 -0400 Subject: subprocess -- broken pipe error In-Reply-To: <1183406772.091375.89830@c77g2000hse.googlegroups.com> References: <1183396350.429008.185200@n2g2000hse.googlegroups.com> <1183397577.959518.264230@g4g2000hsf.googlegroups.com> <1183400345.202323.133750@k29g2000hsd.googlegroups.com> <5et3n6F399q8uU1@mid.individual.net> <1183406772.091375.89830@c77g2000hse.googlegroups.com> Message-ID: 7stud wrote: > On Jul 2, 1:58 pm, Bjoern Schliessmann mail-0306.20.chr0n... at spamgourmet.com> wrote: >> 7stud wrote: >>> Thanks for the response. So are you saying that the only way you >>> can get data out of a pipe is when the subprocess has terminated? >> No, not only because Pipes aren't related to processes in any >> special way. >> >> He said that you can't write to a pipe whose reader has already >> terminated. >> > > What he said was: > >> ...once the subprocess terminates (which it must have done for >> p.stdout.read() to return a result) > > And based on the results of the examples I posted in my last post, it > seems to confirm that no data travels through a pipe until a program > on one side of the pipe has terminated. > No, you plonker! No data is produced *by .read()* until the writer has closed it. I really don't remember anyone in recent history as eager to willfully misunderstand any attempted assistance. Please try to read what is written more carefully. It's most annoying when "the better the advice the worse it's wasted", as the Scots say. Please forgive my brusqueness. 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 stefan.behnel-n05pAM at web.de Mon Jul 16 04:50:40 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 16 Jul 2007 10:50:40 +0200 Subject: Fetching a clean copy of a changing web page In-Reply-To: <5g0g5hF3egi7pU1@mid.uni-berlin.de> References: <5g0g5hF3egi7pU1@mid.uni-berlin.de> Message-ID: <469B3160.3060306@web.de> Diez B. Roggisch wrote: > John Nagle wrote: >> I'm reading the PhishTank XML file of active phishing sites, >> at "http://data.phishtank.com/data/online-valid/" This changes >> frequently, and it's big (about 10MB right now) and on a busy server. >> So once in a while I get a bogus copy of the file because the file >> was rewritten while being sent by the server. >> >> Any good way to deal with this, short of reading it twice >> and comparing? > > Apart from that - the only thing you could try is to apply a SAX parser > on the input stream immediatly, so that at least if the XML is non-valid > because of the way they serve it you get to that ASAP. Sure, if you want to use lxml.etree, you can pass the URL right into etree.parse() and it will throw an exception if parsing from the URL fails to yield a well-formed document. http://codespeak.net/lxml/ http://codespeak.net/lxml/dev/parsing.html BTW, parsing and serialising it back to a string is most likely dominated by the time it takes to transfer the document over the network, so it will not be much slower than reading it using urlopen() and the like. Stefan From kai.kuehne at gmail.com Wed Jul 25 22:07:37 2007 From: kai.kuehne at gmail.com (Kai Kuehne) Date: Thu, 26 Jul 2007 04:07:37 +0200 Subject: Keyword argument 'from'; invalid syntax In-Reply-To: References: Message-ID: Hi Steven, On 7/26/07, Steven D'Aprano wrote: > On Thu, 26 Jul 2007 03:33:20 +0200, Kai Kuehne wrote: > Try this: > > magnolia.bookmarks_find(**d) This works perfectly, thank you guys. Kai From arkanes at gmail.com Fri Jul 27 08:16:39 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 27 Jul 2007 07:16:39 -0500 Subject: cls & self In-Reply-To: <5gu106F3igd71U1@mid.uni-berlin.de> References: <1185419276.645373.83570@d30g2000prg.googlegroups.com> <5gu106F3igd71U1@mid.uni-berlin.de> Message-ID: <4866bea60707270516v2e7206c0wf1c32d768fe5b63a@mail.gmail.com> On 7/27/07, Diez B. Roggisch wrote: > james_027 schrieb: > > hi, > > > > is cls & self the same thing? > > > > I have seen something like > > > > class A: > > def dosomething(cls): > > #doing something > > > > How is cls & self differ? How is it use? > > cls and self are just names. And you most certainly haven't seen the > above, but this instead: > Quite likely he has seen this, except there followed many other lines and then dosomething = classmethod(dosomething) at the end. This disjoint between where it's declared (and looks like a method) and where it's set to a classmethod was a primary factor behind the decorator syntax, of course. From bdesth.quelquechose at free.quelquepart.fr Sat Jul 14 00:20:33 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 14 Jul 2007 06:20:33 +0200 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: <4697de53$0$29041$426a74cc@news.free.fr> Chris Carlen a ?crit : (snip) > > Why? Why is OOP any better at explaining a state machine to a computer? I don't know if it's "better", but state machines are the historical starting point of OO with the Simula language. > I can write state machines all over the place in C, And even in assembler - so why use C ?-) > which tend to be > the core of most of my embedded programs. I can write them with > hardcoded logic if that seems like the easy thing to do any the > probability of extensive changes is extremely low. They are extremely > easy to read and to code. I have written a table-driven state machine > with arbitrary-length input condition lists. The work was all in > designing the data structures. Which is another approach to OO. When programming in C, you do use structs, don't you ? And you do write functions operating on instances of these structs ? And possibly, turn these structs into ADT ? Well, one possible definition of "objects" is "ADT + polymorphism". > Why would OOP be better? Whoever pretend it's absolutely "better" should be shot down. I do find OO *easier* than pure procedural programming, but I started programming with mostly OO (or at least object-based) languages, and only then learned pure procedural languages (and then bits of functional programming). It's not a matter of being "better", it's a matter of what style fits your brain. If OO doesn't fit your brain, then it certainly won't be "better" *for you*. > Different is not better. Popular is not > better. What the academics say is not better. Less lines of code might > be better, if the priority is ease of programming. and maintenance, and robustness (AFAICT, the defect/LOC ratio is somewhat constant whatever the language, so the less code the less bugs). > Or, less machine > execution time or memory usage might be better, if that is the priority. Indeed. > Until I can clearly understand why one or the other of those goals might > better be realized for a given problem with OOP vs. procedures, I just > don't get it. Seems quite sane. > I will keep an open mind however, that until I work with it for some > time there is still the possibility that I will have some light go on > about OOP. So don't worry, I'm not rejecting your input. > >> Python is a relatively easy language, easier than C++, Java, >> or even Perl. It's quite forgiving. The main implementation, >> CPython, is about 60x slower than C, though, This is a very simplistic - and as such, debatable - assertion IMHO. On my Linux box, a cat-like program is hardly faster in C than in Python (obviously since such a program is IO bound, and both implementations will use the native IO libs), and for quite a few computation-heavy tasks, there are Python bindings to highly optimised C (or C++) libs. So while it's clear that Python is not about raw execution speed, it's usually quite correct for most applicative tasks. And when it isn't, well, it's always possible to recode the critical parts in Pyrex or C. From gagsl-py2 at yahoo.com.ar Mon Jul 23 23:20:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Jul 2007 00:20:52 -0300 Subject: code indentation References: Message-ID: En Mon, 23 Jul 2007 16:53:01 -0300, ...:::JA:::... escribi?: >> If you are using the tokenize module as suggested some time ago, try to >> analyze the token sequence you get using { } (or perhaps begin/end pairs >> in your own language, that are easier to distinguish from a dictionary >> display) and the sequence you get from the "real" python code. Then >> write >> a script to transform one into another: > >> from tokenize import generate_tokens >> from token import tok_name > >from cStringIO import StringIO > >> def analyze(source): > > g = generate_tokens(StringIO(source).readline) > > for toknum, tokval, _, _, _ in g: > > print tok_name[toknum], repr(tokval) > >> I think you basically will have to ignore INDENT, DEDENT, and replace >> NAME+"begin" with INDENT, NAME+"end" with DEDENT. > > So......how can I do this????????????? > I will appreciate any help!!!!! Try with a simple example. Let's say you want to convert this: for x in range(10): begin print x end into this: for x in range(10): print x Using the analyze() function above, the former block (pseudo-python) gives this sequence of tokens: NAME 'for' NAME 'x' NAME 'in' NAME 'range' OP '(' NUMBER '10' OP ')' OP ':' NEWLINE '\n' NAME 'begin' NEWLINE '\n' NAME 'print' NAME 'x' NEWLINE '\n' NAME 'end' ENDMARKER '' The latter block ("real" python) gives this sequence: NAME 'for' NAME 'x' NAME 'in' NAME 'range' OP '(' NUMBER '10' OP ')' OP ':' NEWLINE '\n' INDENT ' ' NAME 'print' NAME 'x' DEDENT '' ENDMARKER '' If you feed this token sequence into untokenize, in response you get a source code equivalent to the "real" python example above. So, to convert your "pseudo" python into the "real" python, it's enough to convert the first token sequence into the second - and from that, you can reconstruct the "real" python code. Converting from one sequence into the other is a programming exercise and has nothing to do with the details of the tokenize module, nor is very Python-specific - looking at both sequences you should figure out how to convert one into the other. (Hint: a few additional newlines are not important) It is even simpler than the example given in the tokenize documentation: - which transforms 3.1416 into Decimal("3.1416") by example. Once you get this simple case working, you may try what happens with this: for x in range(10): begin print x end and this: for x in range(10): begin print x end and later this: for x in range(10): begin print x end You are now using explicit begin/end pairs to group statements, so indentation is no more significant. You may want to preprocess the pseudo-python source, stripping any leading blanks, before using tokenize - else you'll get indentation errors (which are bogus in your pseudo-python dialect). Since this will be your own Python dialect, don't expect that someone else will do the work for you - you'll have to do it yourself. But it's not too dificult if you do the things in small steps. In case you get stuck at any stage and have specific questions feel free to ask. -- Gabriel Genellina From miki.tebeka at gmail.com Fri Jul 20 01:26:46 2007 From: miki.tebeka at gmail.com (Miki) Date: Thu, 19 Jul 2007 22:26:46 -0700 Subject: Script to POST to web page with cookies? In-Reply-To: References: Message-ID: <1184909206.444272.282610@e16g2000pri.googlegroups.com> Hello Gille, > I need to write a script to automate fetching data from a web site: > 1. using the POST method, log on, with login/password saved as cookies > 2. download page and extract relevent information using regexes > 3. log off > 4. wait for a random number of minutes, and GOTO 1 > ... http://wwwsearch.sourceforge.net/mechanize/ HTH, -- Miki http://pythonwise.blogspot.com From dittonamed at gmail.com Thu Jul 26 12:00:44 2007 From: dittonamed at gmail.com (dittonamed) Date: Thu, 26 Jul 2007 09:00:44 -0700 Subject: Scope PyQt question In-Reply-To: <46a8ac97$0$14317$9b622d9e@news.freenet.de> References: <1185457304.755050.308530@z24g2000prh.googlegroups.com> <46a8ac97$0$14317$9b622d9e@news.freenet.de> Message-ID: <1185465644.551059.121810@x40g2000prg.googlegroups.com> On Jul 26, 10:15 pm, Stargaming wrote: > On Thu, 26 Jul 2007 06:41:44 -0700, dittonamed wrote: > > Code pasted below -----> > > > Can anyone out there suggest a way to access the object "p" thats > > started in playAudio() from inside the stopAudio()? I need the object > > reference to use QProcess.kill() on it. The code sample is below. Thanks > > to anyone who helps out =) > > > More comments in the code below ------> > > > from qt import * > > > class Form2(QMainWindow): > > def __init__(self,parent = None,name = None,fl = 0): > > QMainWindow.__init__(self,parent,name,fl) self.statusBar() > > > def playAudio(self): > > p = QProcess(self, 'player') > > playcmd = '/usr/bin/play' > > filename = 'song.ogg' > > p.addArgument(playcmd) > > p.addArgument(filename) > > p.start() > > > def stopAudio(self): > > ''' #This is just to show that i can "see" the object, though > > i > > #dont know how to "access" it > > #the output shows the QProcess object by name... # but how do > > i reference it?? > > allobjs = list(QObject.objectTrees()) for obj in allobjs: > > objName = QObject.name(obj) > > if objName == 'Form2': > > print QObject.children(obj) > > ''' > > > QProcess.kill(NEED THE REFERENCE HERE) > > Answering from a non-Qt point of view (ie. I don't know if there were > cleaner ways using Qt stuff), you have to bind p somewhere not local to > the function. Any attribute of `self` (that's hopefully not used by > QMainWindow) should be fine.- Hide quoted text - > > - Show quoted text - I was having trouble getting that to work and thought it because of event driven nature of gui/qt programming. But i'll give it another go anyway .. any examples? ;-) Im wondering what the "right" way to do this is - the Qt way, or is what you mentioned in fact the "right" way? Can i access the QObject another way or am i barking up the wrong tree? Thanks Stargaming and to anyone else who has some input! Ben From jeff at taupro.com Tue Jul 24 01:30:35 2007 From: jeff at taupro.com (Jeff Rush) Date: Tue, 24 Jul 2007 00:30:35 -0500 Subject: Usergroups Forming: Arizona and Carolina US Regions Message-ID: <46A58E7B.2050202@taupro.com> Two new Python usergroups are being organized! = Arizona = Michael March is starting a group for those in the Flagstaff/Phoenix/Tucson region of Arizona. The first meeting to get organized will be held on *Monday July 30th* at 6:30pm. Location is not yet set -- need input from potential attendees. If you are interested, a mailing list and wiki page have been established: http://mail.python.org/mailman/listinfo/sunpiggies http://wiki.python.org/moin/ValleyOfTheSunPiggies And also a Meetup.com group, where you can sign up to receive automated calendar reminders of group activities. http://python.meetup.com/184/ = North/South Carolina = While there is an existing group TriZPUG for the Raleigh-Durham-Chapel Hill region, a new group is being formed for the *Charlotte and North-Central South Carolina area*. No meetings have yet been scheduled - to participate in discussions join the Google Group: http://groups.google.com/group/charpy = Other Groups = There are 34 states with Python usergroups, leaving 16 without any Python organizations at all -- and this is just in the United States. We would like to encourage the formation of more groups worldwide. If you've been wishing there were meetings near you, step forward and help initiate or revitalize one. There are experienced organizers waiting to mentor you on the mailing list: http://mail.python.org/mailman/listinfo/group-organizers Usergroups are a lot of fun, a source of employment opportunities and a great way to enhance your programming and teaching skills. The Python Software Foundation and the experienced group organizers are ready to support you in your efforts. Jeff Rush Python Advocacy Coordinator From shriphanip at gmail.com Mon Jul 23 05:07:09 2007 From: shriphanip at gmail.com (Shriphani) Date: Mon, 23 Jul 2007 02:07:09 -0700 Subject: python-fam documentation. Message-ID: <1185181629.147654.248420@r34g2000hsd.googlegroups.com> Folks, I am trying to create an app which stares at a file and when the file is altered, the script joins a channel on freenode and reports that the file has been altered. I found a module called python-fam, unfortunately i have been unable to find documentation for it. Can someone please help me ? Thanks, Shriphani Palakodety. From kyosohma at gmail.com Mon Jul 9 11:42:28 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 09 Jul 2007 08:42:28 -0700 Subject: no python install In-Reply-To: <1183994762.455062.170190@j4g2000prf.googlegroups.com> References: <1183994762.455062.170190@j4g2000prf.googlegroups.com> Message-ID: <1183995748.896754.98590@57g2000hsv.googlegroups.com> On Jul 9, 10:26 am, Beethon wrote: > my computer has no puthon installed > i downloaded some sofware that are shiped with .py files > please explain how the programs become workable ? > > thanks Check the softwares' website(s) to see what the dependencies are and download them. You can download Python at www.python.org. Mike From escalation746 at yahoo.com Sun Jul 22 19:51:51 2007 From: escalation746 at yahoo.com (escalation746) Date: Sun, 22 Jul 2007 16:51:51 -0700 Subject: custom plugin architecture: how to see parent namespace? In-Reply-To: References: <1185113192.049692.258310@k79g2000hse.googlegroups.com> Message-ID: <1185148311.431968.148520@m3g2000hsh.googlegroups.com> Wojciech Mu a wrote: > These names don't match. I replaced Valuable() with proper name, > and everything work fine. That was a result of a transcription error when posting to the newsgroup. My actual test code did not have this error but nevertheless did not work. However, copying the code I *did* post to the newsgroup and making that change you pointed out... the code indeed worked as you claimed! Two wrongs making a right? I am sure when I look at this tomorrow it will not work again. :-) -- robin From palmkeith at gmail.com Fri Jul 27 18:10:57 2007 From: palmkeith at gmail.com (Keith) Date: Fri, 27 Jul 2007 22:10:57 -0000 Subject: "struct" module problem w/ pyinstaller Message-ID: <1185574257.284927.217300@k79g2000hse.googlegroups.com> Hello, I am trying to create exectuables on inux using "pyinstaller". I am using pyinstaller-1.3, RHEL 4.4, Python 2.5. The executables fail to run. The problem returned is pertaining to "struct.py" not being able to find the module "_struct". struct.py is located under /usr/local/lib/python-2.5/, and there is a _struct.o (no _struct.py anywhere) located under /usr/local/lib/ python-2.5/lib-dynload. When trying to run the executable, the loader returns: File "/usr/local/lib/python2.5/struct.py", line 30, in ImportError: No module named _struct The line in question is: from _struct import Struct, error I am a python neophyte. If someone could give me some information, I would appreciate it. Thanks! From raims at dot.com Sat Jul 7 13:58:53 2007 From: raims at dot.com (Lawrence Oluyede) Date: Sat, 7 Jul 2007 19:58:53 +0200 Subject: problem with pickle References: <1183830214.845484.116090@o11g2000prd.googlegroups.com> Message-ID: <1i0wcsl.14m3rff1b1nbuuN%raims@dot.com> K Gaur wrote: > this is what the python interpreter returns on giving the basic > command > > >>>pickle.dump(x,f) where x is a tuple and f is a file object > > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'pickle' is not defined > > kindly elucidate what's wrong You should import the module in the local namespace before using it: >>> import pickle >>> pickle.dump -- 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 mkb at incubus.de Sun Jul 8 16:18:06 2007 From: mkb at incubus.de (Matthias Buelow) Date: Sun, 08 Jul 2007 22:18:06 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1183924114.414672.92430@n60g2000hse.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1183841277.333384.188950@g4g2000hsf.googlegroups.com> <1183856442.027967.272530@g4g2000hsf.googlegroups.com> <1183924114.414672.92430@n60g2000hse.googlegroups.com> Message-ID: <5fcv44F3c4l7eU1@mid.dfncis.de> Twisted wrote: > I, for one, have a strong preference for interfaces that let me see > what the hell I'm doing and make it easy to find commands, navigate > the interface, navigate the help, and so forth, while making me resort > to reaching for that help as infrequently as reasonably achievable. These are, of course, not unreasonable wishes. I assume you're programming that software already, given that you're crossposting to various programming-language newsgroups. Very well. We'll eagerly judge you by what you'll come up with. F'up-to: comp.emacs. From jjl at pobox.com Fri Jul 6 14:53:09 2007 From: jjl at pobox.com (John J. Lee) Date: Fri, 06 Jul 2007 18:53:09 GMT Subject: urllib to cache 301 redirections? References: Message-ID: <87wsxds6sq.fsf@pobox.com> "O.R.Senthil Kumaran" writes: > Hi, > There is an Open Tracker item against urllib2 library python.org/sf/735515 > which states that. > urllib / urllib2 should cache the results of 301 (permanent) redirections. > This shouldn't break anything, since it's just an internal optimisation > from one point of view -- but it's also what the RFC (2616, section 10.3.2, first para) says > SHOULD happen. > > I am trying to understand, what does it mean. > Should the original url be avaiable to the user upon request as urllib > automatically calls the redirect_request and provides the redirected url only? urllib2, you mean. Regardless of this bug, Request.get_full_url() should be (and is) whatever URL the request instance was originally constructed with. > I am not completely getting what "cache - redirection" implies and what should > be done with the urllib2 module. Any pointers? When a 301 redirect occurs after a request for URL U, via urllib2.urlopen(U), urllib2 should remember the result of that redirection, viz a second URL, V. Then, when another urllib2.urlopen(U) takes place, urllib2 should send an HTTP request for V, not U. urllib2 does not currently do this. (Obviously the cache -- that is, the dictionary or whatever that stores the mapping from URLs U to V -- should not be maintained by function urlopen itself. Perhaps it should live on the redirect handler.) 302 redirections are temporary and are handled correctly in this respect already by urllib2. John From __peter__ at web.de Thu Jul 5 14:06:16 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Jul 2007 20:06:16 +0200 Subject: Where is the syntax for the dict() constructor ?! References: <468D1D9D.6060002@gmail.com> Message-ID: Neil Cerutti wrote: > On 2007-07-05, Captain Poutine wrote: >> I'm simply trying to read a CSV into a dictionary. >> >> (if it matters, it's ZIP codes and time zones, i.e., >> 35983,CT >> 39161,CT >> 47240,EST >> >> >> >> Apparently the way to do this is: >> >> import csv >> >> dictZipZones = {} >> >> reader = csv.reader(open("some.csv", "rb")) >> for row in reader: >> # Add the row to the dictionary > > In addition to Chris's answer, the csv module can read and write > dictionaries directly. Look up csv.DictReader and csv.DictWriter. DictReader gives one dict per row, with field names as keys. The OP is more likely to want dict(csv.reader(open("some.csv", "rb"))) which produces a dict that maps ZIP codes to time zones. Peter From balu.vemu at gmail.com Wed Jul 25 07:31:22 2007 From: balu.vemu at gmail.com (Bala Subramanyam vemu) Date: Wed, 25 Jul 2007 07:31:22 -0400 Subject: Query on User Authentication modules Message-ID: Hi ALL I have SLES 10 installed on my machine, i wanted to get all the information about the installed " USER authentication modules" for example :: localauthentication or LDAP or even a radius server how can I get the above information in SUSE, do we have any python scripts for that Thanks in advance Subramanyam -------------- next part -------------- An HTML attachment was scrubbed... URL: From spamtrap at dot-app.org Thu Jul 26 20:54:54 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Thu, 26 Jul 2007 20:54:54 -0400 Subject: SQLObject 0.9.1 References: <20070726143614.GI30176@phd.pp.ru> Message-ID: Steve Holden writes: > Sherm Pendley wrote: >> Steve Holden writes: >> >>> Sherm Pendley wrote: >>>> Gerardo Herzig writes: >>>> >>>>> So..at 11:23 we got version 0.7.8...at 11:30 was version 0.8.5...now >>>>> there is a 0.9.1 version?? Have a coffe dude >>>> Sounds more to me like he needs to lay off the coffee, or at least switch >>>> to decaffeinated for a while. :-) >>>> >>> Come on, give Oleg a break. He's maintaining three separate versions >>> in parallel. >> >> What part of ":-)" did you not understand? >> > The part that completely bypassed my sense of humor, I guess. Feel > free to ignore me until further notice :-) If I'm ignoring you, how will I get the notice? :-) I'll stop now... this is getting too silly for even me... sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From steve at holdenweb.com Mon Jul 30 11:51:35 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Jul 2007 11:51:35 -0400 Subject: Bug? exec converts '\n' to newline in docstrings!? In-Reply-To: References: Message-ID: <46AE0907.3090700@holdenweb.com> Edward K Ream wrote: > It looks like both exec and execfile are converting "\n" to an actual > newline > in docstrings! > > Start idle: > > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on > win32 > [rest of signon deleted] > >>>> s = '''\ > strings = 'abc'.split("\n") > ''' >>>> print s > strings = 'abc'.split(" > ") > > I see this in my own calls to exec and execfile. Is this a bug or am I > missing something? > Python is doing exactly what you told it to do. You created a string with triple single-quote delimiters. Nothing in the string literal syntax says that escape sequences will not be actioned, so the literal has a value that includes a newline. This has nothing to do with exec, and I don't believe it will happen with execfile should you create a file with a legal Python program inside it. The problem is because you are trying to represent a Python program as a Python string literal, and doing it incorrectly. What you did is no different from writing: >>> s = '''\ ... This is a string with\nan embedded newline''' >>> print s This is a string with an embedded newline >>> It just doesn't match your expectations, is 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 arkanes at gmail.com Mon Jul 9 13:20:54 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 9 Jul 2007 12:20:54 -0500 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xejjjjtqb.fsf@ruckus.brouhaha.com> References: <7xejjjjtqb.fsf@ruckus.brouhaha.com> Message-ID: <4866bea60707091020p73aa63efx69fb318a7a76e083@mail.gmail.com> On 07 Jul 2007 23:27:08 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: > "Hamilton, William " writes: > > > Why on earth would anyone prefer taking a failure in the field over > > > having a static type check make that particular failure impossible? > > > > Because static typechecking won't make that particular failure > > "impossible," but instead just change it from a type error into a data > > error that may or may not be harder to identify. If your program gets a > > piece of data that breaks it, you'll get a failure in the field. Static > > typechecking won't prevent that. > > I'm not doing a good job explaining that regexp example. Static > checking a la Haskell and ML avoids these problems by: > > 1) noticing through case analysis that you actually handle the > error return (except it looks like you have to use a separate > tool for this in Haskell, sigh); and > > 2) (in Haskell) using monadic types to propagate match results from > one operation to another, automatically taking care of turning > a match failure in a chain of operations into a failure of the > whole chain. > > In Python it's all too common to say > > g1 = re.match(pattern, string) > a = g2.group(0) > g2 = re.match(template % a, other_string) > result = g2.group(1) > > or stuff like that, without bothering to check for match failures, > just because of Python's inconvenient syntax. > I don't think it's the syntax that keeps people from checking for errors. It's more a difference of error handling philosophy - in Python, if you can't do something sensible with an error you just pretend it can't happen and rely on your caller to do something sensible. In a lot of cases, this means that nobody does anything and errors propagate all the way up and thats fine. What you're describing with the type inference solution feels more like Javas checked exceptions to me, where the compiler ends up signaling an error if you don't pretend like you considered the error condition. In Java, at least, this tends to create actively harmful code where you stick in empty or otherwise useless exception handlers to shut up the compiler, and when "can't happen" errors actually do occur they are lost or worse. Maybe this doesn't happen in Haskel, but I'd be interested in how it doesn't. From bdesth.quelquechose at free.quelquepart.fr Sun Jul 15 18:42:41 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 16 Jul 2007 00:42:41 +0200 Subject: questions about functions inside a function In-Reply-To: References: Message-ID: <469be497$0$29872$426a74cc@news.free.fr> Jeremy Sanders a ?crit : > fdu.xiaojf at gmail.com wrote: > > >>What I want is, the value of i should be bounded to the anonymous >>function. And the output should like this: > > ... > >>How to achieve this? > > > This doesn't answer your question (others have), but another (perhaps > clearer) way to do such things is something like > > class MyFunc(object): > """A function object.""" > def __init__(self, val): > self.val = val > > def __call__(self): > """Return value squared""" > return self.val**2 > > a = [] > for i in range(4): > a.append(MyFunc(i)) > > for f in a: > f() > I wouldn't say it's "clearer" - at least in this concrete use case. And it takes more than just defining the __call__ method to have a fully function-like object (hint: try using a MyFunc instance as a method). From rw at smsnet.pl Wed Jul 11 03:37:38 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Wed, 11 Jul 2007 00:37:38 -0700 Subject: bool behavior in Python 3000? In-Reply-To: References: <7xodijdd8r.fsf@ruckus.brouhaha.com> Message-ID: <1184139458.063988.63510@w3g2000hsg.googlegroups.com> Steven D'Aprano wrote: > From a purely functional perspective, bools are unnecessary in Python. I > think of True and False as syntactic sugar. But they shouldn't be > syntactic sugar for 1 and 0 any more than they should be syntactic sugar > for {"x": "foo"} and {}. But `bools` are usefull in some contexts. Consider this: >>> 1 == 1 True >>> cmp(1, 1) 0 >>> 1 == 2 False >>> cmp(1, 2) -1 At first look you can see that `cmp` does not return boolean value what not for all newbies is so obvious. Rob From Muffin at BottomPost.Trim Thu Jul 19 22:27:07 2007 From: Muffin at BottomPost.Trim (Muffin) Date: Thu, 19 Jul 2007 22:27:07 -0400 Subject: Newbie: freebsd admin scripting In-Reply-To: References: Message-ID: <46A01D7B.3040502@BottomPost.Trim> Thx for the advise. From sla29970 at gmail.com Tue Jul 3 12:50:06 2007 From: sla29970 at gmail.com (sla29970 at gmail.com) Date: Tue, 03 Jul 2007 16:50:06 -0000 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: <7xbqethpr8.fsf@ruckus.brouhaha.com> References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> <7x645al8kc.fsf@ruckus.brouhaha.com> <1182894003.920335.317620@a26g2000pre.googlegroups.com> <7x7ipoy6cf.fsf@ruckus.brouhaha.com> <1183041149.275562.114490@o11g2000prd.googlegroups.com> <7xbqethpr8.fsf@ruckus.brouhaha.com> Message-ID: <1183481406.243354.139830@e16g2000pri.googlegroups.com> On Jul 3, 1:10 am, Paul Rubin wrote: > Well, if you're trying to pick just one timestamp standard, I'd say > you're better off using a worldwide one rather than a national one, no > matter how the bureaucracies work. TAI is derived from atomic clocks > all over the world, while the national metrology labs are more subject > to error and desynchronization, and whatever legal primacy they have > is good in only one country. For the purposes of an operational system there is an important difference between a time scale which is practically available in real time and a time scale which is not available until next month. There is no available source for TAI, and in the current scheme of things there cannot be one for there is no mechanism for distributing it. There are two reasonably reliable worldwide time sources right now: Russia's GLONASS and US GPS. GPS time is based on UTC(USNO). UTC(USNO) is TA(USNO) minus leap seconds. Note that is TA(USNO), not TAI(USNO), for USNO cannot define anything named TAI. From bignose+hates-spam at benfinney.id.au Thu Jul 26 02:24:32 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Jul 2007 16:24:32 +1000 Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> <87ps2ghtd7.fsf@benfinney.id.au> <1185412639.075218.186290@z24g2000prh.googlegroups.com> <1185426066.162458.187050@z28g2000prd.googlegroups.com> Message-ID: <87zm1jhecf.fsf@benfinney.id.au> "mensanator at aol.com" writes: > On Jul 25, 9:04?pm, Steven D'Aprano > wrote: > Why does it make no sense? Have you never had to scrape a web page > or read a CSV file? Again, unrelated to the way the Python compiler syntactically treats the source code. > So this proposal would only apply to string literals at compile > time, not running programs? Exactly the same way that it works for string literals in source code: once the source code is compiled, the literal is indistinguishable from the same value written a different way. > And I want the same error to occur if my CSV parser tries to convert > '123 456' into a single number. I don't want it to assume the > number is '123456'. Once again, this is a discussion about Python syntax, not the behaviour of the csv module. -- \ "I always had a repulsive need to be something more than | `\ human." -- David Bowie | _o__) | Ben Finney From Succelus at gmail.com Mon Jul 16 19:16:22 2007 From: Succelus at gmail.com (Succelus at gmail.com) Date: Mon, 16 Jul 2007 16:16:22 -0700 Subject: How to organize control access to source code ? In-Reply-To: References: <1184618776.798929.98960@57g2000hsv.googlegroups.com> Message-ID: <1184627782.951682.77870@n2g2000hse.googlegroups.com> On 16 juil, 21:10, Erik Jones wrote: > On Jul 16, 2007, at 3:46 PM, Succe... at gmail.com wrote: > > > Hello, > > How can we organize development team with code source control policy, > > that limit access to some portion of code ? > > The specifics largely depend on the system(s) you're working with > but, basically (sic), you need to read up on filesystem level > permissions. > Thanks for your response, But I want to know if there is a process or best practices, to give not the access to all of the project. in other words, must every developer work on the entire copy of the project locally ? Or to work just on his module and manage a process of integration, and if there is any Agile practices for this problem. From arkanes at gmail.com Wed Jul 11 18:14:43 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 11 Jul 2007 17:14:43 -0500 Subject: storing pickles in sql data base In-Reply-To: References: <592087469.jZQWuvoN0q@teancum> Message-ID: <4866bea60707111514q6962b447sd965a0d4f5c57469@mail.gmail.com> On 7/11/07, Nick Craig-Wood wrote: > David Bear wrote: > > I need to store pickled objects in postgresql. I reading through the pickle > > docs it says to always open a file in binary mode because you can't be sure > > if the pickled data is binary or text. So I have 2 question. Can I set the > > pickle to be text -- and then store it in a 'text' type field in my sql > > table, or should what sql type should I save the pickle as? > > You could always encode it into text form, eg > > >>> from cPickle import dumps, loads > >>> a = range(10) > >>> a > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > >>> b = dumps(a).encode("zip").encode("base64").strip() > >>> b > 'eJzTyCkw5PI04Er0NARiIyA2BmITIDYFYjMgNgdiCyC25ErUAwD5DQqD' > >>> loads(b.decode("base64").decode("zip")) > [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] > >>> > Protocol 0 (the default) is a text protocol, it's safe to store in a text field or write to a text file. base64 encoding will work on protocol 1 and 2 (which are binary protocols and not text-safe), but doing that removes the main benefit of the higher protocols, which is smaller pickle data. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jul 18 03:45:20 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 18 Jul 2007 09:45:20 +0200 Subject: Design question regarding exceptions. In-Reply-To: <1184701939.282684.260730@o11g2000prd.googlegroups.com> References: <1184701939.282684.260730@o11g2000prd.googlegroups.com> Message-ID: <469dc505$0$27893$426a74cc@news.free.fr> asincero a ?crit : > I have a class called Users that provides a higher level of > abstraction to an underlying "users" table in a pgsql database. It > has methods like "addUser()" and "deleteUser()" which, obviously, wrap > the corresponding SQL statements. My question is would it better to > let any exceptions thrown by the underlying DB-API calls bubble up > from these methods, or should I catch them inside the methods, wrap > them inside my own custom exceptions, and throw those exceptions > instead? There's no absolute answer to this. But unless your "abstraction layer" is supposed to be usable with non-DB-API backends (ie: text files, LDAP, etc), I don't see any reason to abstract the exceptions. From 27828964011 at vodamail.co.za Sun Jul 22 14:22:39 2007 From: 27828964011 at vodamail.co.za (David Manti) Date: Sun, 22 Jul 2007 18:22:39 -0000 Subject: http://www.tbn.org/films/videos/To_Hell_And_Back.ram << GREAT VIDEO! Message-ID: <000101c7fc78$d18d1e30$b781310a@private86fd040> An HTML attachment was scrubbed... URL: From phd at phd.pp.ru Thu Jul 26 10:30:35 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 26 Jul 2007 18:30:35 +0400 Subject: SQLObject 0.8.5 Message-ID: <20070726143035.GF30176@phd.pp.ru> Hello! I'm pleased to announce the 0.8.5 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.8.5 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.8.4 ---------------- Bug Fixes ~~~~~~~~~ * Replaced calls to style.dbColumnToPythonAttr() in joins.py by name/dbName lookup in case the user named columns differently using dbName. * Minor correction in the tests: we fully support EnumCol in Postgres. * MySQLConnection now recognizes Enum, Double and Time columns when drawing the database scheme from DB. * Minor fix in FirebirdConnection.fromDatabase. * Fixed a bug with default field values for columns for firebird connection. * Prevent a deadlock in declarative.threadSafeMethod() by not reacquiring the class lock. * Run post_funcs after sending RowCreatedSignal. * Suppress the second RowUpdateSignal in .set() called from ._SO_setValue(). * Fixed a bug in col.createSQL(). * Fixed a bug in converting date/time for years < 1000 (time.strptime() requires exactly 4 digits for %Y, hence a year < 1000 must be 0-padded). Other Changes ~~~~~~~~~~~~~ * Changed string quoting style for PostgreSQL and MySQL from \' to ''. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From bsneddon at yahoo.com Thu Jul 5 16:34:13 2007 From: bsneddon at yahoo.com (bsneddon) Date: Thu, 05 Jul 2007 13:34:13 -0700 Subject: XQuery module for Python Message-ID: <1183667653.152640.192570@n2g2000hse.googlegroups.com> Does anyone know of a module for Python XML that includes XQuery? http://www.w3.org/XML/Query/ It seem like it would be very useful. Is there a down side to XQuery that has prevented it from being incorporated into some of the Python XML offerings? I have googled this some and have not seen answer to my above questions. Bill From zxo102 at gmail.com Tue Jul 17 00:59:12 2007 From: zxo102 at gmail.com (zxo102) Date: Tue, 17 Jul 2007 04:59:12 -0000 Subject: Is it possible to run two "while 1:" loops in two threadings respectively? Message-ID: <1184648352.400425.322440@e9g2000prf.googlegroups.com> Hi, I would like to combine two python applications into a single one with two threadings. Both of them have a "while 1:" loop respectively. For example, one application is to monitoring serial port 'com1' and another application is a TCP/IP server which has used threadings already. I write the following demo code but it does not work right. It stays in the first "while 1:" and never thingOne.start(). The second threading never be started. Any ideas? Thanks a lot. Ouyang ################################################################# import threading, time class serial_port_com1: def spc(self): i = 0 while 1: time.sleep(5) print "%d: hello, I am here in spc()"%i i += 1 class TCP_IP: def tcpip(self): i = 0 while 1: time.sleep(5) print "%d: hello, I am here in tcpip()"%i i += 1 class ThreadOne ( threading.Thread ): def run ( self ): print 'Thread', self.getName(), 'started.' time.sleep ( 5 ) print 'Thread', self.getName(), 'ended.' class ThreadTwo ( threading.Thread ): def run ( self ): print 'Thread', self.getName(), 'started.' thingOne.join() print 'Thread', self.getName(), 'ended.' if __name__=="__main__": spc = serial_port_com1() tcpip = TCP_IP() thingOne = ThreadOne(target=spc.spc()) thingOne.start() thingTwo = ThreadTwo(target=tcpip.tcpip()) thingTwo.start() From uriel.katz at gmail.com Mon Jul 2 23:45:04 2007 From: uriel.katz at gmail.com (urielka) Date: Tue, 03 Jul 2007 03:45:04 -0000 Subject: object references/memory access In-Reply-To: <1183428795.334268.36630@e9g2000prf.googlegroups.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1183407411.397142.304790@e16g2000pri.googlegroups.com> <1183417108.245203.158830@x35g2000prf.googlegroups.com> <1183428795.334268.36630@e9g2000prf.googlegroups.com> Message-ID: <1183434304.491595.217280@k79g2000hse.googlegroups.com> if both the search server and the web server/script are in the same computer you could use POSH(http://poshmodule.sourceforge.net/) for memory sharing or if you are in UNIX you can use mmap. this is way faster than using sockets and doesn`t require the serialization/deserialization step. From gagsl-py2 at yahoo.com.ar Tue Jul 24 20:09:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Jul 2007 21:09:06 -0300 Subject: Trouble with email package References: <87r6n8foqd.fsf@wilson.homeunix.com> <87myxwfoap.fsf@wilson.homeunix.com> <1185264631.132295.119800@w3g2000hsg.googlegroups.com> Message-ID: En Tue, 24 Jul 2007 05:10:31 -0300, Harel escribi?: > What was the solution you found? > Could you please post it? I'm having the same problem... ;o( > > On Jul 16, 2:53 pm, Torsten Bronger > wrote: >> >> > The Content-Transfer-Encoding is wrong. Okay (well, not okay but) >> > then I added message["Content-Transfer-Encoding"] = "8bit" to my >> > code and got >> >> > Content-Type: text/plain; charset="utf-8" >> > MIME-Version: 1.0 >> > Content-Transfer-Encoding: base64 >> > Content-Transfer-Encoding: 8bit In case he's not reading anymore, this is an extract from the Message class documentation : __setitem__(name, val): Add a header to the message [...] Note that this does not overwrite or delete any existing header with the same name. If you want to ensure that the new header is the only one present in the message with field name name, delete the field first, e.g.: del msg['subject'] msg['subject'] = 'Python roolz!' See also the add_header and replace_header methods. -- Gabriel Genellina From bbxx789_05ss at yahoo.com Sat Jul 28 17:26:53 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 28 Jul 2007 14:26:53 -0700 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1184466882.446791.127670@x35g2000prf.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> <1184458002.961657.267830@x35g2000prf.googlegroups.com> <1184466882.446791.127670@x35g2000prf.googlegroups.com> Message-ID: <1185658013.859359.47700@57g2000hsv.googlegroups.com> On Jul 14, 8:34 pm, Graham Dumpleton wrote: > On Jul 15, 10:06 am, Graham Dumpleton > wrote: > > > > > On Jul 15, 2:47 am, 7stud wrote: > > > > Themod_pythonmanual says this under section 2.1 Prerequisites: > > > > ------ > > > In order to compilemod_pythonyou will need to have the include files > > > for both Apache and Python, as well as the Python library installed on > > > your system. If you installed Python and Apache from source, then you > > > already have everything needed. However, if you are using prepackaged > > > software (e.g. Red Hat Linux RPM, Debian, or Solaris packages from > > > sunsite, etc) then chances are, you have just the binaries and not the > > > sources on your system. Often, the Apache and Python include files and > > > libraries necessary to compilemod_pythonare part of separate > > > ``development'' package. If you are not sure whether you have all the > > > necessary files, either compile and install Python and Apache from > > > source, or refer to the documentation for your system on how to get > > > the development packages. > > > ----- > > > > I installed Apache from source using these instructions: > > > >http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-o... > > > > but I used a package to install python 2.4. The package was from > > > here: > > > >http://www.pythonmac.org/packages/ > > > > and it's a "Universal binary version of Python that runs natively on > > > PPC and Intel systems." > > > > But my mac came with Python 2.3.5 pre-installed, so I wonder if I > > > already have the necessary "include files for both Apache and Python, > > > as well as the Python library" already installed. > > > Have you actually tried to installmod_python? That would be the > > quickest way of finding out. > > > Because you are using an alternate Apache than the OS supplied one, > > you will need to use the --with-apxs option to configure when building > > Python. > > Whoops, --with-apxs option is to configure formod_python, not Python. > > > Unless you really need Python 2.4, it is easier to use the OS > > supplied version of Python. If you must use an alternate version, use > > the --with-python option to configure formod_pythonto tell it which > > version. Depending on where that Python version is installed, you may > > also have to fiddle the Apache 'envvars' file as well to get it to > > work. > > > Graham Hi, Thanks for the response. Sorry, I didn't respond in a timely manner. I thought I would give your suggestion a shot and just try installing mod_python and see what happens, so I installed mod_python 3.3.1 with this command: $ ./configure --with-apxs=/Library/Apache2/bin/apxs Here is the output: -------- checking for gcc... gcc checking for C compiler default output file name... a.out checking whether the C compiler works... yes checking whether we are cross compiling... no checking for suffix of executables... checking for suffix of object files... o checking whether we are using the GNU C compiler... yes checking whether gcc accepts -g... yes checking for gcc option to accept ANSI C... none needed checking for ar... ar checking for a BSD-compatible install... /usr/bin/install -c checking whether make sets $(MAKE)... yes checking for main in -lm... yes checking for an ANSI C-conforming const... yes checking your blood pressure... a bit high, but we can proceed configure: checking whether apxs is available... checking for --with-apxs... /Library/Apache2/bin/apxs executable, good checking Apache version... 2.2.4 checking for Apache libexec directory... /Library/Apache2/modules checking for Apache include directory... -I/Library/Apache2/include checking for --with-python... no checking for python... /Library/Frameworks/Python.framework/Versions/ Current/bin/python checking Python version... 2.4 checking Python install prefix... /Library/Frameworks/Python.framework/ Versions/2.4 checking checking where python libraries are installed... /Library/ Frameworks/Python.framework/Versions/2.4/lib/python2.4 checking what libraries Python was linked with... -framework Python -ldl checking linker flags used to link Python... checking where Python include files are... -I/Library/Frameworks/ Python.framework/Versions/2.4/include/python2.4 checking for --with-python-src... no checking for --with-mutex-dir... no Using MUTEX_DIR /tmp checking for --with-max-locks... no Using 8 MAX_LOCKS. checking for --with-flex... no checking for flex... /usr/bin/flex found /usr/bin/flex, we'll use this. Use --with-flex to specify another. checking flex version... configure: WARNING: Flex version 2.5.4 found. Version 2.5.31 or greater is required. You can generally ignore this warning unless you need to regenerate psp_parser.c from psp_parse.l. If you do need regenerate psp_parser.c, use --with-flex to specify the location of the correct flex version. See the README for more information. configure: creating ./config.status config.status: creating Makefile config.status: creating src/Makefile config.status: creating Doc/Makefile config.status: creating src/include/mod_python.h config.status: creating test/Makefile config.status: creating test/testconf.py config.status: creating dist/setup.py config.status: creating dist/Makefile ----- So it looks like it installed fine--although I notice it picked up python 2.4 and you said it was easier to install mod_python using the pre-installed python 2.3.3. Then I tried to test the installation following the test in the mod_python manual, which says to add the following to Apache's http.conf file: AddHandler mod_python .py PythonHandler mptest PythonDebug On I did that, but when I started Apache, I got this error: --- Syntax error on line 474 of /Library/Apache2/conf/httpd.conf: Invalid command 'PythonHandler', perhaps misspelled or defined by a module not included in the server configuration --- Any ideas what went wrong? Thanks From stefan.behnel-n05pAM at web.de Mon Jul 16 04:06:47 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 16 Jul 2007 10:06:47 +0200 Subject: getting text inside the HTML tag In-Reply-To: <469b225c$0$2315$426a74cc@news.free.fr> References: <1184436087.239958.228710@r34g2000hsd.googlegroups.com> <469b225c$0$2315$426a74cc@news.free.fr> Message-ID: <469b2717$0$31624$9b4e6d93@newsspool3.arcor-online.net> Bruno Desthuilliers wrote: > kyosohma at gmail.com a ?crit : >> On Jul 14, 12:47 pm, Nikola Skoric wrote: >>> I'm using sgmllib.SGMLParser to parse HTML. I have successfuly parsed >>> start >>> tags by implementing start_something method. But, now I have to fetch >>> the >>> string inside the start tag and end tag too. I have been reading through >>> SGMLParser documentation, but just can't figure that out... can somebody >>> help? :-) >>> >>> -- >>> "Now the storm has passed over me >>> I'm left to drift on a dead calm sea >>> And watch her forever through the cracks in the beams >>> Nailed across the doorways of the bedrooms of my dreams" >> >> Oi! Try Beautiful Soup instead. That seems to be the defacto HTML >> parser for Python: > > Nope. It's the defacto parser for HTML-like tag soup !-) Very true. As long as you're dealing with something that looks pretty much like HTML, I actually don't think you can beat lxml.html (and it's still getting better every day). Stefan From gh at gregor-horvath.com Wed Jul 25 15:14:08 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Wed, 25 Jul 2007 21:14:08 +0200 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185385374.866372.198520@x35g2000prf.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> Message-ID: walterbyrd schrieb: > Don't get me wrong: I am not saying that PHP is better than Python for > web-development. But, I sometimes think that Python could learn a few > things from PHP. Yes, indeed we can learn that popularity is not superiority. ;-) Gregor From apt.shansen at gmail.com Wed Jul 18 01:02:31 2007 From: apt.shansen at gmail.com (Stephen Hansen) Date: Tue, 17 Jul 2007 22:02:31 -0700 Subject: wxPython, threads, and search engine In-Reply-To: <1184723659.204544.229000@x35g2000prf.googlegroups.com> References: <1184723659.204544.229000@x35g2000prf.googlegroups.com> Message-ID: <7a9c25c20707172202y1d581f42w42c5588d78aaceb9@mail.gmail.com> I'm assuming you're accessing this Queue in an idle loop maybe? How many items do you get out of it before you pass and wait for a re-invocation? Either way, you can try calling 'wx.Yield()' after each add to the GUI or every few or such, so the GUI can process events. On 7/17/07, Benjamin wrote: > > I'm writing a search engine in Python with wxPython as the GUI. I have > the actual searching preformed on a different thread from Gui thread. > It sends it's results through a Queue to the results ListCtrl which > adds a new item. This works fine or small searches, but when the > results number in the hundreds, the GUI is frozen for the duration of > the search. I suspect that so many search results are coming in that > the GUI thread is too busy updating lists to respond to events. I've > tried buffer the results so there's 20 results before they're sent to > the GUI thread and buffer them so the results are sent every .1 > seconds. Nothing helps. Any advice would be great. > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jzgoda at o2.usun.pl Tue Jul 24 05:13:18 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 24 Jul 2007 11:13:18 +0200 Subject: Where do they tech Python officialy ? In-Reply-To: <7x8x96fa3q.fsf@ruckus.brouhaha.com> References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> <1185265091.276958.239910@r34g2000hsd.googlegroups.com> <7x8x96fa3q.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin napisa?(a): >> 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. > > Why would you want to become a programmer? Programmers smell bad, > they have no social life, they get treated like crap by everyone. > They can get paid pretty well but then they spend all the money on > useless electronic junk so they still live like bums. There is only > one reason to be a programmer, which is that the drive to program > burns in you like a fire. But in that case don't ask how to become a > programmer, because you are already one, so welcome to the ranks ;-). +1 QOTW -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From rcdailey at gmail.com Fri Jul 6 12:00:07 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 06 Jul 2007 16:00:07 -0000 Subject: Expandable 2D Dictionaries? In-Reply-To: <5f76ugF3b6hheU1@mid.uni-berlin.de> References: <1183736635.415927.208450@57g2000hsv.googlegroups.com> <5f76ugF3b6hheU1@mid.uni-berlin.de> Message-ID: <1183737607.466894.62780@o61g2000hsh.googlegroups.com> On Jul 6, 10:54 am, "Diez B. Roggisch" wrote: > Robert Dailey wrote: > > Hi, > > > I am interested in creating an expandable (dynamic) 2D dictionary. For > > example: > > > myvar["cat"]["paw"] = "Some String" > > > The above example assumes "myvar" is declared. In order for this to > > work, I have to know ahead of time the contents of the dictionary. For > > the above to work, my declaration must look like: > > > myvar = {"cat": {"paw":""} } > > > I would like to not have to declare my dictionary like this, as it > > does not allow it to be expandable. I'm very new to Python (I'm a > > professional C++ programmer. Any comparisons to C++ would help me > > understand concepts). > > > Is there a way that when I index into my dictionary using an "unknown" > > index (string), that python will dynamically add that key/value pair? > > Not really, unless you know that the first level of values are _always_ > dicts. > > What you can do is to use > > myvar.setdefault('cat', {})['paw'] = "Some String" > > Diez Could you emphasize what you mean by "unless you know that the first level of values are _always_ dicts."? Could I create a class wrapper that automates this? I could have an insert() method of some sort. However I would have to research if it's possible to overload operators in python. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 17 08:35:03 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 17 Jul 2007 14:35:03 +0200 Subject: a=0100; print a ; 64 how to reverse this? In-Reply-To: <1184670575.205759.115360@i13g2000prf.googlegroups.com> References: <1184670575.205759.115360@i13g2000prf.googlegroups.com> Message-ID: <469cb76f$0$7584$426a34cc@news.free.fr> mosi a ?crit : > Problem: > how to get binary from integer and vice versa? > The simplest way I know is: > a = 0100 > a > 64 > > but: > a = 100 (I want binary number) > does not work that way. > > a.__hex__ exists > a.__oct__ exists > > but where is a.__bin__ ??? > > > What`s the simplest way to do this? bruno at bruno:~$ 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. >>> help(int) Help on class int in module __builtin__: class int(object) | int(x[, base]) -> integer | | Convert a string or number to an integer, if possible. A floating point | argument will be truncated towards zero (this does not include a string | representation of a floating point number!) When converting a string, use | the optional base. It is an error to supply a base when converting a | non-string. If the argument is outside the integer range a long object | will be returned instead. >>> a = int('100', 2) >>> a 4 >>> HTH From benc.nospam at gmail.com Tue Jul 3 10:25:02 2007 From: benc.nospam at gmail.com (Ben Cartwright) Date: Tue, 03 Jul 2007 07:25:02 -0700 Subject: mysteries of urllib/urllib2 In-Reply-To: <1183470239.153444.244700@j4g2000prf.googlegroups.com> References: <1183470239.153444.244700@j4g2000prf.googlegroups.com> Message-ID: <1183472702.932557.108600@n2g2000hse.googlegroups.com> On Jul 3, 9:43 am, Adrian Smith wrote: > The following (pinched > from Dive Into Python) seems to work perfectly in Idle, but falls at > the final hurdle when run as a cgi script - can anyone suggest > anything I may have overlooked? > > request = urllib2.Request(some_URL) > request.add_header('User-Agent', 'some_plausible_string') > opener = urllib2.build_opener() > data = opener.open(request).read() Most likely the account that cgi script is running as does not have permissions to access the net. Check the traceback to be sure. Put this at the top of your cgi script: import cgitb; cgitb.enable() --Ben From carsten at uniqsys.com Tue Jul 17 00:05:59 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 17 Jul 2007 00:05:59 -0400 Subject: Fetching a clean copy of a changing web page In-Reply-To: References: <1184566190.197725.296610@n60g2000hse.googlegroups.com> Message-ID: <1184645159.3245.26.camel@localhost.localdomain> On Tue, 2007-07-17 at 00:47 +0000, John Nagle wrote: > Miles wrote: > > On Jul 16, 1:00 am, John Nagle wrote: > > > >> I'm reading the PhishTank XML file of active phishing sites, > >>at "http://data.phishtank.com/data/online-valid/" This changes > >>frequently, and it's big (about 10MB right now) and on a busy server. > >>So once in a while I get a bogus copy of the file because the file > >>was rewritten while being sent by the server. > >> > >> Any good way to deal with this, short of reading it twice > >>and comparing? > >> > >> John Nagle > > > > > > Sounds like that's the host's problem--they should be using atomic > > writes, which is usally done be renaming the new file on top of the > > old one. How "bogus" are the bad files? If it's just incomplete, > > then since it's XML, it'll be missing the "" and you should > > get a parse error if you're using a suitable strict parser. If it's > > mixed old data and new data, but still manages to be well-formed XML, > > then yes, you'll probably have to read it twice. > > The files don't change much from update to update; typically they > contain about 10,000 entries, and about 5-10 change every hour. So > the odds of getting a seemingly valid XML file with incorrect data > are reasonably good. Does the server return a reliable last-modified timestamp? If yes, you can do something like this: prev_last_mod = None while True: u = urllib.urlopen(theUrl) if prev_last_mod==u.headers['last-modified']: break prev_last_mod = u.headers['last-modified'] contents = u.read() u.close() That way, you only have to re-read the file if it actually changed according to the time stamp, rather than having to re-read in any case just to check whether it changed. HTH, -- Carsten Haese http://informixdb.sourceforge.net From gagsl-py2 at yahoo.com.ar Mon Jul 16 13:14:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 16 Jul 2007 14:14:25 -0300 Subject: Re-raising exceptions with modified message References: <1183863713.876365.111820@57g2000hsv.googlegroups.com> <1184239885.828717.271410@r34g2000hsd.googlegroups.com> <1184258925.321462.50270@k79g2000hse.googlegroups.com> <1184345588.791872.79010@d55g2000hsg.googlegroups.com> <1184604650.131033.288000@o11g2000prd.googlegroups.com> Message-ID: En Mon, 16 Jul 2007 13:50:50 -0300, fumanchu escribi?: > On Jul 15, 2:55 am, Christoph Zwerschke wrote: >> Here is a simple solution, but it depends >> on the existence of the args attribute that >> "will eventually be deprecated" according >> to the docs > > If you don't mind using .args, then the solution is usually as simple > as: > > > try: > Thing.do(arg1, arg2) > except Exception, e: > e.args += (Thing.state, arg1, arg2) > raise > > > No over-engineering needed. ;) If you read enough of this long thread, you'll see that the original requirement was to enhance the *message* displayed by a normal traceback - the OP has no control over the callers, but wants to add useful information to any exception. Your code does not qualify: py> try: ... open("a file that does not exist") ... except Exception,e: ... e.args += ("Sorry",) ... raise ... Traceback (most recent call last): File "", line 2, in IOError: [Errno 2] No such file or directory: 'a file that does not exist' py> try: ... x = u"?".encode("ascii") ... except Exception,e: ... e.args += ("Sorry",) ... raise ... Traceback (most recent call last): File "", line 2, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 0: ordinal not in range(128) -- Gabriel Genellina From carsten at uniqsys.com Sun Jul 22 14:37:34 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 22 Jul 2007 14:37:34 -0400 Subject: Where is the collections module? In-Reply-To: References: Message-ID: <1185129454.3159.19.camel@localhost.localdomain> On Sun, 2007-07-22 at 14:24 -0400, Gordon Airporte wrote: > I was going to try tweaking defaultdict, but I can't for the life of me > find where the collections module or its structures are defined. Python 2.5. It's written in C. You'll find it in the Python2.5 source code at /path/to/source/Modules/collectionsmodule.c -- Carsten Haese http://informixdb.sourceforge.net From tazmaster at rocketmail.com Tue Jul 10 00:21:22 2007 From: tazmaster at rocketmail.com (Jim Langston) Date: Mon, 9 Jul 2007 21:21:22 -0700 Subject: 2**2**2**2**2 wrong? Bug? Message-ID: In Python 2.5 on intel, the statement 2**2**2**2**2 evaluates to >>> 2**2**2**2**2 20035299304068464649790723515602557504478254755697514192650169737108940595563114 53089506130880933348101038234342907263181822949382118812668869506364761547029165 04187191635158796634721944293092798208430910485599057015931895963952486337236720 30029169695921561087649488892540908059114570376752085002066715637023661263597471 44807111774815880914135742720967190151836282560618091458852699826141425030123391 10827360384376787644904320596037912449090570756031403507616256247603186379312648 47037437829549756137709816046144133086921181024859591523801953310302921628001605 68670105651646750568038741529463842244845292537361442533614373729088303794601274 72495841486491593064725201515569392262818069165079638106413227530726714399815850 88112926289011342377827055674210800700652839633221550778312142885516755540733451 07213112427399562982719769150054883905223804357045848197956393157853510018992000 02414196370681355984046403947219401606951769015611972698233789001764151719005113 34663068981402193834814354263873065395529696913880241581618595611006403621197961 01859534802787167200122604642492385111393400464351623867567078745259464670903886 54774348321789701276445552940909202195958575162297333357615955239488529757995402 84719435299135437637059869289137571537400019863943324648900525431066296691652434 19174691389632476560289415199775477703138064781342309596190960654591300890188887 58808473362595606544488850144733570605881709016210849971452956834406197969056546 98136311620535793697914032363284962330464210661362002201757878518574091620504897 11781820400187282939943446186224328009837323764931814789848119452713007440220765 68091037620399920349202390662626449190916798546151577883906039772075927937885224 12943010174580868622633692847258514030396155585643303854506886522131148136384083 84778263790459607186876728509763471271988890680478243230394718650525660978150729 86114143030581692792497140916105941718535227588750447759221830115878070197553572 22414000195481020056617735897814995323252085897534635470077866904064290167638081 61740550405117670093673202804549339027992491867306539931640720492238474815280619 16690093380573212081635070763435166986962502096902316285935007187419057916124153 68975148082619048479465717366010058924766554458408383347905441448176842553272073 15586349347605137419779525190365032198020108764738368682531025183377533908861426 18480037400808223810407646887847164755294532694766170042446106331123802113458869 45322001165640763270230742924260515828110703870183453245676356259514300320374327 40780879056283663406965030844225855967039271869461158513793386475699748568670079 82396060439347885086164926030494506174341236582835214480672667684180708375486221 14082365798029612000274413244384324023312574035450193524287764308802328508558860 89962774458164680857875115807014743763867976955049991643998284357290415378143438 84730348426190338884149403136613985425763557710533558020662218557706008255128889 33322264362819848386132395706761914096385338323743437588308592337222846442879962 45605476932428998432652677378373173288063210753211238680604674708428051166488709 08477029120816110491255559832236624486855665140268464120969498259056551921618810 43412268389962830716548685255369148502995396755039549383718534059000961874894739 92880432496373165753803673586710175783994818471798498246948060532081996066183434 01247609663951977802144119975254670408060849934417825628509272652370989865153946 21930046073645079262129759176982938923670151709920915315678144397912484757062378 04600009918293321306880570046591458387208088016887445835557926258465124763087148 56631352893416611749061752667149267217612833084527393646924458289257138887783905 63004824837998396920292222154861459023734782226825216399574408017271441461795592 26175083889020074169926238300282286249284182671243405751424188569994272331606998 71298688277182061721445314257494401506613946316919762918150657974552623619122484 80638900336690743659892263495641146655030629659601997206362026035219177767406687 77463549375318899587866282125469797102065747232721372918144666659421872003474508 94283091153518927111428710837615922238027660532782335166155514936937577846667014 57179719012271178127804502400263847587883393968179629506907988171216906869295382 48529830023476068454114178139110648560236549754227497231007615131870024053910510 91381784372179142252858743209852495787803468370333781842144401713868812424998441 86181292711985333153825673218704215306311977485352146709553346263366108646673322 92409879849256691109516143618601548909740241913509623043612196128165950518666022 03071561368473236466086890501426391390651506390819937885231836505989729912540447 94434251667742996598118492331515552728832740283526884424087528112832899806259126 73699546247341543333500147231430612750390307397135252069338173843322950701049061 86753943313078479801565513038475815568523621801041965025559618193498631591323303 60964619059902361126811960234418433633345949276319461017166529138237171823942992 16272538461776065694542297877071383198817036964588689811863210976900355735884624 46483570629145305275710127887202796536447972402540544813274839179412882642383517 19491972097971459368875371987291308317380339110161285474153773777159517280841116 27597186384924222802373441925469991983672192131287035585307966942713416391033882 75431861364349010094319740904733101447629986172542442335561223743571582593338280 49862438924982227807159517627578471094751190334822414120251826887137281931042534 78196128440176479531505057110722974314569915223451643121848657575786528197564843 50895838472292353455946452121583165775147129870822590929265563883665112068194383 69041162526687100445602437042006637090019411855571604720446436969328500600469281 40507119069261393993902735534545567470314903886022024639948260501762431969305640 66636662609020704888743889890749815286544438186291738290105182086993638266186830 39152732645812867828066013375000965933646251460917231803129303478774212346791184 54791311109897794648216922505629399956793483801699157439700537542134485874586856 04728675106542334189383909911058646559511364606105515683854121745980180713316361 25730796111683438637676673073545834947897883163301292408008363568259391571131309 78030516441716682518346573675934198084958947940983292500086389778563494693212473 42610306271374507728615692259662857385790553324064184901845132828463270926975383 08673084091422476594744399733481308109863994173797896570106870267341619671965915 99588537834822988270125605842365589539690306474965584147981310997157542043256395 77607048510088157829140825077773855979012912940730946278594450585941227319481275 32251523248015034665190482289614066468903051025109162377704484862302294889667113 80555607956620732449373374027836767300203011615227008921843515652121379215748206 85935692079021450227713309998772945959695281704458218195608096581170279806266989 12050615607423256868422713062950098644218534708104071289176469065508361299166947 78023822502789667843489199409657361704586786242554006942516693979292624714524945 40885842272615375526007190433632919637577750217600519580069384763578958687848953 68721228985578068265181927036320994801558744555751753127364714212955364940843855 86615208012115079075068553344489258693283859653013272046970694571546959353658571 78889486233329246520273585318853337094845540333656535698817258252891805663548836 37437933484118455801683318276768346462919956055134700391478768086403226296166415 60667508153710646723108461964247537490553744805318226002710216400980584497526023 03564003808347205314994117296573678506642140084269649710324191918212121320693976 91439233683747092282677387081322366800869247034915868409911530983154120635661231 87504305467536983230827966457417620806593177265685841681837966106144963432544111 70694170022265781735835125982108076910196105222926387974504901925431190062056190 65774524161919131875339840493439768233102984658933183730158095925228292068208622 30332585280119266496314441316442773003237792274712330696417149945532261035475145 63129066885434542686978844774298177749371011761465162418361668025481529633530849 08499430067636548061029400946937506098455885580439704859144495844450799784970455 83550685408745163316464118083123079704389849190506587586425810738422420591191941 67418249045270028826398305795005734171148703118714283418449915345670291528010448 51451760553069714417613685823841027876593246626899784183196203122624211773914772 08004883578333569204533935953254564897028558589735505751235129536540502842081022 78524877660357424636667314868027948605244578267362623085297826505711462484659591 42102781227889414481639949738818846227682448516220518170767221698632657016543169 19742651230041757329904473537672536845792754365412826553581858046840069367718605 02007054724754840080553042495185449526724726134731817474218007857469346544713603 69758841180294080396167469462885406791721386012254195038197045384172680063988206 56328792839582708510919958839448297775647152026132871089526163417707151642899487 95356485455355314875497813400996485449863582484769059003311696130376612792346432 31297066284113074270462020320133683503854253603136367635752126047074253112092334 02837482949453104727418969287275572027615272268283376741393425652653283068469997 59709775000556088993268502504921288406827413988163154045649035077587168007405568 57240217586854390532281337707074158307562696283169556874240605277264858530506113 56384851965918968649596335568216975437621430778665934730450164822432964891270709 89807667662567151726906205881554966638257382927418208227896068448822298339481667 09840390242835143068137672534601260072692629694686727507943461904399966189796119 28750519442356402644303271737341591281496056168353988188569484045342311424613559 92527233006488162746672352375123431189344211888508507935816384899448754475633168 92138696755743027379537852625423290248810471819390372206668947022042588368958409 39998453560948869946833852579675161882159410981624918741813364726965123980677561 94791255795744647142786862405375057610420426714936608498023827468057598259133100 69199419046519065311719089260779491192179464073551296338645230356733455880333131 97080365457184791550432654899559705862888286866606618021882248602144999973122164 13817065348017551043840662441282280361664890425737764095632648282525840766904560 84394903252905263375323165090876813366142423983095308065496618793819491200339194 89494065132398816642080088395554942237096734840072642705701165089075196155370186 26479745638118785617545711340047381076276301495330973517418065547911266093803431 13785325328835333520249343659791293412848549709468263290758301930726653377825593 14331110963848053940859283988907796210479847919686876539987477095912788727475874 43980677982496827827220092644994455938041460877064194181044075826980568803894965 46165879839046605876453418102899071942930217745199761044950431968415034555140448 20928933378657363052830619990077748726922998608279053171691876578860908941817057 99340489021844155979109267686279659758395248392673488363474565168701616624064242 42412289611180106156823425393921800524834547237792199112285959141918774917938233 40010078128326506710281781396029120914720100947878752551263372884222353869490067 92766451163475810119387531965724212147603828477477457170457861041738574791130190 85838778901523343430130052827970385803598151829296003056826120919509437373254541 71056383887047528950563961029843641360935641632589408137981511693338619797339821 67076100460798009601602482309694304380695662012321365014054958625061528258803302 29083858124784693157203232336018994694376477267218793768264318283826035645206994 68630216048874528424363593558622333506235945002890558581611275341783750455936126 13085264082805121387317749020024955273873458595640516083058305377073253397155262 04447054295735383611136775231699727402929416742044232481138750756313190782721888 64053374694213842169928862940479635305150560788126366206497231257579019598873041 19562622734372890051656111109411174527796548279047125058199907749806382155937688 55464988229389854082913251290764783863224947810167534916934892881042030156102833 86143827378160946341335383578340765314321417150655877547820252454780657301342277 47061674424196895261316427410469547462148375628829977180418678508454696561915090 86958742511844358373065909514609804512474094113738999278224929833677960110153870 96129749705566301637307202750734759922943792393824427421186158236161317886392553 09511718842129850830723825972914414225157940388301135908333165185823496722125962 18125070581137594955250227472746743698871319266707692991990844671612287388584575 84622726573330753735572823951616964175198675012681745429323738294143824814377139 86190671665757294580780482055951188168718807521297183263644215533678775127476694 07901170575098195750845635652173895441798750745238544552001335720333323798950743 93905312918212255259833790909463630202185353848854825062897715616963860712382771 72562131346054940177041358173193176337013633225281912754719144345092071184883836 68181742633429496118700915030491653394647637177664391207983474946273978221715020 90670190302469762151278521956142070806461631373236517853976292092025500288962012 97014137964003805573494926907353514596120867479654773369295877362863566014376796 40384307968641385634478013282612845891848985280480488441808216394239740143629034 81665458114454366460032490618763039502356402044530748210241366895196644221339200 75747912868380517515063466256939193774028351207566626082989049187728783385217852 27920457718469658552787904475621926639920084093020756739253637356283908298175779 02153202106409617373283598494066652141198183810884515459772895164572131897797907 49194101314836854463961690460703010759681893374121757598816512700076126278916951 04063158576375347874200702220510708912576123616580268068158584998526314658780866 16800733264676830206391697203064894405628195406190685242003053463156621891327309 06968735318164109451428803660599522024824888671155442910472192913424834643870536 85086487490991788126705656653871910497218200423714927401644609434598453925367061 32210616533085662021188968234005752675486101476993688738209584552211571923479686 88816085363161586288015039594941852948922707441082820716930338781808493620401825 52222710109856534448172074707560192459155994310729495781978785905789400525401228 67517142511184356437184053563024181225473266093302710397968091064939272722683035 41046763259135527968383770501985523462122285841055711992173171796980433931770775 07556270560478317798444476375602546370333692471142208155199736913719751632413027 48712199863404548248524570118553342675264715978310731245663429805221455494156252 72402891533335434934121786203700726031527987077187249123449447714790952073476138 54254853115527733010303424768358654960937223240071545181297326920810584240905577 25645803681462234493189708138897143299831347617799679712453782310703739151473878 69211918756670031932128189680332269659445928621060743882741691946516226763254066 50708810710303941788605648937698167341590259251946118236429456526693722031555047 00213598846292758012527715422016629954863130324912311029627923723899766416803497 14122652793190763632613681414551637665655983978848938173308266877990196288693229 65973799519316211872154552873941702436698855938887933167445333631195415184040882 83815193421234122820030950313341050704760159987985472529190665222479319715440331 79483683737322082188577334162385644138070054191353024594391350255453188645479625 22602517629283743304651023610575835145507394433396102162296754614157811271970017 38611494279501411253280621254775810512972088465263158094806633687670147310733540 71771087661593585681409821296773075919738297344144525668877085532457088895832099 38234321027182241147637327913575686154212528496579033350931527769255058456440105 52192644505312073756287744998163646332835816140330175813967359427327690448920361 88038675495575180689005853292720149392350052584514670698262854825788326739873522 04572282392902071448222198855871028969919358730742778151597576207640239512438602 02032596596250212578349957710085626386118233813318509014686577064010676278617583 77277289589274603940393033727187385053691295712671506689668849388088514294360996 20129667590792250822753138128498515269029317002631363289420957975779593276355311 62066753488651317323872438748063513314512644889967589828812925480076425186586490 24111112730135719718138160258317850693224400799865663537154408845486639318170839 57357807990597308390948818040609359591909074739609044101505163217496814121007657 19177483767355751000733616922386537429079457803200042337452807566153042929014495 78062963413838355178359976470885134900485697369796523869584599459559209070905895 68914511414126845054621179450266117501669282602509507707782119504326173832235624 37601776799362796099368975191394965033358507155418436456852616674243688920371037 49532842592713161053783498074073915863381796765842525803673720646935124865223848 13416638080615057048290598906964519364400185971204257230073164100099169875242603 77362177763430621616744884930810929901009517974541564251204822086714586849255132 44426677712786372821133153622430109182439124338021404624222334915355951689081628 84879899882736304453724321742802157557779670216663170479697281724833928410156422 74507271779269399929740308072770395013581545142494049026536105825409373114653104 94338248437971860693721444460082679800247122948940576185389220342560830269705287 66213773735943942241147070740729027254613073585417456914194464876243576823970657 03184168467540733466346293673983620004041400714054277632480132742202685393698869 78760700959004868465062677136307097982100655728510130660101078063374334477307347 86538817426812307437660666433127753564665786037151929227684404582732832438082128 41218776132042460464900801054731426749260826922155637405486241717031027919996942 64562095561981645454766204502241144940474934983220680719135276798674781345820385 95704134661779372285349400316315995440936840895725334387029867178297703733328068 01764639502090023941931499115009105276821119510999063166150311585582835582607179 41005252858361136996130344279017381178741206128818206202326384986151565645123004 77929675636183457681050433417695430675380411139285537925292413473394810505320257 08728186307291158911335942014761872664291564036371927602306283840650425441742335 46454998705531872688792642410214736369862546374715974435494344389973005174252511 08773578863909468120966734281525859199248576404880550713298142993599114632399191 13959926752576359007446572810191805841807342227734721397723218231771716916400108 82611254909336118678057572239101818616854910850088527227437421208652485237245624 86976622453848192986711294529455154970305859193071984971054141816369689761311267 44027009648667545934567059936995464500558921628047976365686133316563907395703272 03438917541526750091501119885687270884819553167693168127289214303137681801644547 73675183534978579242764633541624336011259602521095016122641103460834656482355979 34274056868849224458745493776752120324703803035491157544831295275891939893680876 32768543876955769488142284431199859570072752139317683783177033913042306095899913 73146845690104220951619670705064202567338734461156552761759927271518776600102389 44760539789516945708802728736225121076224091810066700883474737605156285533943565 84375627124124445765166306408593950794755092046393224520253546363444479175566172 59621871992791865754908578529500128402290350615149373101070094461510116137124237 61426722541732055959202782129325725947146417224977321316381845326555279604270541 87149623658525245864893325414506264233788565146467060429856478196846159366328895 42997807225422647904006160197519750074605451500602918066382714970161109879513366 33771378434416194053121445291855180136575558667615019373029691932076120009255065 08158327550849934076879725236998702356793102680413674571895664143185267905471716 99629903630155456450900448027890557019683283136307189976991531666792089587685722 90600915472919636381673596673959975710326015571920237348580521128117458610065152 59888384311451189488055212914577569914657753004138471712457796504817585639507289 5337539755822087777506072339445587895905719156736L >>> From mizrandir at gmail.com Wed Jul 25 12:42:25 2007 From: mizrandir at gmail.com (mizrandir at gmail.com) Date: Wed, 25 Jul 2007 09:42:25 -0700 Subject: Recursive lists In-Reply-To: <46a6096c$0$8399$9b622d9e@news.freenet.de> References: <1185268478.433070.291370@q75g2000hsh.googlegroups.com> <46a6096c$0$8399$9b622d9e@news.freenet.de> Message-ID: <1185381745.823870.131780@b79g2000hse.googlegroups.com> So if I understood correctly the recursive structure isn't a problem for python because "a" contains a reference to "a", not "a" itself. On the other hand, print works ok because it has a special trap to detect recursive structures. I think I understand it now. Thnks for your replies, miz. From google at mrabarnett.plus.com Wed Jul 25 20:10:20 2007 From: google at mrabarnett.plus.com (MRAB) Date: Wed, 25 Jul 2007 17:10:20 -0700 Subject: Cleaning up a string In-Reply-To: References: Message-ID: <1185408620.608157.215940@w3g2000hsg.googlegroups.com> On Jul 24, 8:47 pm, James Stroud wrote: > Hello all, > > I dashed off the following function to clean a string in a little > > program I wrote: > > def cleanup(astr, changes): > for f,t in changes: > atr = astr.replace(f, t) > return astr > > where changes would be a tuple, for example: > > changes = ( > ('%', '\%'), > ('$', '\$'), > ('-', '_') > ) > > If these were were single replacements (like the last), string.translate > would be the way to go. As it is, however, the above seems fairly > inefficient as it potentially creates a new string at each round. Does > some function or library exist for these types of transformations that > works more like string.translate or is the above the best one can hope > to do without writing some C? I'm guessing that "if s in astr" type > optimizations are already done in the replace() method, so that is not > really what I'm getting after. > A simple way of replacing single characters would be this: def cleanup(astr, changes): changes = dict(changes) return "".join(changes.get(c, c) for c in astr) From alexandre.ferrieux at gmail.com Fri Jul 27 14:17:38 2007 From: alexandre.ferrieux at gmail.com (Alexandre Ferrieux) Date: Fri, 27 Jul 2007 18:17:38 -0000 Subject: Why is "for line in f" faster than readline() In-Reply-To: References: <1185473637.817954.129660@o61g2000hsh.googlegroups.com> Message-ID: <1185560258.433192.54000@19g2000hsx.googlegroups.com> On Jul 27, 2:16 pm, Duncan Booth wrote: > Alexandre Ferrieux wrote: > > Now, *why* is such buffering gaining speed over stdio's fgets(), which > > already does input buffering (though in a more subtle way, which makes > > it still usable with pipes etc.) ? > > Because the C runtime library has different constraints than Python's file > iterator. > > In particular the stdio fgets() must not read ahead (because the stream > might not be seekable), so it is usually just implemented as a series of > calls to read one character at a time until it has sufficient characters. Sorry, but this is simply wrong. Try an strace on a process doing fgets(), and you'll see that it does large read()s. Moreover, the semantics of a blocking read on those live sources is to block while there are no more data, but to return whatever's available (possibly fewer bytes than asked) as soon as new data arrive. This is the key to libc's performance in both line-by-line or bulk transfers. In fact, the Python file iterator is not faster than fgets() by the way. It's just faster than the Python-wrapped version of it, readline, which you said is just a thin layer above fgets(). So instead of dismissing too quickly ol'good libc, maybe the investigation could uncover a slight suboptimality in readline... > Anyone worried about > speed won't use it anyway, so improving it on specific platforms wouldn't > really help. Oh really ? grep, sed, awk, all these stdio-based tools, are pathetic snails compared to the Python file iterator, of course. But then, why didn't anyone feel the urge to use this very same trick in C and provide an "fgets2()", working only on seekable devices, but so much faster ? -Alex From nospam at williamsdurkin.co.uk Thu Jul 5 16:20:37 2007 From: nospam at williamsdurkin.co.uk (Martin Durkin) Date: 5 Jul 2007 20:20:37 GMT Subject: Reversing a string References: <1182997438.541012.54100@o61g2000hsh.googlegroups.com> <1i0kjpx.wjw44j15np22dN%aleax@mac.com> <1i0pz5v.eftrpfbeilzpN%aleax@mac.com> Message-ID: aleax at mac.com (Alex Martelli) wrote in news:1i0pz5v.eftrpfbeilzpN%aleax at mac.com: > Aahz wrote: >> I would agree with people who claim >> that you should memorize most of the built-in functions (which is >> precisely why there is a high barrier to adding more built-in >> functions). > > I think the built-in functions and types a beginner is likely to need > are a "fuzzy subset" (the decision of whether to include or exclude > something being not really obvious:-) roughly including: > > abs all any bool chr cmp dict dir enumerate float getattr help hex int > iter len list max min object open ord property raw_input reversed set > sorted str sum tuple unichr unicode xrange zip > Thanks guys, that is helpful. From rrr at ronadam.com Tue Jul 17 14:26:20 2007 From: rrr at ronadam.com (Ron Adam) Date: Tue, 17 Jul 2007 13:26:20 -0500 Subject: Break up list into groups In-Reply-To: <1184694533.380918.169640@m37g2000prh.googlegroups.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> <1184694533.380918.169640@m37g2000prh.googlegroups.com> Message-ID: <469D09CC.3080402@ronadam.com> Matimus wrote: > I did some more experimenting and came up with the code below. It > shows several methods. When run, the script tests the robustness of > each method (roughly), and profiles it using timeit. The results from > running on my laptop are shown below the code. Try this one... def groupdata(data, fn): start = 0 for n in range(1, len(data)): if fn(data[n]): yield data[start:n] start = n yield data[start:] print list(groupdata(l, lambda x: x & 0x80)) Cheers ;-) Ron > > seqs = [# Original: > [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, > 12, 13, > 0xF0, 14, 0xF1, 15], > # Single entry: > [0xF0, 1, 2, 3], > # empty > [], > # No values with 0x80 set > [1, 2, 3, 14, 15], > # Does not start with a value that has 0x80 set > [1, 2, 3, 14, 15, 0xF0, 1, 2, 3]] > > expected = [# Original: > [[0xF0, 1, 2, 3], [0xF0, 4, 5, 6], [0xF1, 7, 8], [0xF2, 9, > 10, 11, 12, 13], > [0xF0, 14], [0xF1, 15]], > # Single entry: > [[0xF0, 1, 2, 3]], > # empty > [], > # No values with 0x80 set > [], > # Does not start with a value that has 0x80 set > [[0xF0, 1, 2, 3]]] > > def gengroups0(seq): > group = None > for val in seq: > if val & 0x80: > if group: yield group > group = [] > try: > group.append(val) > except AttributeError: > pass > if group: yield group > > def getgroups0(seq): > groups = [] > group = None > for val in seq: > if val & 0x80: > if group: > groups.append(group) > group = [] > try: > group.append(val) > except AttributeError: > pass > if group: > groups.append(group) > return groups > > def gengroups1(seq): > idxs = [i for i,v in enumerate(seq) if v&0x80] > for i,j in zip(idxs,idxs[1:]+[None]): > yield seq[i:j] > > def getgroups1(seq): > idxs = [i for i,v in enumerate(seq) if v&0x80] > return [seq[i:j] for i,j in zip(idxs,idxs[1:]+[None])] > > # Similar to the partition method on strings > def partition(seq,f=None): > if f is None: > f = lambda x:x > for i,v in enumerate(seq): > if f(v): > return seq[:i],[seq[i]],seq[i+1:] > return seq,[],[] > > def rpartition(seq, f=None): > if f is None: > f = lambda x:x > for i,v in zip(range(len(seq)-1,-1,-1),seq[::-1]): > if f(v): > return seq[:i],[seq[i]],seq[i+1:] > return ([],[],seq) > > def gengroups2(seq): > while seq: > seq, key, val = rpartition(seq, lambda x: x&0x80) > if key and val: yield key+val > > def getgroups2(seq): > groups = [] > while seq: > seq, key, val = rpartition(seq, lambda x: x&0x80) > if key and val: > groups.append(key+val) > return groups > > def getgroups3(seq): > groups = [] > for i in seq: > if 0x80 & i: > groups.append([i]) > else: > groups[-1].append(i) > return [x for x in groups if x] > > seq = seqs[0] > if __name__ == "__main__": > from timeit import Timer > import __main__ > for i in range(4): > fname = "getgroups"+str(i) > f = getattr(__main__,fname) > print fname > for i,(s,e) in enumerate(zip(seqs,expected)): > print "test %d:"%i, > try: > if f(s) == e: > print "pass" > else: > print "fail" > except: > print "error" > > t = Timer(fname+'(seq)', > 'from __main__ import seq,'+fname) > print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/ > 100000) > print > > > Output from running the above: > getgroups0 > test 0: pass > test 1: pass > test 2: pass > test 3: pass > test 4: pass > 14.85 usec/pass > > getgroups1 > test 0: pass > test 1: pass > test 2: pass > test 3: pass > test 4: pass > 13.81 usec/pass > > getgroups2 > test 0: fail > test 1: pass > test 2: pass > test 3: pass > test 4: pass > 56.38 usec/pass > > getgroups3 > test 0: pass > test 1: pass > test 2: pass > test 3: error > test 4: error > 16.23 usec/pass > > `getgropus2' fails test 0 because it produces a reversed list. That > can easily be fixed by re-reversing the output before returning. But, > since it is by far the slowest method, I didn't bother. > > `getgroups3' is a method I got from another post in this thread, just > for comparison. > >>From my benchmarks it looks like getgroups1 is the winner. I didn't > scour the thread to test all the methods however. > From steven.klass at gmail.com Wed Jul 11 09:49:48 2007 From: steven.klass at gmail.com (rh0dium) Date: Wed, 11 Jul 2007 13:49:48 -0000 Subject: A clean way to program an interface In-Reply-To: <1184012359.352835.147960@o61g2000hsh.googlegroups.com> References: <1183957402.819499.227350@o11g2000prd.googlegroups.com> <5feidnF3au460U1@mid.uni-berlin.de> <1183989399.366239.250850@g4g2000hsf.googlegroups.com> <5feuvvF3bcgoiU1@mid.uni-berlin.de> <1184000380.457434.316970@g4g2000hsf.googlegroups.com> <1184012359.352835.147960@o61g2000hsh.googlegroups.com> Message-ID: <1184161788.560692.177670@m3g2000hsh.googlegroups.com> On Jul 9, 1:19 pm, rh0dium wrote: Hi all, OK so I've started re-writing this based on the feedback you all gave me. How does this look? class Scanner: def __init__(self, *args, **kwargs): """description""" # Setup Logging self.log = logging.getLogger(module+self.__class__.__name__) self.loglevel = kwargs.get('loglevel', logging.WARN) self.setLoglevel(self.loglevel) self.serialport=kwargs.get('port', PORT) self.serialbps=kwargs.get('bps', 115200) self.uniden=UnidenConnection.UnidenConnection(port=self.serialport, bps=self.serialbps, loglevel=self.loglevel) if self.inProgramMode(): self.PRGMode=True else: self.PRGMode=False def setLoglevel(self,loglevel): """setLog log level""" if loglevel is not False: self.log.setLevel(loglevel) self.log.debug("Setting Logging level to %s" % loglevel) else: self.log.setLevel(logging.WARN) if self.loglevel == logging.DEBUG: self.debug = True else: self.debug=False def ProgramMode(fn): def _prgmode(self,*args,**kwargs): progmode=True if not self.PRGMode: self.log.debug("Going into programming mode") progmode=False self.PRG() ret = fn(self,*args,**kwargs) if not progmode: self.log.debug("Getting out of programming mode") self.EPG() return ret return _prgmode def __orderedDictValues(self,orderedlist,dictvals): rlist = [] for x in orderedlist: if dictvals.has_key(x) or x == "rsv": if x == "rsv": rlist.append("") else: rlist.append(str(dictvals[x])) else: break return rlist def STS(self): """Get Current Status""" cmd = "STS" p = self.uniden.write(cmd) retargs = "dsp_form l1_char l1_mode l2_char l2_mode l3_char l3_mode \ l4_char l4_mode l5_char l5_mode l6_char l6_mode l7_char \ l7_mode l8_char l8_mode sql mut rsv wat led_1 led_2 sig_lvl \ bk_color bk_dimmer".split() t = dict((k,v) for k, v in zip(retargs,p) if v != "") return t def PRG(self): """Enter Programming Mode""" self.PRGMode=True return self.uniden.write("PRG") def EPG(self): """Exit Programming Mode""" self.PRGMode=True return self.uniden.write("EPG") @ProgramMode def SIN(self, *args, **kwargs): """Get/Set System Index""" cmd = "SIN" iptargs="index name quick_key hld lout dly skp rsv rsv apco \ threshold start_key record latitude longitude range \ gps_enable rsv".split() iptarglist=self.__orderedDictValues(iptargs,kwargs) if len(iptarglist) != len(iptargs) and len(iptarglist) != 1: raise SyntaxError, "Missing arguments for %s expected 1 or %d got %d - given %s" % (cmd, len(iptargs), len(iptarglist), kwargs) p = self.uniden.write("%s,%s" % (cmd,",".join(iptarglist))) retargs = "sys_type name quick_key hld lout dly skp rsv rsv apco \ threshold rev_index fwd_index chn_grp_head chn_grp_tail \ seq_no start_key record latitude longitude range gps enable \ rsv".split() t = dict((k,v) for k, v in zip(retargs,p) if v != "") return t def inProgramMode(self): try: print"PRGMODE",self.STS() if self.STS()["l2_char"].strip()=="Remote Mode": print "IN PRG" return True else: return False except: return False From stesch at no-spoon.de Fri Jul 27 05:00:29 2007 From: stesch at no-spoon.de (Stefan Scholl) Date: Fri, 27 Jul 2007 11:00:29 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> <0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de> <5gtjeeF3i0lfsU2@mid.uni-berlin.de> Message-ID: <2T49f13tIf2oNv8%stesch@parsec.no-spoon.de> Marc 'BlackJack' Rintsch wrote: > On Fri, 27 Jul 2007 06:47:48 +0200, Stefan Scholl wrote: > >> Chris Mellon wrote: >>> XML is not a string. It's a specific type of bytestream. If you want >>> to work with XML, then generate well-formed XML in the correct >>> encoding. There's no reason you should have an XML document (as >>> opposed to values extracted from that document) in unicode objects at >>> all. >> >> The affected method in xml.sax is called parseString() > > Exactly. It's *not* called `parseUnicode()`. Semantics. >>> u"".__class__.__base__ >>> "".__class__.__base__ From matthieutc at yahoo.com Wed Jul 4 08:15:24 2007 From: matthieutc at yahoo.com (Matthieu TC) Date: Wed, 4 Jul 2007 05:15:24 -0700 (PDT) Subject: what is wrong with that r"\" Message-ID: <61910.22236.qm@web50105.mail.re2.yahoo.com> May I suggest giving the possibility to use any delimiter for a raw string? just like in Vi or ruby. Vi: %s_a_b_g is valid and so is %s/a/b/g Ruby: %q{dj'\ks'a\'"} or %q-dj'\ks'a\'"- So as long as your regex does not use all the valid characters, readability is maintained. -matt ----- Original Message ---- From: Marc 'BlackJack' Rintsch To: python-list at python.org Sent: Wednesday, July 4, 2007 9:27:46 PM Subject: Re: what is wrong with that r"\" On Wed, 04 Jul 2007 11:21:14 +0000, Neil Cerutti wrote: > If the escaped quotes didn't function in raw strings, I'd be > unable to construct (with a single notation) a regex that > included both kinds of quotes at once. > > re.compile(r"'\"") Where's the problem!? :: re.compile(r''''"''') Ah, I see -- readability is the problem. :-) Ciao, Marc 'BlackJack' Rintsch -- http://mail.python.org/mailman/listinfo/python-list From steve at REMOVE.THIS.cybersource.com.au Fri Jul 20 09:59:00 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 20 Jul 2007 23:59:00 +1000 Subject: class C: vs class C(object): References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> Message-ID: On Thu, 19 Jul 2007 10:42:54 -0700, Aahz wrote: > In article , > Steven D'Aprano wrote: >> >>It isn't wrong to use the old style, but it is deprecated, [...] > > Really? Can you point to some official documentation for this? AFAIK, > new-style classes still have not been integrated into the standard > documentation. Maybe I missed something, though. > > Note very carefully that "going away eventually" is *not* the same as > deprecation. *slaps head* Yes, Aahz is correct, and I for one should have known better: see this thread, for example, where I not only defend the use of old style classes but explicitly stated that they *weren't* deprecated. http://groups.google.com.au/group/comp.lang.python/browse_thread/thread/c33c458568b1027c/52fabc6398a566b6?lnk=st&q=steven+aahz+new+style+classes+&rnum=1#52fabc6398a566b6 Mea culpa. -- Steven. From hjp-usenet2 at hjp.at Wed Jul 4 02:12:53 2007 From: hjp-usenet2 at hjp.at (Peter J. Holzer) Date: Wed, 4 Jul 2007 08:12:53 +0200 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> <7xlke6y6y1.fsf@ruckus.brouhaha.com> <7x645al8kc.fsf@ruckus.brouhaha.com> <1182894003.920335.317620@a26g2000pre.googlegroups.com> <7x7ipoy6cf.fsf@ruckus.brouhaha.com> <1183041149.275562.114490@o11g2000prd.googlegroups.com> <7xbqethpr8.fsf@ruckus.brouhaha.com> <468AD888.6A023A0E@yahoo.com> Message-ID: On 2007-07-03 23:15, CBFalconer wrote: > "Peter J. Holzer" wrote: >> Richard Heathfield wrote: >> > ... snip ... >> >>> In that case, the obvious choice is Greenwich Mean Time. :-) >> >> Hardly. That hasn't been in use for over 35 years (according to >> Wikipedia). > > I am glad to see you depend on absolutely reliable sources. Mostly I relied on my own memory (which is of course even less reliable than Wikipedia). I checked Wikipedia for the date (Jan 1st 1972) when GMT was replaced by UTC as the basis for civil time. Since that coincided with my own recollection (sometime in the 1970's), I see no reason to doubt it. It is possible that the observatory at Greenwich still keeps and announces GMT, but it has no practical importance anymore. Certainly what everybody (except specialists in the field) means when they talk about "GMT" is UTC. hp -- _ | Peter J. Holzer | I know I'd be respectful of a pirate |_|_) | Sysadmin WSR | with an emu on his shoulder. | | | hjp at hjp.at | __/ | http://www.hjp.at/ | -- Sam in "Freefall" From claird at lairds.us Thu Jul 5 12:52:15 2007 From: claird at lairds.us (Cameron Laird) Date: Thu, 5 Jul 2007 16:52:15 +0000 Subject: The best platform and editor for Python References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183627699.941481.92660@g4g2000hsf.googlegroups.com> <44fc5$468cd4f1$547078de$24824@news.chello.at> Message-ID: In article <44fc5$468cd4f1$547078de$24824 at news.chello.at>, Gregor Horvath wrote: >kimiraikkonen schrieb: > >> My another aim is: Can i develop graphical applications (like in >> Windows) which contain menus, interactive dialog boxes etc. using >> Ptyhon? >> >> I got it quite but not sure. I don't know Ptyhon's capability skills >> for creating interactive softwares like in Windows's created by C++ or >> Delphi. >> > >have a look at Dabo > >http://www.dabodev.com/ . . . I want to make this explicit for the benefit of the original questioner: A. Dabo's great stuff; but B. there are, at the same time, quite a few other frameworks for GUI programming with Python . From gagsl-py2 at yahoo.com.ar Fri Jul 13 01:51:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jul 2007 02:51:25 -0300 Subject: Getting values out of a CSV References: <1184295593.638409.22910@22g2000hsm.googlegroups.com> Message-ID: En Fri, 13 Jul 2007 02:10:17 -0300, Daniel escribi?: > data = [row for row in csv.reader(open('some.csv', 'rb')) Note that every time you see [x for x in ...] with no condition, you can write list(...) instead - more clear, and faster. data = list(csv.reader(open('some.csv', 'rb'))) -- Gabriel Genellina From semanticist at gmail.com Mon Jul 16 02:09:50 2007 From: semanticist at gmail.com (Miles) Date: Sun, 15 Jul 2007 23:09:50 -0700 Subject: Fetching a clean copy of a changing web page In-Reply-To: References: Message-ID: <1184566190.197725.296610@n60g2000hse.googlegroups.com> On Jul 16, 1:00 am, John Nagle wrote: > I'm reading the PhishTank XML file of active phishing sites, > at "http://data.phishtank.com/data/online-valid/" This changes > frequently, and it's big (about 10MB right now) and on a busy server. > So once in a while I get a bogus copy of the file because the file > was rewritten while being sent by the server. > > Any good way to deal with this, short of reading it twice > and comparing? > > John Nagle Sounds like that's the host's problem--they should be using atomic writes, which is usally done be renaming the new file on top of the old one. How "bogus" are the bad files? If it's just incomplete, then since it's XML, it'll be missing the "" and you should get a parse error if you're using a suitable strict parser. If it's mixed old data and new data, but still manages to be well-formed XML, then yes, you'll probably have to read it twice. -Miles From horpner at yahoo.com Tue Jul 24 11:30:12 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 24 Jul 2007 15:30:12 GMT Subject: Closures / Blocks in Python References: <1185289112.771239.200260@n60g2000hse.googlegroups.com> Message-ID: On 2007-07-24, treble54 wrote: > Does anyone know a way to use closures or blocks in python like > those used in Ruby? Particularly those used in the { } braces. Python's nameless functions are week. So it supports iterators and generators using protocols, comprehensions and a few simple statements, rather than promoting the use of nameless functions. Ruby's some_list.each do |item| puts item end if I understood it correctly, In Python would be: for item in some_list: print item That works for any object that supports the iterator protocol. -- Neil Cerutti From dysmas at gmail.com Wed Jul 4 07:34:07 2007 From: dysmas at gmail.com (dysmas) Date: Wed, 04 Jul 2007 04:34:07 -0700 Subject: issues with htmlparser.getpos Message-ID: <1183548847.515341.293540@q69g2000hsb.googlegroups.com> Hi, Im having an issue with HTMLParser, the getpos() funtion sometimes returns things like : (1, 1247) (1, 2114) (1, 2168) (1, 2228) (1, 2295) (1, 2382) (1, 2441) (1, 2963) (1, 3040) i guess this is because the HTMLParser has not correctly parsed the newline characters in the string fed to it... is there a workaround for this, without checking the string every time i feed it some data? From juanvazquez at gmail.com Sat Jul 7 10:02:54 2007 From: juanvazquez at gmail.com (Juan Vazquez) Date: Sat, 7 Jul 2007 09:02:54 -0500 Subject: tk password module Message-ID: <5dbef1c10707070702g2e6e12c1n34fd8adcde00571@mail.gmail.com> I am working on a script that utilizes tk in order to connect users to an online account. It must be done on their personal machines and I would like to have them use a gui. Is there a method that can take text and make it unreadable (like password form in html)? thanks -J -------------- next part -------------- An HTML attachment was scrubbed... URL: From sturlamolden at yahoo.no Fri Jul 13 23:58:55 2007 From: sturlamolden at yahoo.no (sturlamolden) Date: Fri, 13 Jul 2007 20:58:55 -0700 Subject: Pass by reference or by value? In-Reply-To: <1184353832.314694.228270@n60g2000hse.googlegroups.com> References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> Message-ID: <1184385535.558451.306630@22g2000hsm.googlegroups.com> On Jul 13, 9:10 pm, Robert Dailey wrote: > I noticed in Python all function parameters seem to be passed by > reference. This means that when I modify the value of a variable of a > function, the value of the variable externally from the function is > also modified. Pass-by-value and pass-by-reference usually refer to the semantics used in C and Fortran, respectively. Here is an example showing the distinction between the 'pass-by-value' semantics of C and the 'pass-by-reference' semantics of Fortran: In C you can pass pointers, but it is still a pure 'pass-by-value' semantics. The pointer itself is passed by value (which is an address). What that means, is that the function receives a copy of the argument used in the call: int a = 1; foo(&a); bar(&a); void foo(int *a) { a = (int*) 0; /* no side effect */ } void bar(int *a) { *a = 0; /* side effect, but a is still passed by value */ } Now take a look at how the functions foo and bar are called. They both have the same signature, void ()(* int). Thus they must be called equivalently. But still one produces a side-effect and the other does not. Often in C litterature you can see what happens in the function bar called 'pass-by- reference'. But that is very incorrect, C never passes anything by reference. 'Pass-by-value' is thus equivalent to 'pass-a-copy'. In Fortran you can only pass references. integer(4) :: a a = 1 call bar(a) subroutine bar(a) integer(4) :: a a = 0 ! side-effect end subroutine That means, when a variable is used to call a function, the function receives a pointer to the actual argument, not a local copy. That is very different from C's copy-passing behaviour. C++ can pass-by-value and pass-by-reference: int a = 1; foo(&a); // no side-effect bar(&a); // side-effect foo2(a); // no side-effect bar2(a); // side-effect!!! void foo(int *a) // pass-by-value { a = (int*) 0; // no side effect } void bar(int *a) // pass-by-value { *a = 0; // side effect, but a is still passed by value } void foo2(int a) // pass-by-value { a = 0; // no side effect !!! } void bar2(int &a) // pass-by-reference { a = 0; // side effect !!! } The C++ example clearly shows what we mean by pass-by-reference. It seems when we call the function bar2 that we give it the value of a, when we in fact give it a reference to a. That is the same thing that happens in Fortran. What it all boils down to is this: Local copies are made in the 'pass-by-value' semantics. Local copies are not made in the 'pass-by-reference' semantics. Now that we have defined 'pass-by-value' and 'pass-by-reference' precisely, it is time to examine what Python does. It turns out that Python neither works like C nor like Fortran. Rather, Python works like LISP. That is: Python names are pointers bound to values. Python always pass pointers to values. Python never pass local copies. Function arguments are referenced by names in the function's local namespace. Names referencing function arguments can be rebound in the local scope. >From this you might think that Python does pass-by-reference. Afterall it does not create local copies. But as names can be rebound in the local scope, function calls in Python and Fortran behave very differently. That is: a = 1 # a points to an int(1) foobar(a) # a still points to an int(1) def foobar(a): a = 0 # rebinds a locally, produces no side-effect # in Fortran this would have produced a side-effect Now, examine this code sniplet: a = 1 # a points to an int(1) foobar(a) # a still points to an int(1) as an int is immutable a = [1, 2, 3] # rebinds a, a points to a mutable type foobar(a) # a points to [1,2,3,1,2,3] def foobar(a): a *= 2 # rebinds a only if a points to an immutable type, # otherwise the value pointed to by a is changed If you take a careful look at these examples, you should be able to figure out what Python does. Python does 'pass-by-reference' in the sense that it always pass pointers. Python does 'pass-by-value' in the sense that names has a local scope and can be rebound in the local scope. The correct statement would be to say that Python does neither pass-by- reference nor pass-by-value in the conventional meaning of the terms. Rather Python does 'pass-as-lisp'. Sturla Molden P.S. You could think of Python as a Java only having reference types. What makes the semantics of Java and C# 'pass-by-value' like C, is the fact that they make copies of value-types when passed to a function. A reference type is also passed by value, in this case the value of the reference is passed. Python does not have value types. But Python does have immutable types. An int is an immutable type in Python and a value type in Java. What happens when Python and Java calls a function with an int as argument is very different. Java makes a copy of the int and passes that. Python passes a pointer to the int. But as an int is immutable in Python, it may look like Python passes ints 'by value' when in fact it never creates a local copy. From sbassi at clubdelarazon.org Sun Jul 15 10:36:54 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sun, 15 Jul 2007 11:36:54 -0300 Subject: CSV without first line? In-Reply-To: <4699C27D.7010305@lexicon.net> References: <1184473728.675046.149640@m37g2000prh.googlegroups.com> <9e2f512b0707142204r3eaa8b5dmb25a8a8b9893325d@mail.gmail.com> <4699C27D.7010305@lexicon.net> Message-ID: <9e2f512b0707150736k1cb678b0x2988479ecb57edc9@mail.gmail.com> On 7/15/07, John Machin wrote: > So you imagine that there is an undocumented feature? No, I just think that is documented but I am not able to understand it. Reading the list I've learned several things that are not directly inferred from documentation (that is not the same as undocumented feature). -- Sebasti?n Bassi (???????) Diplomado en Ciencia y Tecnolog?a. GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D From bdesth.quelquechose at free.quelquepart.fr Sun Jul 15 17:07:27 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 15 Jul 2007 23:07:27 +0200 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: Message-ID: <469bce45$0$14054$426a74cc@news.free.fr> Wayne Brehaut a ?crit : > On Fri, 13 Jul 2007 20:37:04 -0400, Steve Holden > wrote: > > >>Aahz wrote: >> >>>In article , >>>Chris Carlen wrote: >>>>From what I've read of OOP, I don't get it. >>> >>>For that matter, even using OOP a bit with C++ and Perl, I didn't get it >>>until I learned Python. >>> >>> >>>>The problem for me is that I've programmed extensively in C and .asm on >>>>PC DOS way back in 1988. >>> >>>Newbie. ;-) >>> >>>(I started with BASIC in 1976.) >>> >> >>Newbie ;-) >> >>(I started with Algol 60 in 1967). > > > Newbie ;-) > > (I started with Royal McBee LGP 30 machine language (hex input) in > 1958, and their ACT IV assembler later! Then FORTRAN IV in 1965. By > 1967 I too was using (Burroughs) Algol-60, and 10 years later upgraded > to (DEC-10) Simula-67.) > My my my... Would you believe that my coworkers do consider me like an old sage because I started programming in 1990 with HyperTalk on Mac Classic !-) I suddenly feel 20 again ! Woo !-) From http Thu Jul 26 16:59:12 2007 From: http (Paul Rubin) Date: 26 Jul 2007 13:59:12 -0700 Subject: question about math module notation References: <7xd4ye7vv9.fsf@ruckus.brouhaha.com> Message-ID: <7xejiukhjz.fsf@ruckus.brouhaha.com> brad writes: > Ah yes, that works too... thanks. I've settled on doing it this way: > print int(math.pow(2,64)) > I like the added parenthesis :) I was surprised to find that gives an exact (integer, not floating-point) answer. Still, I think it's better to say 2**64 which also works for (e.g.) 2**10000 where math.pow(2,10000) raises an exception. From hg at nospam.org Sun Jul 1 17:53:42 2007 From: hg at nospam.org (hg) Date: Sun, 01 Jul 2007 16:53:42 -0500 Subject: ctype and functions that return a pointer to a structure References: Message-ID: Lenard Lindstrom wrote: > hg wrote: >> Hi, >> >> I have the following code: >> ****************************************** >> from ctypes import * >> g_lib = cdll.LoadLibrary("libc.so.6") >> class Struct_Password(Structure): >> """ >> >> """ >> _fields_ = [ ('name', c_char_p), >> ('code', c_char_p), >> ('date', c_long), >> ('min', c_long), >> ('max', c_long), >> ('warn', c_long), >> ('inact', c_long), >> ('expire', c_long), >> ('flag', c_ulong) >> ] >> l_res = g_lib.getspnam('john') >> l_struct = cast(l_res, POINTER( Struct_Password() ) ) > > l_struct = cast(l_res, POINTER( Struct_Password ) ) > > POINTER wants a ctypes type as an argument. Struct_Password() is a > Structure instance. > > A better way to do it is define the return type for getspnam: > > g_lib.getspnam.restype = POINTER( Struct_Password ) > > Now the function returns a structure pointer so the cast is unnecessary. > > --- > Lenard Lindstrom > Many thanks, hg From sjdevnull at yahoo.com Wed Jul 4 00:48:47 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: Tue, 03 Jul 2007 21:48:47 -0700 Subject: Building a Python app with Mozilla In-Reply-To: References: Message-ID: <1183524527.709730.190290@q75g2000hsh.googlegroups.com> Thorsten Kampe wrote: > Hi, > > I've already sent this to the Komodo mailing list (which seemed to me > the more appropriate place) but unfortunately I got no response. > > I'd like to build a Python GUI app. Neither Tkinter nor Wxpython nor > PyQT are actually what I want (because the lack of GUI builders and > they don't really look good on Windows and Linux). > > Komodo itself is an excellent example of a - at least Python driven - > application that looks superb I dunno about Windows, but on Linux Komodo/Firefox/etc stick out like a sore thumb with their ugly, non-native looking widgets (idem. Tk). wxWidgets will give you native looking apps on both Linux and Windows (and I think on Macs as well but it's been a while since I looked). From aisaac at american.edu Wed Jul 4 21:36:10 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 05 Jul 2007 01:36:10 GMT Subject: disappearing documentation of `coerce` Message-ID: Once upon a time, `coerce` was documented with the other built-ins. http://pydoc.org/1.5.2/__builtin__.html Now it is not. http://docs.python.org/lib/built-in-funcs.html Reason? Thanks, Alan Isaac From vodela.sai at gmail.com Mon Jul 30 17:43:47 2007 From: vodela.sai at gmail.com (Rohan) Date: Mon, 30 Jul 2007 21:43:47 -0000 Subject: Directory Message-ID: <1185831827.206641.163630@x40g2000prg.googlegroups.com> 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. From jakf at mail.cnt.ru Fri Jul 20 09:17:44 2007 From: jakf at mail.cnt.ru (Garrison Arabella) Date: Fri, 20 Jul 2007 08:17:44 -0500 Subject: No subject Message-ID: <46A0B5F8.1080208@weishaupt.ru> -------------- next part -------------- A non-text attachment was scrubbed... Name: journal.pdf Type: application/pdf Size: 4600 bytes Desc: not available URL: From gagsl-py2 at yahoo.com.ar Mon Jul 9 21:42:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Jul 2007 22:42:53 -0300 Subject: Error when trying to write unicode xml to zipfile References: <1184022684.557693.111890@n60g2000hse.googlegroups.com> Message-ID: En Mon, 09 Jul 2007 20:11:24 -0300, Martin escribi?: > I get below error when trying to write unicode xml to a zipfile. > > zip.writestr('content.xml', content.toxml()) > File "/usr/lib/python2.4/zipfile.py", line 460, in writestr > zinfo.CRC = binascii.crc32(bytes) # CRC-32 checksum > UnicodeEncodeError: 'ascii' codec can't encode character u'\u25cf' in > position 2848: ordinal not in range(128) > > Any ideas? Encode before writing. Assuming you want to use utf-8: zip.writestr('content.xml', content.toxml().encode('utf-8')) In general, when working with unicode, it's best to decode bytes into unicode as early as possible (when reading input), process only unicode inside the program, and encode into bytes at the last step (when writing output). Some non-unicode-aware libraries may interfere with this flow, unfortunately. -- Gabriel Genellina From kyosohma at gmail.com Thu Jul 19 09:30:12 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 19 Jul 2007 06:30:12 -0700 Subject: Real-time Update In-Reply-To: <1184747090.102324.265230@i13g2000prf.googlegroups.com> References: <1184747090.102324.265230@i13g2000prf.googlegroups.com> Message-ID: <1184851812.735634.135900@d30g2000prg.googlegroups.com> On Jul 18, 3:24 am, ReTrY wrote: > I'm writing a program with Tkinter GUI, When the program is running it > need to be updated every five seconds (data comes from internet). How > should I do that ? How to make a function in main loop ? I'm pretty sure the book "Programming Python 3rd Ed." by Lutz covers this stuff in detail. I think it mentions using threads for this sort of thing. The wxPython wiki has a good example that I think you could adapt for Tkinter. Just use the threading code and wrap it in your Tkinter code and I think you'll be good to go. Here's the link: http://www.wxpython.org/maillist.php Good luck, Mike From carl.dhalluin at gmail.com Thu Jul 12 05:30:45 2007 From: carl.dhalluin at gmail.com (carl.dhalluin at gmail.com) Date: Thu, 12 Jul 2007 09:30:45 -0000 Subject: atexit, sys.exit, sys.exitfunc, reaching end of source code In-Reply-To: References: <1184192510.343401.13860@57g2000hsv.googlegroups.com> Message-ID: <1184232645.089981.168090@n60g2000hse.googlegroups.com> On 12 jul, 01:32, Wojciech Mu a wrote: > carl.dhall... at gmail.com wrote: > > I am playing with theatexitmodule but I don't find a way to see the > > difference > > between a script calling sys.exit() and the interpreting > > arriving at the end > > of the source code file. This has a semantic difference for my > > applications. > > Is there a way to determine in an exithandler (that is registered > > usingatexit.register) > > how I exited? > > Actually sys.exit raises exception SystemExit, but if interpreter > reaches end of script exception is not raised. Try something > like this: > > if __name__ == '__main__': > exit_code_for_exithandler = None > try: > #... > sys.exit(5) > pass > #... > except SystemExit, e: > exit_code_for_exithandler = e.code > print "sys.exit called" > else: > print "end of script" > > w. I am getting quite confused with this SystemExit. If I register a custom sys.excepthook then it is never invoked when I do sys.exit(.) From faulkner891 at gmail.com Tue Jul 10 08:21:25 2007 From: faulkner891 at gmail.com (faulkner) Date: Tue, 10 Jul 2007 05:21:25 -0700 Subject: Get a filename list of a web site In-Reply-To: <1184058732.163303.96300@q75g2000hsh.googlegroups.com> References: <1184058732.163303.96300@q75g2000hsh.googlegroups.com> Message-ID: <1184070085.921709.219020@r34g2000hsd.googlegroups.com> On Jul 10, 5:12 am, aidech... at yahoo.it wrote: > Hi all, > is it possible to get a filename directory list of a website (possibly > with full path indication)? > Using python & possibly wget? > > Bye. HTTP does not provide a command for this. you need to acquire a shell account on the specific server you're interested in. generally, this requires emailing the addresses in the whois database, explaining why you need a shell account. generally, they will deny your request. then you can say `ssh YOURNAME at SERVER ls DIRECTORY`. a few directories on a few servers are configured such that they list themselves when queried. iirc, there's a google trick to let you find these directories. From the.mindstorm.mailinglist at gmail.com Sun Jul 15 03:00:47 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Sun, 15 Jul 2007 00:00:47 -0700 Subject: Lists in classes In-Reply-To: <46967a84$0$11778$426a74cc@news.free.fr> References: <1184253811.052346.220470@22g2000hsm.googlegroups.com> <1184255240.559017.61330@o61g2000hsh.googlegroups.com> <46967a84$0$11778$426a74cc@news.free.fr> Message-ID: <1184482847.657566.307120@g4g2000hsf.googlegroups.com> On Jul 13, 6:02 am, Bruno Desthuilliers wrote: > Alex Popescu a ?crit : > (snip) > > > > > You are defining the list in the class context and so it becomes a > > class field/member. > > 'attribute' is the pythonic term. Thanks! I'm just a couple of weeks Python old, so I am still fighting to use the correct vocabulary :-). And as with foreign languages, while I am becoming better at reading I still have problems expressing correct ideas using correct words. ./alex -- .w( the_mindstorm )p. From nick at craig-wood.com Thu Jul 19 07:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 19 Jul 2007 06:30:04 -0500 Subject: wxPython and threads References: <1184726489.112138.96350@z28g2000prd.googlegroups.com> Message-ID: Josiah Carlson wrote: > Sending results one at a time to the GUI is going to be slow for any > reasonably fast search engine (I've got a pure Python engine that does > 50k results/second without breaking a sweat). Don't do that. Instead, > have your search thread create a list, which it fills with items for > some amount of time, *then* sends it off to the GUI thread (creating a > new list that it then fills, etc.). While you *could* use a Queue, it > is overkill for what you want to do (queues are really only useful when > there is actual contention for a resource and you want to block when a > resource is not available). I'd dispute that. If you are communicating between threads use a Queue and you will save yourself thread heartache. Queue has a non blocking read interface Queue.get_nowait(). -- Nick Craig-Wood -- http://www.craig-wood.com/nick From S.Mientki-nospam at mailbox.kun.nl Mon Jul 16 15:20:57 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Mon, 16 Jul 2007 21:20:57 +0200 Subject: running a Delphi part from Python ? In-Reply-To: References: <889c1$469b275c$d443bb3a$2876@news.speedlinq.nl> <469b2b65$0$21672$426a74cc@news.free.fr> <86c61$469b30d1$d443bb3a$15805@news.speedlinq.nl> <469b3530$0$26995$426a74cc@news.free.fr> <47dce$469b3a07$d443bb3a$26795@news.speedlinq.nl> Message-ID: <525c5$469bc3be$d443bb3a$23897@news.speedlinq.nl> Chris Mellon wrote: > On 7/16/07, Stef Mientki wrote: >> tool69 wrote: >> > Stef Mientki a ?crit : >> > >> >> AFAIK, Scintilla is a code editor. >> >> What I need looks more like ms-word, >> >> handling lists, tables, images, formulas. >> >> >> >> thanks, >> >> Stef Mientki >> > >> > >> > So you'll need the RichTextCtrl >> > >> > http://www.wxpython.org/docs/api/wx.richtext.RichTextCtrl-class.html >> > >> > See a sample in the demo under "Recent Additions". >> >> Well it's better, >> - it has lists >> - it has images, but no image editing, >> It doesn't have >> - drag & drop >> - tables, >> - formula editing, >> - screen capture, >> - links >> - embedded code >> - CSS >> - .... >> so unfortunately it's not yet sufficient :-( >> > > This goes far beyond the requirement for a rich text editor. You're > now talking about rich object integration, which is about 80% of a > full featured word processor. The features I describe, are just 1% of the (in-)capabilities of ms-word, so what do you call ms-word ;-) You won't find a cross platform > implementation that's suitable for use as a component in anything. > > Delphi components are tightly tied to the Delphi runtime environment > and its' gui abstractions, so embedding it as is is will be a massive > hack (and require extensive C code) if its even possible. The editor I've in mind communicates only through messages, about 20 to the editor and 5 back, so that doesn't sound too much. > > However, any company who writes such a full featured control is likely > to package it as an ActiveX control so they can get the sales from the > VB guys, and you can embed ActiveX control in wxPython applications > (Windows only, of course). Very good idea, although I've never done it, according to the decriptions, it should be just one press on a button to create an ActiveX of the Editor-component. thanks, Stef Mientki From kelvie at ieee.org Tue Jul 24 14:02:28 2007 From: kelvie at ieee.org (Kelvie Wong) Date: Tue, 24 Jul 2007 11:02:28 -0700 Subject: Any python module for Traversing HTML files In-Reply-To: <1185298581.322910.311720@w3g2000hsg.googlegroups.com> References: <1185297135.542235.55290@r34g2000hsd.googlegroups.com> <1185298581.322910.311720@w3g2000hsg.googlegroups.com> Message-ID: <94ccbe710707241102v318c41c8n38585591bec7c9af@mail.gmail.com> I think he meant "Beautiful Soup". On 7/24/07, Clement wrote: > On Jul 24, 10:12 pm, johnny wrote: > > Any python module for navigating and selecting, parsing HTML files? > > try beautyfulshop > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Kelvie From crobc at BOGUS.sbcglobal.net Sat Jul 28 18:03:16 2007 From: crobc at BOGUS.sbcglobal.net (CC) Date: Sat, 28 Jul 2007 15:03:16 -0700 Subject: How to stop print printing spaces? Message-ID: Hi: I've conjured up the idea of building a hex line editor as a first real Python programming exercise. To begin figuring out how to display a line of data as two-digit hex bytes, I created a hunk of data then printed it: ln = '\x00\x01\xFF 456789abcdef' for i in range(0,15): print '%.2X ' % ord(ln[i]), This prints: 00 01 FF 20 34 35 36 37 38 39 61 62 63 64 65 because print adds a space after each invocation. I only want one space, which I get if I omit the space in the format string above. But this is annoying, since print is doing more than what I tell it to do. What if I wanted no spaces at all? Then I'd have to do something obnoxious like: for i in range(0,15): print '\x08%.2X' % ord(ln[i]), This works: import sys for i in range(0,15): sys.stdout.write( '%.2X' % ord(ln[i]) ) print Is that the best way, to work directly on the stdout stream? Thanks for input. -- _____________________ Christopher R. Carlen crobc at bogus-remove-me.sbcglobal.net SuSE 9.1 Linux 2.6.5 From byte8bits at gmail.com Mon Jul 9 10:27:31 2007 From: byte8bits at gmail.com (brad) Date: Mon, 09 Jul 2007 10:27:31 -0400 Subject: catching empty strings (I guess that's what they are) Message-ID: I've began accepting user input :( in an old program. The input comes from a simple text file where users enter filenames (one per line). What is the appropriate way to handle blank lines that hold whitespace, but not characters? Currently, I'm doing this: for user_file in user_files: # Remove whitespace and make lowercase. file_skip_list.append(user_file.strip().lower()) file_skip_list = list(sets.Set(file_skip_list)) However, if the input file has blank lines in it, I get this in my list: '' (that's two single quotes with noting in between) I thought I could do something like this: if user_file == None: pass Or this: if user_file == '': pass But, these don't work, the '' is still there. Any suggestions are appreciated! Brad From Dave.Baum at motorola.com Thu Jul 12 18:42:34 2007 From: Dave.Baum at motorola.com (Dave Baum) Date: Thu, 12 Jul 2007 17:42:34 -0500 Subject: Function parameter type safety? References: <1184277163.803229.318660@g4g2000hsf.googlegroups.com> Message-ID: In article <1184277163.803229.318660 at g4g2000hsf.googlegroups.com>, Robert Dailey wrote: > Hi, > > Is there a way to force a specific parameter in a function to be a > specific type? For example, say the first parameter in a function of > mine is required to be a string. If the user passes in an integer, I > want to notify them that they should pass in a string, not an integer. At present, there isn't any built-in way to do this (see the recent thread "PEP 3107 and stronger typing" for a long discussion). However, you can use assert and isinstance() to check it manually: def foo(a): assert isinstance(a, str), "argument 'a' must be a string" I wouldn't advocate getting carried away with this pattern since it precludes your function from working with duck typing and defeats some of the dynamic nature of Python. On the other hand, without such checks the resulting exceptions from assuming an argument is one type when it is another can be a bit misleading. Dave From takveen at gmail.com Fri Jul 6 07:03:50 2007 From: takveen at gmail.com (takveen at gmail.com) Date: Fri, 06 Jul 2007 11:03:50 -0000 Subject: Learn Oracle Database Administration in 10 Minutes Message-ID: <1183719830.310797.31090@n2g2000hse.googlegroups.com> Learn Oracle Database Administration in 10 Minutes. No kidding. Check it yourself, http://www.takveen.com Only good analogy makes complex concepts simple! From giovanni.porcari at gmail.com Sat Jul 21 19:20:37 2007 From: giovanni.porcari at gmail.com (genro) Date: Sat, 21 Jul 2007 16:20:37 -0700 Subject: Pythonic way for missing dict keys In-Reply-To: <46a20f0b$0$27858$426a74cc@news.free.fr> References: <46a20f0b$0$27858$426a74cc@news.free.fr> Message-ID: <1185060037.143793.50490@n60g2000hse.googlegroups.com> On Jul 19, 6:29 am, Bruno Desthuilliers wrote: > > Myobject will be instanciated each time, yes. > > > and so if the initialization is expensive you > > will probably see surprises. > > No "surprise" here, but it can indeed be suboptimal if instanciating > myobject is costly. What about this way ? my_obj = my_dict.get(key) or my_dict.setdefault(key,myobject()) Ciao G. From bob at mellowood.ca Thu Jul 12 22:36:16 2007 From: bob at mellowood.ca (bvdp) Date: Thu, 12 Jul 2007 19:36:16 -0700 Subject: Circular import problem Message-ID: <1184294176.550267.119980@n60g2000hse.googlegroups.com> I'm going quite nutty here with an import problem. I've got a fairly complicated program (about 12,000 lines in 34 modules). I just made some "improvements" and get the following error: bob$ mma Traceback (most recent call last): File "/usr/local/bin/mma", line 55, in import MMA.main File "/usr/local/share/mma/MMA/main.py", line 33, in import MMA.docs File "/usr/local/share/mma/MMA/docs.py", line 34, in import MMA.grooves File "/usr/local/share/mma/MMA/grooves.py", line 41, in import MMA.auto File "/usr/local/share/mma/MMA/auto.py", line 35, in import MMA.parse File "/usr/local/share/mma/MMA/parse.py", line 2052, in 'AUTHOR': MMA.docs.docAuthor, AttributeError: 'module' object has no attribute 'docs' I can fix this by deleting a line in docs.py. Just take out the "import MMA.grooves" and all works. What I really don't get is that in the middle of this module which is now NOT loading "grooves.py" I have a command to access a function in that module and it works. Yes, grooves.py has an import docs.py. And there are lots of other such imports in the program. So, I have to assume that the error is being generated by some other modules loading in the grooves.py stuff ... but really have no idea. Is there anything I can do to trace though this and get it working properly? Oh, this is python 2.5.1 on Ubuntu Linux. Thanks. From supercooper at gmail.com Mon Jul 23 16:03:50 2007 From: supercooper at gmail.com (supercooper) Date: Mon, 23 Jul 2007 13:03:50 -0700 Subject: Where do they tech Python officialy ? In-Reply-To: <215fn4-60g.ln1@lairds.us> References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <215fn4-60g.ln1@lairds.us> Message-ID: <1185221030.628374.56180@q75g2000hsh.googlegroups.com> http://home.earthlink.net/~python-training/ I highly recommend Mark Lutz. Took the class last fall in Estes Park and it was worth every penny. From superflit at gmail.com Tue Jul 10 21:57:28 2007 From: superflit at gmail.com (flit) Date: Wed, 11 Jul 2007 01:57:28 -0000 Subject: Simple search and Display system, no need for db? Message-ID: <1184119048.302574.141810@w3g2000hsg.googlegroups.com> Hello All, I was discussing with a friend and we get in a hot debate. We have homepage that act like a name list. The user goes there: - Choose the building -- Department and the user receive an html table with all names . So the user gives two inputs and receive the names. Currently we are using this in mysql, This is the reason of the debate. If our list will never change and we are supposing that will be true for a long time, is it not too much use an mysql? Which kind of structure can we use in python? in web? Thanks! From mike.klaas at gmail.com Thu Jul 5 15:03:04 2007 From: mike.klaas at gmail.com (Klaas) Date: Thu, 05 Jul 2007 12:03:04 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: References: <8180ef690703310255q55572efaqc512b968504e2c1b@mail.gmail.com> Message-ID: <1183662184.771664.242970@g37g2000prf.googlegroups.com> On Jun 29, 3:48 am, "Mark Dufour" wrote: > I have just released version 0.0.22 of Shed Skin, an experimental > Python-to-C++ compiler. Among other things, it has the exciting new > feature of being able to generate (simple, for now) extension modules, > so it's much easier to compile parts of a program and use them (by > just importing them). Here's the complete changelog: > > -support for generating simple extension modules (linux/windows; see README) Great work. You might want to advertise this on the main site (currently it states that this is impossible). You've said somewhere that you didn't/don't plan on working on this aspect, but it is surely the "killer feature" of shed skin needed to for it to be able to be used as pyrex is currently (optimizing bits of larger projects). Of course, the perfect synthesis would be to combine the two projects into something that applied type inferencing with a fallback to python vm when necessary . But there is such a large gap betwixt the twain that such dreaming is but an excercise in fantasy (there's always pypy). I wish I had time to help, -Mike From rvu44vs02 at sneakemail.com Fri Jul 20 14:03:48 2007 From: rvu44vs02 at sneakemail.com (rvu44vs02 at sneakemail.com) Date: Fri, 20 Jul 2007 12:03:48 -0600 Subject: Trying to choose between python and java In-Reply-To: <1i1bcty.j0nnz4hkz078N%aleax@mac.com> Message-ID: <20070720180348.GA7658@dynamo.powerhouse.invalid> On Sun, 15 Jul 2007 at 22:28:08 -0700, Alex Martelli wrote: > James T. Dennis wrote: > ... > > You can start writing all your code now as: print() --- calling > > the statement as if it were a function. Then you're future Python > > ...except that your output format will thereby become disgusting...: > > >>> name = 'Alex' > >>> print 'Hello', name, 'and welcome to my program!' > Hello Alex and welcome to my program! > >>> print('Hello', name, 'and welcome to my program!') > ('Hello', 'Alex', 'and welcome to my program!') > > In Python 2.*, the parentheses will make a tuple, and so you'll get an > output full of parentheses, quotes and commas. I think it's pretty bad > advice to give a newbie, to make his output as ugly as this. > > > Alex > -- One possible kind of print function that might be used in the interim is something like: def print_fn(*args): """print on sys.stdout""" arg_str = " ".join([str(x) for x in args]) print arg_str -Jim From ptmcg at austin.rr.com Fri Jul 13 05:44:51 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Fri, 13 Jul 2007 02:44:51 -0700 Subject: web page text extractor In-Reply-To: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> References: <1184233345.559415.253830@m3g2000hsh.googlegroups.com> Message-ID: <1184319891.778537.71000@m3g2000hsh.googlegroups.com> On Jul 12, 4:42 am, kublai wrote: > Hello, > > For a project, I need to develop a corpus of online news stories. I'm > looking for an application that, given the url of a web page, "copies" > the rendered text of the web page (not the source HTNL text), opens a > text editor (Notepad), and displays the copied text for the user to > examine and save into a text file. Graphics and sidebars to be > ignored. The examples I have come across are much too complex for me > to customize for this simple job. Can anyone lead me to the right > direction? > > Thanks, > gk One of the examples provided with pyparsing is an HTML stripper - view it online at http://pyparsing.wikispaces.com/space/showimage/htmlStripper.py. -- Paul From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 17 03:46:57 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 17 Jul 2007 09:46:57 +0200 Subject: Dynamic method In-Reply-To: <1184621432.556914.238840@o61g2000hsh.googlegroups.com> References: <46939ba9$0$32159$426a74cc@news.free.fr> <46949c19$0$23164$426a34cc@news.free.fr> <1i1clx6.1qpf4ykihdj1oN%raims@dot.com> <469b80bb$0$23769$426a34cc@news.free.fr> <1184621432.556914.238840@o61g2000hsh.googlegroups.com> Message-ID: <469c73eb$0$25922$426a74cc@news.free.fr> Daniel a ?crit : > Bruno Desthuilliers wrote: >>> Another way is to use the 'types' module: >> True - and that's somewhat cleaner since it doesn't expose the internals >> of the descriptor protocol. OTHO, it can lead to strange results with >> callables not implementing the descriptor protocol: > > > > Actually, the result is not "strange" at all if you understand what's > going. Don't worry, *I* do exactly know what's going on !-) But we all here know that newbies already tend to get confused (or at least perplexed) by the error message they get when they forgot the self argument in methods definition... FWIW, I did experiment this situation a couple years ago, whith a coworker that, while proficient with C and Perl, was somewhat new to Python. He banged his head against the wall for near an hour before asking for help, and it took me quite a couple of minutes to figure out what was going wrong. From nick at craig-wood.com Thu Jul 12 06:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 12 Jul 2007 05:30:04 -0500 Subject: os.wait() losing child? References: <4694903B.8000105@cosc.canterbury.ac.nz> Message-ID: Jason Zheng wrote: > Nick Craig-Wood wrote: > > The problem you are having is you are letting Popen do half the job > > and doing the other half yourself. > > Except that I never wanted Popen to do any thread management for me to > begin with. Popen class has advertised itself as a replacement for > os.popen, popen2, popen4, and etc., and IMHO it should leave the > clean-up to the users, or at least leave it as an option. > > > Here is a way which works, done completely with Popen. Polling the > > subprocesses is slightly less efficient than using os.wait() but does > > work. In practice you want to do this anyway to see if your children > > exceed their time limits etc. > > I think your polling way works; it seems there no other way around this > problem other than polling or extending Popen class. I think polling is probably the right way of doing it... Internally subprocess uses os.waitpid(pid) just waiting for its own specific pids. IMHO this is the right way of doing it other than os.wait() which waits for any pids. os.wait() can reap children that you weren't expecting (say some library uses os.system())... -- Nick Craig-Wood -- http://www.craig-wood.com/nick From dak at gnu.org Sun Jul 8 16:29:52 2007 From: dak at gnu.org (David Kastrup) Date: Sun, 08 Jul 2007 22:29:52 +0200 Subject: The Modernization of Emacs: terminology buffer and keybinding References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1183841277.333384.188950@g4g2000hsf.googlegroups.com> <1183856442.027967.272530@g4g2000hsf.googlegroups.com> <1183883315.265068.61600@n60g2000hse.googlegroups.com> <1183923997.160960.3080@q75g2000hsh.googlegroups.com> Message-ID: <851wfivdtr.fsf@lola.goethe.zz> Twisted writes: > On Jul 8, 4:28 am, Adriano Varoli Piazza wrote: >> b) If you do want to keep an antediluvian copy of emacs -probably >> versioned in the negative numbers, for all you've said- please do. Do >> be so kind as to send a copy, since it might be quite valuable as an >> antique. > > Judging by the existence of the newsgroup comp.emacs, emacs is > indeed considered by some to be a quite valuable antique. Otherwise > why on earth would it have an apparently fairly active newsgroup a > full seven years into the 21st century? As opposed to your brain, Emacs has not undergone fossilization 10 years ago. While a newsgroup discussing your dim recollections of Emacs would indeed be boring (apart from the amusement value of your pomposity), a newsgroup discussing current (and evolving) versions and use of Emacs has its place. And anyway, the language C has changed much less in the last 10 years than Emacs has, and you'll still find active discussion groups for that, too: it is still very much in use, like Emacs. As a note aside, you'd be hard put to find an editor that manages a similar multitude of encodings as well as Emacs does. While it is to be expected that in the long term utf-8-encoded Unicode is the way of the future (and Emacs is going to focus more on that in future versions, too), at the moment there are few editors which keep up with the existing multitude of multibyte encodings as well as Emacs does. Emacs also makes it fairly easy to input stuff without much hassle, so you can easily write things like ?? ???? ?? ? ????? or ???? ?????????. So even if you don't like the user interface of Emacs from 10 years ago and delight in assuming that it did not change in all that time, there would be valid reasons for using it nevertheless. -- David Kastrup, Kriemhildstr. 15, 44793 Bochum From stefan.behnel-n05pAM at web.de Wed Jul 11 09:37:29 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Wed, 11 Jul 2007 15:37:29 +0200 Subject: stripping the first byte from a binary file In-Reply-To: <1184153416.798767.163740@d55g2000hsg.googlegroups.com> References: <1184063032.195000.25880@i13g2000prf.googlegroups.com> <1184115964.912526.273780@e16g2000pri.googlegroups.com> <1184148168.639675.85900@a26g2000pre.googlegroups.com> <4694B01A.30107@web.de> <1184153416.798767.163740@d55g2000hsg.googlegroups.com> Message-ID: <4694DD19.9090706@web.de> Alex Popescu wrote: > Forgive my newbie ignorance, but I am wondering why the other method > would not work? I mean it may not be very safe, > but I guess it may perform a lot better, than having to read the whole > file just to cut out the first byte. Why would you expect that? It *might* perform better if there was a system call for removing bytes from inside a file, as that could reduce the intermediate space requirements to the size of a hard disk sector rather than the remaining size of the file (note that the time consumption would not be reduced significantly, if the remaining file has to be copied around to fill the sectors). But since that is a rather rare use case that most people would prefer being handled in a safe rather than space-optimal way, I don't see the need for such a function. Stefan From exarkun at divmod.com Fri Jul 20 11:52:53 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Fri, 20 Jul 2007 11:52:53 -0400 Subject: subprocess (spawned by os.system) inherits open TCP/UDP/IP port In-Reply-To: Message-ID: <20070720155253.4947.732380741.divmod.quotient.13830@ohm> On Fri, 20 Jul 2007 08:15:39 -0500, alf wrote: >Jean-Paul Calderone wrote: > >> >> You can avoid this, if you like. Set FD_CLOEXEC on the socket after you >> open it, before you call os.system: >> >> old = fcntl.fcntl(s.fileno(), fcntl.F_GETFD) >> fcntl.fcntl(s.fileno(), fcntl.F_SETFD, old | fcntl.FD_CLOEXEC) >> > >thx for responding (I was about to send the question to twisted mailing >list too ;-). > > >still would like to find out why it is happening (now FD_CLOEXEC >narrowed may yahooing/googling searches). While realize that file >descriptors are shared by forked processes it is still weird why the >port moves to the child process once parent gets killed. what it the >parent got multiple subprocesses. It doesn't actually move. The file descriptor 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. > >Plus it is kind of unintuitive os.system does not protect from such >behavoir which is for me more an equivalent of like issuing a ne >wcommand/ starting a process from the shell. Possibly, but intuitive and software often don't go hand in hand. :) Jean-Paul From ironfroggy at gmail.com Fri Jul 20 19:14:47 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Fri, 20 Jul 2007 19:14:47 -0400 Subject: ANN: CharPy, Charlotte, NC Python Group Message-ID: <76fd5acf0707201614u4de8eafctcacb9e34624f175c@mail.gmail.com> I announced the idea earlier, but forgot to mention the state. I started a mailing list, and I want to find who in the area might be interested. Join if you can, even if you don't know you'll stick. We need to see what kind of interest there is in the area. If you are in the area, even if you aren't sure you'll attend meetups, can you recommend a good location? http://groups.google.com/group/charpy -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From faulkner891 at gmail.com Wed Jul 11 23:55:48 2007 From: faulkner891 at gmail.com (faulkner) Date: Wed, 11 Jul 2007 20:55:48 -0700 Subject: bash-style pipes in python? In-Reply-To: References: Message-ID: <1184212548.314558.203880@n60g2000hse.googlegroups.com> On Jul 11, 8:56 pm, Dan Stromberg - Datallegro wrote: > I'm constantly flipping back and forth between bash and python. > > Sometimes, I'll start a program in one, and end up recoding in the > other, or including a bunch of python inside my bash scripts, or snippets > of bash in my python. > > But what if python had more of the power of bash-style pipes? I might not > need to flip back and forth so much. I could code almost entirely in python. > > The kind of thing I do over and over in bash looks like: > > #!/usr/bin/env bash > > # exit on errors, like python. Exit on undefind variables, like python. > set -eu > > # give the true/false value of the last false command in a pipeline > # not the true/false value of the lat command in the pipeline - like > # nothing I've seen > set -o pipefail > > # save output in "output", but only echo it to the screen if the command fails > if ! output=$(foo | bar 2>&1) > then > echo "$0: foo | bar failed" 1>&2 > echo "$output" 1>&2 > exit 1 > fi > > Sometimes I use $PIPESTATUS too, but not that much. > > I'm aware that python has a variety of pipe handling support in its > standard library. > > But is there a similarly-simple way already, in python, of hooking the stdout of > process foo to the stdin of process bar, saving the stdout and errors from both > in a variable, and still having convenient access to process exit values? > > Would it be possible to overload | (pipe) in python to have the same behavior as in > bash? > > I could deal with slightly more cumbersome syntax, like: > > (stdout, stderrs, exit_status) = proc('foo') | proc('bar') > > ...if the basic semantics were there. > > How about it? Has someone already done this? class P(subprocess.Popen): def __or__(self, otherp): otherp.stdin.write(self.stdout.read()) otherp.stdin.close() return otherp def __init__(self, cmd, *a, **kw): for s in ['out', 'in', 'err']: kw.setdefault('std' + s, -1) subprocess.Popen.__init__(self, cmd.split(), *a, **kw) print (P('cat /etc/fstab') | P('grep x')).stdout.read() of course, you don't need to overload __init__ at all, and you can return otherp.stdout.read() instead of otherp, and you can make __gt__, __lt__ read and write files. unfortunately, you can't really fudge &>, >>, |&, or any of the more useful pipes, but you can make more extensive use of __or__: class Pipe: def __or__(self, other): if isinstance(other, Pipe): return ... elif isinstance(other, P): return ... def __init__(self, pipe_type): ... k = Pipe(foo) m = Pipe(bar) P() |k| P() P() |m| P() From jstroud at mbi.ucla.edu Thu Jul 12 19:04:48 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 12 Jul 2007 16:04:48 -0700 Subject: Where does str class represent its data? In-Reply-To: <1184276470.733520.265990@n2g2000hse.googlegroups.com> References: <1184196082.903895.176020@n60g2000hse.googlegroups.com> <%Egli.5395$rL1.3818@newssvr19.news.prodigy.net> <1184276470.733520.265990@n2g2000hse.googlegroups.com> Message-ID: ChrisEdgemon at gmail.com wrote: > On Jul 11, 9:49 pm, James Stroud wrote: >>The "flat is better than nested" philosophy suggests that clean should >>be module level and you should initialize a MyString like such: >> >> m = MyString(clean(s)) >> >>Where clean is >> >> def clean(astr): >> return astr.replace('m', 'f') >> >>Although it appears compulsory to call clean each time you instantiate >>MyString, note that you do it anyway when you check in your __init__. >>Here, you are explicit. > > Initially, I tried simply calling a clean function on a regular > string, without any of this messy subclassing. However, I would end > up accidentally cleaning it more than once, and transforming the > string was just very messy. Its not clear what you mean here. A code snippet might help. In theory, you can encapsulate any amount of cleaning inside a single function, so it shouldn't be messy. You need only to return the result. def fix_whitespace(astr): import string astr = ''.join(c if c not in string.whitespace else '-' for c in astr) return astr.strip() def fix_m(astr): return astr.replace('m', 'f') def clean_up(astr): return fix_m(fix_whitespace(astr)) In theory, if you didn't want a custom string to actually change its own value, this could be semantically equivalent to: new_str = astr.fix_whitespace().fix_m() The latter might be a little more readable than the former. > I thought that it would be much easier to > just clean the string once, and then add methods that would give me > the various transformations that I wanted from the cleaned string. If you intended these transformations to be new instances of MyString, then this would probably not be abuse of the str built in type. > Using __new__ seems to be the solution I was looking for. >>Additionally, it has been suggested that you use __new__. E.g.: >> >>py> class MyString(str): >>... def __new__(cls, astr): >>... astr = astr.replace('m', 'f') >>... return super(MyString, cls).__new__(cls, astr) >>... >>py> MyString('mail') >>'fail' >> >>But this is an abuse of the str class if you intend to populate your >>subclasses with self-modifying methods such as your clean method. In >>this case, you might consider composition, wherein you access an >>instance of str as an attribute of class instances. The python standard >>library make this easy with the UserString class and the ability to add >>custom methods to its subclasses: > What constitutes an abuse of the str class? Changing its value as if it were mutable. This might be ok (though not recommended) during instantiation, but you wouldn't want something like this: py> class MyString(str): ... [etc.] ... py> s = MyString('mail man') py> s 'fail fan' py> # kind-of ok up till now, but... py> s.fix_whitespace() py> s 'fail-fan' py> # abusive to str Probably better, if subclassing str, would be something more explicit: py> s = MyString('mail man') py> s 'mail man' py> s = s.fix_ms() py> s 'fail fan' py> s = s.fix_whitespace() py> s 'fail-fan' py> s = MyString('mail man') py> s 'mail man' py> s.clean_up() 'fail-fan' In this way, users would not need to understand the implementation of MyString (i.e. that it gets cleaned by default), and its behavior more intuitively resembles the built-in str class--except that MyString has added functionality. > Is there some performance > decrement that results from subclassing str like this?(Unfortunately > my implementation seems to have a pretty large memory footprint, 400mb > for about 400,000 files.) Or do you just mean from a philsophical > standpoint? Philosophical from a standpoint of desiring intuitively usable, reusable, and maintainable code. > I guess I don't understand what benefits come from using > UserString instead of just str. Probably not many if you think of MyString as I suggest above. But if you want it to be magic, as you described originally, then you might think about UserString. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From glen.e.mettler at lmco.com Thu Jul 12 17:29:43 2007 From: glen.e.mettler at lmco.com (meg99) Date: Thu, 12 Jul 2007 14:29:43 -0700 Subject: New guy help with setup In-Reply-To: References: <1184275051.504507.116080@57g2000hsv.googlegroups.com> Message-ID: <1184275783.250640.327630@g4g2000hsf.googlegroups.com> On Jul 12, 4:24 pm, Paul McNett wrote: > meg99 wrote: > > I just downloaded 2.5 and read the readme file. It says "Before you > > can build Python, you must first confiigure it....Start by running the > > script "./configure". > > > I can't find "./configure" > > > I am running Windows XP SP2 > > You downloaded the wrong file. You want the Windows Installer:http://python.org/ftp/python/2.5.1/python-2.5.1.msi > > HTH > Paul > > -- > pkm ~http://paulmcnett.com My applogies - I did download and install 2.5.1 meg99 From http Mon Jul 30 22:19:21 2007 From: http (Paul Rubin) Date: 30 Jul 2007 19:19:21 -0700 Subject: What is the "functional" way of doing this? References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> <1185838434.596591.132640@d30g2000prg.googlegroups.com> <7x3az5wjfa.fsf@ruckus.brouhaha.com> <1185839713.412656.242950@i13g2000prf.googlegroups.com> Message-ID: <7x8x8x2u3a.fsf@ruckus.brouhaha.com> James Stroud writes: > def f(n): > if n>0: > yield n%26 > for i in f(n/26): > yield i Right, this mutates i though. Let's say we have a library function itertools.iterate() and that we ignore (as we do with functions like "map") that it uses mutation under the clothes: def iterate(f, x): # generate the infinite sequence x, f(x), f(f(x)), ... while True: yield x x = f(x) Then we could write: from itertools import imap, takewhile def snd((a,b)): return b def f(n): return takewhile(bool, imap(snd, iterate(lambda (a,b): divmod(a,26), divmod(n,26)))) From ratchetgrid at googlemail.com Tue Jul 3 14:06:46 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Tue, 3 Jul 2007 19:06:46 +0100 Subject: Programming Idiomatic Code In-Reply-To: <468a373a$0$22943$426a74cc@news.free.fr> References: <468a0768$0$14120$426a74cc@news.free.fr> <468a373a$0$22943$426a74cc@news.free.fr> Message-ID: <676224240707031106n4df8964dq86d849cb8369c7f9@mail.gmail.com> > > Using a module global for this kind of data is usually a bad idea > > (except eventually for run-once throw-away scripts, and even then...) > > > > Why is this a bad idea? > > Don't you have any idea ? > -- Not really.....problem with access, using unneeded memory... I grasping at straws here... From nytrokiss at gmail.com Thu Jul 5 20:45:13 2007 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 5 Jul 2007 17:45:13 -0700 Subject: Debugger Message-ID: <8a6b8e350707051745h20021203u50dcf749bb75d56b@mail.gmail.com> Can anyone please tell me of a good debugger that can debug threads. My issue is that i have a program that is crashing only under certain threads but others are fine. And when i do it without threads it runs fine! -- http://www.goldwatches.com/watches.asp?Brand=14 http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From wojciech_mula at poczta.null.onet.pl.invalid Wed Jul 11 19:32:22 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?iso-8859-2?Q?Mu=B3a?=) Date: Wed, 11 Jul 2007 23:32:22 +0000 (UTC) Subject: atexit, sys.exit, sys.exitfunc, reaching end of source code References: <1184192510.343401.13860@57g2000hsv.googlegroups.com> Message-ID: carl.dhalluin at gmail.com wrote: > I am playing with the atexit module but I don't find a way to see the > difference > between a script calling sys.exit() and the interpreting > arriving at the end > of the source code file. This has a semantic difference for my > applications. > Is there a way to determine in an exithandler (that is registered > using atexit.register) > how I exited? Actually sys.exit raises exception SystemExit, but if interpreter reaches end of script exception is not raised. Try something like this: if __name__ == '__main__': exit_code_for_exithandler = None try: #... sys.exit(5) pass #... except SystemExit, e: exit_code_for_exithandler = e.code print "sys.exit called" else: print "end of script" w. From robert.rawlins at thinkbluemedia.co.uk Tue Jul 10 10:32:48 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Tue, 10 Jul 2007 15:32:48 +0100 Subject: Parsing Help Message-ID: <022501c7c2ff$30c4ee90$924ecbb0$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm looking for some help building a function which can parse some XML for me using ElementTree. The document is of a very consistent format and I've copied an example of the document below. Now, the piece of information I'm looking to retrieve is inside the element and is, in this example , however I want the function to return the standard integer value and not the unit8 encoded version, so instead of my function returning '0x05' it just needs to return '5' which is the standard integer version. I will be passing this XML into the function as a string, so the function will be formed something like this: Def myFunction(XmlAsString): Pass the xml and exract my value.... Return the value as an integer... I'm not sure on the best method to do this, I just want something nice and quick, lightweight and that's not resource hungry. Can anyone offer some advice on this? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From shrek2099 at yahoo.com Tue Jul 3 23:08:12 2007 From: shrek2099 at yahoo.com (shrek2099 at yahoo.com) Date: Tue, 03 Jul 2007 20:08:12 -0700 Subject: UTF-8 Support of Curses in Python 2.5 Message-ID: <1183518492.937047.214130@z28g2000prd.googlegroups.com> Hi All, Recently I ran into a problem with UTF-8 surrport when using curses library in python 2.5 in Fedora 7. I found out that the program using curses cannot print out unicode characters correctly on UTF-8 enabled console. I googled around and got an impression that the reason for this problem is that python is linked with libcurses library instead of libcursesw. The latter one is said to be able to solve this problem. Has anybody tried this? How to manually let python use libcursesw? Thanks a lot! Here is a test program: #!/usr/bin/env python # -*- coding: utf-8 -*- import curses def keyloop(stdscr): # Clear the screen and display the menu of keys stdscr_y, stdscr_x = stdscr.getmaxyx() menu_y = (stdscr_y-3)-1 str = u'This is my first curses python program. Press \'q\' to exit. (???)' stdscr.addstr(menu_y, 4, str.encode('utf-8')) xpos = stdscr_x / 2 ypos = stdscr_y / 2 while (1): stdscr.move(ypos, xpos) c = stdscr.getch() if 0 < c < 256: c = chr(c) if c in 'Qq': break else: pass elif c == curses.KEY_UP and ypos > 0: ypos -= 1 elif c == curses.KEY_DOWN and ypos < stdscr_y - 1: ypos += 1 elif c == curses.KEY_LEFT and xpos > 0: xpos -= 1 elif c == curses.KEY_RIGHT and xpos < stdscr_x - 1: xpos += 1 else: pass def main(stdscr): keyloop(stdscr) if __name__ == '__main__': curses.wrapper(main) From phd at phd.pp.ru Thu Jul 26 10:36:14 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Thu, 26 Jul 2007 18:36:14 +0400 Subject: SQLObject 0.9.1 Message-ID: <20070726143614.GI30176@phd.pp.ru> Hello! I'm pleased to announce the 0.9.1 release of SQLObject. What is SQLObject ================= SQLObject is an object-relational mapper. Your database tables are described as classes, and rows are instances of those classes. SQLObject is meant to be easy to use and quick to get started with. SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and Firebird. It also has newly added support for Sybase, MSSQL and MaxDB (also known as SAPDB). Where is SQLObject ================== Site: http://sqlobject.org Development: http://sqlobject.org/devel/ Mailing list: https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss Archives: http://news.gmane.org/gmane.comp.python.sqlobject Download: http://cheeseshop.python.org/pypi/SQLObject/0.9.1 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.9.0 ---------------- Bug Fixes ~~~~~~~~~ * Replaced calls to style.dbColumnToPythonAttr() in joins.py by name/dbName lookup in case the user named columns differently using dbName. * Minor correction in the tests: we fully support EnumCol in Postgres. * MySQLConnection now recognizes Enum, Double and Time columns when drawing the database scheme from DB. * Fixed misspelled methods in col.py. * Minor fix in FirebirdConnection.fromDatabase. * Fixed a bug with default field values for columns for firebird connection. * Prevent a deadlock in declarative.threadSafeMethod() by not reacquiring the class lock. * Run post_funcs after sending RowCreatedSignal. * Suppress the second RowUpdateSignal in .set() called from ._SO_setValue(). * Fixed a bug in col.createSQL(). * Fixed a bug in converting date/time for years < 1000 (time.strptime() requires exactly 4 digits for %Y, hence a year < 1000 must be 0-padded). Other Changes ~~~~~~~~~~~~~ * Changed string quoting style for PostgreSQL and MySQL from \' to ''. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From BjornSteinarFjeldPettersen at gmail.com Mon Jul 16 02:26:03 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: Mon, 16 Jul 2007 06:26:03 -0000 Subject: determining the source code and module based on the class In-Reply-To: References: Message-ID: <1184567163.447588.101420@22g2000hsm.googlegroups.com> On Jul 16, 6:55 am, alf wrote: ... > now I need a piece of code which based on the class name can point to > the module as well as the line number where the given class is defined. > > Is it doable in Python? look in the inspect module. -- bjorn From gabe at dragffy.com Wed Jul 25 12:34:32 2007 From: gabe at dragffy.com (Gabriel Dragffy) Date: Wed, 25 Jul 2007 17:34:32 +0100 Subject: reading data form an ISA port Message-ID: Dear list members I must admit I am a new user of Python, but it is a language that I enjoy using. For one of my university projects I need to write a program that can read several bytes from an ISA port. It has been suggested to me that I look at using C or Pyinline. If I can I would prefer to continue to use Python, and Pyinline won't play ball. I am sure Python can do this for me, but the question is how? What modules and code do I need to look? I'd be very grateful for any suggestions and advice. Best regards Gabriel Dragffy gabe at dragffy.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Mon Jul 9 10:19:59 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 09 Jul 2007 07:19:59 -0700 Subject: wxPython - ListCtrl ColumnSorterMixin sometimes works sometimes doesn't! In-Reply-To: References: Message-ID: <1183990799.052317.305080@g4g2000hsf.googlegroups.com> On Jul 7, 7:55 am, Steve Senior wrote: > Hi, > > My application has a tree control in which a user can select a filter. > This filter is then applied to the results and the results are > constructed in the ListControl (report style) widget. > > This all works fine. > > Recently I added the wx.lib.mixins.listctrl.ColumnSorterMixin mixin to > the ListCtrl widget. > > Now here is the problem. On some of the filters you can sort all of the > columns both ascending and descending - i.e. if you click a column once > it will sort properly, then if you click the column again it will > happily reverse the sort. > > On some of the filters you can only sort the column once. Repeated > clicks do not reverse the sort order. I added some print statments to > the listctrl.py to see what was happening here and it appears that when > you click the column for the second time, it actually sorts it twice > which means that the display doesn't change! > > This is really perplexing me, I've exhausted all of my options and need > some help please. > > Many Thanks, > Steve. It sounds a lot like your program is firing an event twice. What event are you using to capture the mouse-click? You are much better off posting wxPython specific questions to the wxPython user's list: http://www.wxpython.org/maillist.php Mike From mshiltonj at gmail.com Sun Jul 8 21:29:36 2007 From: mshiltonj at gmail.com (mshiltonj) Date: Mon, 09 Jul 2007 01:29:36 -0000 Subject: accessing an object instance by only having one of its attribute values In-Reply-To: <1183940993.096789.148950@22g2000hsm.googlegroups.com> References: <1183918727.033724.213010@22g2000hsm.googlegroups.com> <1183921865.879071.172730@n2g2000hse.googlegroups.com> <1183940993.096789.148950@22g2000hsm.googlegroups.com> Message-ID: <1183944576.702579.302150@g4g2000hsf.googlegroups.com> On Jul 8, 8:29 pm, Paul McGuire wrote: > On Jul 8, 2:11 pm, mshiltonj wrote: > I have some comments on the Pythonicity of your suggestions. Same > assumption, object attr is a unique key of some sort. How to create > the dict of objects, and how to retrieve an object by key. > > -- Paul I was probably being overly helpful, in a bad way. I'm new to python, I'm not very pythonic yet, and still learning the python idioms. Not sure why I slipped into the habit of testing for None, though. :-( Probably a perl thing, where I'm regularly testing for defined-ness. "if ($foo)" is different than "if (defined $foo)" Still, I'm really like python so far. From marcpp at gmail.com Thu Jul 26 10:02:33 2007 From: marcpp at gmail.com (marcpp) Date: Thu, 26 Jul 2007 16:02:33 +0200 Subject: Generating PDF reports Message-ID: Hi i'm introducing to do reports from python, any recomendation? From carl.dhalluin at qlayer.com Wed Jul 11 18:00:51 2007 From: carl.dhalluin at qlayer.com (Carl DHalluin) Date: Thu, 12 Jul 2007 00:00:51 +0200 Subject: sys.exit versus termination of source code Message-ID: <9246A60D003B924F9F28DFA2F26935C201C3E2E9@MSEVS01.outlook.hostbasket.com> Hi, I am playing with the atexit module but I don't find a way to see the difference between a script calling sys.exit() and the interpreting arriving at the end of the source code file. This has a semantic difference for my applications. Is there a way to determine in an exithandler (that is registered using atexit.register) how I exited? Second question: is there a way to determine in my exithandler what the return code was. atexit doesn't seem to support that Third question: I can solve part of my problem by reassigning sys.exit = myfunction Is that a wise idea? Thanks Carl D'Halluin www.qlayer.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From exarkun at divmod.com Tue Jul 3 11:54:39 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 3 Jul 2007 11:54:39 -0400 Subject: python 3.0 or 3000 ....is it worth waiting??? Newbie Question In-Reply-To: <1183475626.705580.214870@n2g2000hse.googlegroups.com> Message-ID: <20070703155439.4947.1855131693.divmod.quotient.6417@ohm> On Tue, 03 Jul 2007 15:13:46 -0000, "Nomad.C at gmail.com" wrote: >Hi >I'm considering learning Python...but with the python 3000 comming >very soon, is it worth waiting for?? I know that the old style of >coding python will run parallel with the new, but I mean, its going to >come to an end eventually. > >What do you think?? >Chris Python 3000 doesn't include many significant changes to the language. If you learn Python 2.x, almost all of what you learn will be applicable to Python 3.x, if you ever choose to switch to it. Since the Python development team have promised tools for porting code and a Python 2.6 which will be completely backwards compatible with Python 2.5 as well as provide feedback about code which will not be compatible with Python 3.x (), you'll be able to convert any code you write for Python 2.x into Python 3.x code easily. Jean-Paul From trentm at activestate.com Wed Jul 4 13:07:18 2007 From: trentm at activestate.com (Trent Mick) Date: Wed, 04 Jul 2007 10:07:18 -0700 Subject: ActivePython In-Reply-To: <5f0g54F396io7U1@mid.individual.net> References: <5f0g54F396io7U1@mid.individual.net> Message-ID: <468BD3C6.4000103@activestate.com> Frank Swarbrick wrote: > Why might one choose to use ActivePython instead of using the free CPython? Expanding on what Alex already said, there are a few reasons: 1. On Windows, ActivePython also includes the PyWin32 [1] extensions which otherwise you'd have to install separately over a python.org install. 2. ActivePython includes ready-to-install packages for more platforms (some of which the python.org distros also cover, of course): * Windows/x86 and Windows/x64, * Mac OS X (Universal build), * Linux/x86 and Linux/x86_64, * Solaris SPARC and x86, * HP-UX, and * AIX. For some of these platforms (e.g. Linux), a fair amount of work has been done to ensure you can use all of the core extensions (e.g. Tkinter, bsddb, bzip2, etc.) out of the box without running into dependency issues. ActivePython's installer on the Un*x platforms also makes it easy to install either in a shared location or in a user-specific location. 3. ActivePython includes a number of extra documentation sets that may prove useful to some. E.g. "Dive Into Python", a non-programmer's tutorial for Python, the Python HOWTOs, a snapshot of the Python PEPs, the Python FAQs, back copies of Andrew Kuchling's excellent "What's New in Python" Some sometimes mentioned, but untrue reasons to avoid ActivePython: - It doesn't include OpenSSL bindings. As of ActivePython 2.5.0.0, full SSL bindings are included. - It isn't free. See my answer to Steve, below. - It isn't compatible with python.org's Python distro. It is. If there is a case where this isn't the case, it is a serious bug. Some more details here: http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/whatsincluded.html To answer some questions from others on this thread: tleeuwenburg wrote: > Well, Komodo is a nice enough IDE, so you might choose to use > ActivePython for integration reasons, and maybe it's a little easier > on Windows. > > However, I would have thought that if you were planning to distribute > an application, you would want to choose CPython for maximum > interoperability with external packages. Note that Komodo in no way, "prefers" ActivePython over a python.org installation. One of the primary requirements of ActivePython is to fully binary compatible with a python.org build of the same version -- if it isn't, it is a serious bug. As well, with Komodo we aren't *at all* interested in locking people in to our language distros. (BTW: I also work on Komodo.) > The ActiveState web page doesn't > really talk about their reasons very much. As to reasons for ActivePython: ActiveState believes in the dynamic languages (all of the developers here are very passionate about that) and we are both happy to and view it as in our best interests to do what we can to ensure that the dynamic language communities are vibrant and competitive with the more corporate-backed languages and technologies. Of course, it isn't pure altruism, but more of a symbiosis. ActiveState provides for-pay contracts for Perl, Python and Tcl distributions for things like specific support and builds (for example, some companies are happy to pay for the leg-work for an up-to-date Python installer for an old version of HP-UX that supports their C++ extensions). Generally, any patches that we've worked on for these kinds of things are provided back to the language cores so that everyone benefits. As well, these contracts allow us to maintain a large number of build and test machines for the for-pay and free Active* distros -- and to buy food for developers such as myself. Steve Holden wrote: > ...the last time I looked the ActivePython distribution > doesn't allow redistribution at all (i.e. it's not technically open > source). Steve is correct that ActivePython isn't open source. It is free (as in beer), meaning that it is completely free for you to download, install and use on as many machines as you want. As to redistribution: Yes, it is technically correct that you cannot fully redistribute ActivePython without our permission. However, ActivePython's license expressly *does* allow you to use the "freezing" utilities such as "py2exe" and "py2app" -- so you have no worries there. For fully embedding Python in an application, in my experience [2] you'll want to be building your own Python anyway. Sincerely, Trent Python Tech Lead at ActiveState also, a Komodo developer [1] PyWin32 is primarily a set of extensions that provide Python bindings to much of the Windows API and to Windows COM. It also includes an editor/IDE called PythonWin. [2] Komodo embeds its own Python build for doing a lot of the core logic. A custom Python build is generally necessary to avoid cross-talking between Komodo's Python and other possible Pythons on the system. -- Trent Mick trentm at activestate.com From nephish at gmail.com Thu Jul 5 13:32:08 2007 From: nephish at gmail.com (nephish) Date: Thu, 05 Jul 2007 17:32:08 -0000 Subject: need help with converting c function to python function Message-ID: <1183656728.610086.178080@k79g2000hse.googlegroups.com> hello all, i have a c function from some modbus documentation that i need to translate into python. it looks like this: unsigned short CRC16(puchMsg, usDataLen) unsigned char *puchMsg ; unsigned short usDataLen ; { unsigned char uchCRCHi = 0xFF ; unsigned char uchCRCLo = 0xFF ; unsigned uIndex ; while (usDataLen--) { uIndex = uchCRCHi ^ *puchMsgg++ ; uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ; uchCRCLo = auchCRCLo[uIndex] ; } return (uchCRCHi << 8 | uchCRCLo) ; } some of it i can make out, but i can't seem to figgure out this part ' auchCRCHi[uIndex}; it looks like a typo, because there is a closing } that does not match the opening [. here is what i have so far, but is not giving me the right values def crc16(data): crc_hi = 0xff crc_lo = 0xff for x in data: crc_index = crc_hi ^ x crc_hi = crc_lo ^ (crc_hi | crc_index) crc_lo = crc_lo | crc_index return (crc_hi << 8 | crc_lo) whaddya think? thanks From kishoremanikonda at gmail.com Mon Jul 16 05:25:49 2007 From: kishoremanikonda at gmail.com (Kishore kumar Manikonda) Date: Mon, 16 Jul 2007 14:55:49 +0530 Subject: intact Message-ID: <384ea5a0707160225ob16e8e5g47bc39f97ce2b81f@mail.gmail.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam.themindstorm at gmail.com Sun Jul 22 06:55:15 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Sun, 22 Jul 2007 10:55:15 +0000 (UTC) Subject: Pythonic way for missing dict keys References: <1185041243.323915.161230@x40g2000prg.googlegroups.com> Message-ID: Zentrader wrote in news:1185041243.323915.161230 @x40g2000prg.googlegroups.com: > On Jul 21, 7:48 am, Duncan Booth wrote: > > [snip...] > > >>From the 2.6 PEP #361 (looks like dict.has_key is deprecated) > Python 3.0 compatability: ['compatibility'-->someone should use a > spell-checker for 'official' releases] > - warnings were added for the following builtins which no > longer exist in 3.0: > apply, callable, coerce, dict.has_key, execfile, reduce, > reload > I see... what that document doesn't describe is the alternatives to be used. And I see in that list a couple of functions that are probably used a lot nowadays (callable, reduce, etc.). bests, ./alex -- .w the_mindstorm )p. From nagle at animats.com Tue Jul 3 14:07:03 2007 From: nagle at animats.com (John Nagle) Date: Tue, 03 Jul 2007 11:07:03 -0700 Subject: object references/memory access In-Reply-To: References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1183407411.397142.304790@e16g2000pri.googlegroups.com> Message-ID: Steve Holden wrote: > Karthik Gurusamy wrote: > >> On Jul 1, 12:38 pm, dlomsak wrote: > > [...] > >> >> I have found the stop-and-go between two processes on the same machine >> leads to very poor throughput. By stop-and-go, I mean the producer and >> consumer are constantly getting on and off of the CPU since the pipe >> gets full (or empty for consumer). Note that a producer can't run at >> its top speed as the scheduler will pull it out since it's output pipe >> got filled up. This is in fact true, but the overheads of CPython are so large that you don't usually see it. If message passing in CPython is slow, it's usually because the marshalling cost is too high. As I mentioned previously, try "pack" instead of "pickle" or "repr" if you control the interface on both ends of the connection. I've used QNX, the message-passing real time operating system, extensively. QNX has the proper mechanisms to handle interprocess communication efficiently; we could pipe uncompressed video through the message passing system and only use 3% of the CPU per stream. QNX deals with the "stop and go" problem properly; interprocess communication via MsgSend and MsgReceive works more like a subroutine call than a queued I/O operation. In the normal case, you pay for a byte copy and a context switch for a message pass, but it's not necessary to take a trip through the scheduler. Not many operating systems get this right. Minix 3 does, and there are infrequently used facilities in NT that almost do. But pipes, sockets, and System V IPC as in Linux all take you through the scheduler extra times. This is a killer if there's another compute bound process running; on each message pass you lose your turn for the CPU. (There have been worse operating systems. The classic MacOS allows you one (1) message pass per clock tick, or 60 messages per second.) John Nagle From http Sat Jul 28 14:27:50 2007 From: http (Paul Rubin) Date: 28 Jul 2007 11:27:50 -0700 Subject: Where do they tech Python officialy ? References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> Message-ID: <7xejis7595.fsf@ruckus.brouhaha.com> Omari Norman writes: > Just curious--what language would you recommend as most > beginner-friendly? I'm not sure what to suggest, I don't pay much attention to this area. Maybe Logo? > > With some reasonable experience in Scheme or > > Mozart or Haskell, plus a Python manual, you'll be well on your way. > I had heard of these languages, but learning them is a bit discouraging > because (Java excepted) they don't seem to get much practical use. I wouldn't worry about that. It's like saying it's discouraging to learn in engineering class how to solve problems involving frictionless pulleys because you can't buy those in practice. The idea in each of the above cases is to strip the problem to its bare essentials for study. Dealing with real-world complications can come later. From Brad.Johnson at ballardtech.com Mon Jul 30 19:16:59 2007 From: Brad.Johnson at ballardtech.com (Brad Johnson) Date: Mon, 30 Jul 2007 23:16:59 +0000 (UTC) Subject: win32 question in Python References: <1185836292.076175.215860@j4g2000prf.googlegroups.com> Message-ID: Cappy2112 gmail.com> writes: > > > Hello Brad, > > If you don't get a reply here, there is a win32 specific Python list > on ActiveState.com wher ethey do talk about excel & other Win32 python > issues. > Thanks, but I believe this you meant to address the OP Shun-Hsien, not me. Just wanted to clarify in case that confused anyone. From mail at microcorp.co.za Wed Jul 11 02:56:18 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 11 Jul 2007 08:56:18 +0200 Subject: Should I use Python for these programs? References: Message-ID: <000301c7c3be$40fd67a0$03000080@hendrik> "CC" wrote: 8< ----------------------------------------------------------- > Basically, it's almost impossible to use > ethernet on other than PCs, on the official LAN. > > I will have to look into this further though, as higher data rate stuff > is a problem with serial. Although I could do 10Mbps RS-422 I suppose. This kind of implies USB into the PC - Haven't seen a 16550 driven much above 1Mb/s As you have a DSP in the system think about USB (with the chips you mentioned) into a DSP then the DSP's serial port converted to RS-485 for every signal (clock, data in and out and sync) and then everything is native DSP on the remote device. That gives you multiple channels of better than Audio response, full duplex. And since your eyes are slower than your ears, that should be good enough... - Hendrik From mccredie at gmail.com Fri Jul 6 12:06:02 2007 From: mccredie at gmail.com (Matimus) Date: Fri, 06 Jul 2007 16:06:02 -0000 Subject: Expandable 2D Dictionaries? In-Reply-To: <1183736635.415927.208450@57g2000hsv.googlegroups.com> References: <1183736635.415927.208450@57g2000hsv.googlegroups.com> Message-ID: <1183737962.406659.223690@e16g2000pri.googlegroups.com> I'm not sure I completely understand what you want, but if you are using Python2.5 defaultdict might be useful. Below is some example code using defaultdict. [code] from collections import defaultdict myvar = defaultdict(dict) myvar["cat"]["paw"] = "SomeString" myvar["dog"]["tail"] = "wags" myvar["cat"]["tongue"] = "sand-paper" myvar["mouse"]["likes"] = "cheese" [/code] The documentation can do a better job of explaining how this works than I can: http://docs.python.org/lib/defaultdict-objects.html -Matt From nogradi at gmail.com Tue Jul 3 11:25:42 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 3 Jul 2007 17:25:42 +0200 Subject: python 3.0 or 3000 ....is it worth waiting??? Newbie Question In-Reply-To: <1183475626.705580.214870@n2g2000hse.googlegroups.com> References: <1183475626.705580.214870@n2g2000hse.googlegroups.com> Message-ID: <5f56302b0707030825r22414343l4129a97465965184@mail.gmail.com> > Hi > I'm considering learning Python...but with the python 3000 comming > very soon, is it worth waiting for?? I know that the old style of > coding python will run parallel with the new, but I mean, its going to > come to an end eventually. > > What do you think?? > Chris 99% of what you would learn from python 2.x will be useful for python 3.0. HTH, Daniel From nick at craig-wood.com Tue Jul 10 05:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 10 Jul 2007 04:30:04 -0500 Subject: "Empty" text References: <469147b8$1@griseus.its.uu.se> <5fd1aeF3berb8U1@mid.uni-berlin.de> <1184027996.534390.315640@22g2000hsm.googlegroups.com> Message-ID: Miles wrote: > On Jul 9, 4:30 am, Nick Craig-Wood wrote: > > Marc 'BlackJack' Rintsch wrote: > > > On Sun, 08 Jul 2007 22:23:20 +0200, Jan Danielsson wrote: > > > > Firefox is very unhappy about the textarea not having separate > > > > opening and a closing tags. i.e. I need this: > > > > > > Then either Firefox is broken or you don't declare your XHTML properly and > > > Firefox thinks it's HTML. > > > > I suspect the former - we noticed exactly the same thing (can't > > remember which tags we were having problems with), using the > > declaration :- > > > > > > > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> > > > > I haven't tested this again recently though. > > Firefox is not broken. The XML prolog and DOCTYPE do not affect HTML > vs. XHTML interpretation--only the Content-Type does. If you are > serving a page as "text/html", which you almost certainly are, then > all browsers will parse it as HTML, regardless of prolog and doctype, > and HTML does not support self-closing tags. You need to serve the > page as "application/xhtml+xml", or avoid self-closing tags on > elements other than ,
    , , etc. > > http://www.w3.org/TR/xhtml1/#C_3 Ah very good - that solves that mystery - thank you! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From vedrandekovic at v-programs.com Tue Jul 31 05:44:12 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Tue, 31 Jul 2007 02:44:12 -0700 Subject: simple string backspace question Message-ID: <1185875052.153091.23300@19g2000hsx.googlegroups.com> Hello, I have one simple string, backspace character question.Here is my example: >>> text="Hello\bworld" >>> print text "HelloBSworld" Should this character "\b" (backspace) in this text return this: "Helloworld"? Regards, Vedran From star.public at gmail.com Tue Jul 17 12:46:37 2007 From: star.public at gmail.com (star.public at gmail.com) Date: Tue, 17 Jul 2007 09:46:37 -0700 Subject: In a dynamic language, why % operator asks user for type info? In-Reply-To: <1184653181.658840.237510@n2g2000hse.googlegroups.com> References: <1184631007.920803.147790@j4g2000prf.googlegroups.com> <1184653181.658840.237510@n2g2000hse.googlegroups.com> Message-ID: <1184690797.892697.163320@d30g2000prg.googlegroups.com> On Jul 17, 2:19 am, Paddy wrote: > On Jul 17, 1:10 am, Karthik Gurusamy wrote: > > > > > > > Hi, > > > The string format operator, %, provides a functionality similar to the > > snprintf function in C. In C, the function does not know the type of > > each of the argument and hence relies on the embedded % > > specifier to guide itself while retrieving args. > > > In python, the language already provides ways to know the type of an > > object. > > > So in > > > output = '%d foo %d bar" % (foo_count, bar_count), > > why we need to use %d? I'm thinking some general common placeholder, > > say %x (currently it's hex..) could be used. > > > output = '%x foo %x bar" % (foo_count, bar_count). > > Since % by definition is string formatting, the operator should be > > able to infer how to convert each of the argument into strings. > > > If the above is the case, we could've avoided all those exceptions > > that happen when a %d is specified but say a string is passed. > > > Thanks, > > Karthik > > '%s' might be what your after as a more 'general purpose' moifier. > > - Paddy.- Hide quoted text - > > - Show quoted text - It is good for that; I generally use %s until I decide that something needs picky formatting. -- a = '%s Weaver' % random.choice(['Lani','Star','Azure']) a += 'is strange.' From redgrittybrick at spamweary.foo Fri Jul 27 12:12:48 2007 From: redgrittybrick at spamweary.foo (RedGrittyBrick) Date: Fri, 27 Jul 2007 17:12:48 +0100 Subject: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: <7x4pjq7v69.fsf@ruckus.brouhaha.com> References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> <7x4pjq7v69.fsf@ruckus.brouhaha.com> Message-ID: <46aa1986$0$31715$db0fefd9@news.zen.co.uk> Paul Rubin wrote: > M brad writes: > >> Out of the pan and into the fire. :) Welcome to the world of Ph.D's >> in Computer Science. You think the Perl guys have attitude, just >> wait and see what you're in for over here. I think you'll find >> attitudes in any programming language... just different types. May >> God have mercy on your soul! You'll be making a similar >> announcement in a few weeks when you switch to Ruby :) The cold, >> cruel theoretical, lofty Python will mercilessly crush you :) > > > Come over to comp.lang.functional sometime. I thought I was hardcore > but my brain is not big enough for that newsgroup. http://www.catb.org/~esr/faqs/smart-questions.html#not_losing 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. I find it best to treasure the saints, tolerate the irritable and ignore the whiners. YMMV. -- RGB No saint. From the.mindstorm.mailinglist at gmail.com Fri Jul 6 05:17:10 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Fri, 06 Jul 2007 02:17:10 -0700 Subject: Re-raising exceptions with modified message In-Reply-To: References: <1183668029.470160.218230@q69g2000hsb.googlegroups.com> <1183673210.409169.51830@n2g2000hse.googlegroups.com> Message-ID: <1183713430.018956.46380@w3g2000hsg.googlegroups.com> On Jul 6, 4:20 am, Christoph Zwerschke wrote: > Alex Popescu wrote: > > Probably the simplest solution would be to create a new exception and > > wrapping the old one and the additional info. Unfortunately, this > > may have a huge impact on 3rd party code that was catching the > > original exception. So, I think you should create an utility > > factory-like function that is either creating a new exception > > instance as the one caught and with the additional information, > > Right, I have gone with that (see the example with the PoliteException > class somewhere below). > > > or an utility that knows how to modify the caught exception according > > to its type. > > I guess you mean something like this (simplified): > > except Exception, e: > if getattr(e, 'reason'): > e.reason += "sorry" > else: > e.message += "sorry" > > The problem is that these attribute names are not standardized and can > change between Python versions. Not even "args" is sure, and if a class > has "message" it does not mean that it is displayed. Therefore I think > the first approach is better. > > > In the first case you will need somehow to tell to the new instance > > exception the real stack trace, because by simply raising > > a new one the original stack trace may get lost. > > Yes, but thats a different problem that is easy to solve. > Yeah maybe for a python guy, but I am a newbie. I would really appreciate if you can show in this thread how this can be done in Python. tia, ./alex -- .w( the_mindstorm )p. PS: sorry for reposting, but it looks like my previous message hasn't gone through :-(. From siona at chiark.greenend.org.uk Tue Jul 10 08:02:11 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 10 Jul 2007 13:02:11 +0100 (BST) Subject: path backslash escaping trouble References: <1184031604.157526.45120@c77g2000hse.googlegroups.com> Message-ID: <7ap*q1nPr@news.chiark.greenend.org.uk> placid wrote: >I have these files; [ ... ] > >MergeType::::codefromlabel:::: >BLname::::BUILDMODS:::: >OldLname:::::::: >BaseVersion::::6.9.1.24A:::: >RequiredRelease::::6.10.1.3:::: >Description:::::::: >FixRelation:::::::: >Dependencies:::::::: >LpAffected::::No:::: >CodeReview::::FirstName LastName:::: >Testing::::Compile/Build;Designer;Smoketests;:::: >OtherTesting:::::::: >Vobs::::ipsupport;:::: >Elements::::\ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3:::: > >i read this whole file into a string so i can search for the value of >Elements which is >\ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3 > >but this path is escaped >\\ipsupport\\ipbuild\\Wizard\\build.pl@@\\main\\buildmods\\3 How are you reading the file in? Are you absolutely sure that the escaping appears *in the string*, and isn't being done by whatever you're using to inspect it? Consider: >>> s = open('/tmp/Elements').read() >>> s 'Elements::::\\ipsupport\\ipbuild\\Wizard\\build.pl@@\\main\\buildmods\\3::::\n' >>> len(s) 70 Now, if those backslashes had *really* been escaped, the string would be length 77, wouldn't it? >>> s.find('\\\\') -1 And find() can't find any double-backslashes in there. -- \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 bj_666 at gmx.net Mon Jul 30 07:02:03 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Jul 2007 11:02:03 GMT Subject: How to write GUI and event separately in wxPython?? References: <1185777254.925902.204500@z28g2000prd.googlegroups.com> <5h5kmiF3hmufcU3@mid.uni-berlin.de> Message-ID: <5h5upbF3hmufcU5@mid.uni-berlin.de> On Mon, 30 Jul 2007 06:32:55 -0400, Steve Holden wrote: > >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)] > True First I thought: Why the unnecessary list comprehension but to my surprise: In [33]: xrange(42) == xrange(42) Out[33]: False That's strange. Ciao, Marc 'BlackJack' Rintsch From bdesth.quelquechose at free.quelquepart.fr Sun Jul 22 03:01:21 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 22 Jul 2007 09:01:21 +0200 Subject: Singleton in Python Cookbook In-Reply-To: References: Message-ID: <46a7c363$0$19625$426a34cc@news.free.fr> Alex Popescu a ?crit : > Hi all! > > I was reading through Python Cookbook the Singleton recipe. At this moment > I am a bit puzzled as the example in the book is not working resulting in: > > TypeError: type.__new__(SingleSpam): SingleSpam is not a subtype of type > > (I haven't presented the original code as I am not sure about copyrights). I don't have the book, so if you don't post the code, I just give up trying to guess what the problem can be. From hey at mikehowarth.co.uk Fri Jul 27 08:54:00 2007 From: hey at mikehowarth.co.uk (Mike Howarth) Date: Fri, 27 Jul 2007 05:54:00 -0700 (PDT) Subject: Factory pattern again In-Reply-To: <46a9c21f$0$18765$426a74cc@news.free.fr> References: <11825158.post@talk.nabble.com> <46a9c21f$0$18765$426a74cc@news.free.fr> Message-ID: <11828597.post@talk.nabble.com> Thanks that makes absolute sense. I was sure it was something simple, thanks for your time. Bruno Desthuilliers-5 wrote: > > Mike Howarth a ?crit : >> Hi >> >> I was wondering whether anyone could help me, I'm pretty new to python >> coming from a PHP background and I'm having a few products in getting my >> head round how to write the factory pattern within python. >> >> I'm currently looking to try to return values from a db and load up the >> relevant objects, values returned are product type (I,S) and product code >> (123). >> >> At the moment I've adapted some code I've found illustrating the factory >> method but ideally I would like to use the type to load up the relevant >> object. >> >> Another issue I've found is that I don't seem to be able to access to the >> price attribute of each of the object. I'm sure these are very >> straightforward issues however I seem to have tied myself in knots over >> this >> and could do with a fresh set of 'pythonic' eyes to help me out. >> >> registry = {} >> >> class MetaBase(type): >> def __init__(cls, name, bases, dict): >> registry[name] = cls >> >> class Product(object): >> __metaclass__ = MetaBase >> >> class Item(Product): >> def __init__(self, *args, **kw): >> self.price = 1 >> >> class Set(Product): >> def __init__(self, *args, **kw): >> self.price = 2 >> >> def factory(kind, *args, **kw): >> return registry[kind](*args, **kw) >> >> >> item = registry['Item'] > > This returns the Item *class*, not an instance of... So the following: > >> print item.price > > cannot work, since price is an instance attribute, not a class attribute. > > What you want is: > > item = factory('Item') > print item.price > > HTH > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Factory-pattern-again-tf4156186.html#a11828597 Sent from the Python - python-list mailing list archive at Nabble.com. From mail at microcorp.co.za Sun Jul 22 03:55:27 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 22 Jul 2007 09:55:27 +0200 Subject: Pickled objects over the network References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com><011401c7caa0$3e3e5900$03000080@hendrik> <012901c7cb60$5ba530c0$03000080@hendrik> Message-ID: <00c601c7cc38$d826ba00$03000080@hendrik> "Steve Holden" wrote: > I think someone has already pointed out netstrings, which will allow you > to send arbitrary strings over network connections deterministically. Yes I brought it up > I'm afraid for the rest it's just a matter of encoding your information > in a way that you can decode without allowing a malicious sender to > cause arbitrary code to be called. Yes - and in general you do this by having both the sender and the transmitter conform to some pre agreed format - a netstring is one of the simplest of such things - another way is to "frame" records between some kind of delimeter and to "escape" the occurences of the delimiter in the data. Another way is to use simple "self defining fields" that work by giving fields a "tag" number from a list of pre defined things, as well as a length, followed by the data - some financial protocols work as a variant of this concept, where the presence or absence of a bit signify the presence or absence of a field in the record. The problem with all of these schemes is that they are all a PITA to implement, compared to the ease with which you can pickle and unpickle something like a simple dict of parameters. And if that is all you want to pass over to some remote thing, then having to download and import Pyro is an equal PITA and overkill. - It adresses a far more sophisticated problem than just getting some small things across the network. Now if Pyro were to make it into the standard library, it would be my method of choice for even this silly level of functionality, because I happen to think it rocks. > > The issue with pickle is that it's way too general a mechanism to be > secure in open network applications, so a suggestion to beef up its > security was misguided. Trying to "beef up pickle's security" is like > trying to make a shotgun that can't kill anything. > Is it really that impossible to add something like a "noeval" flag, or to force it to only give you a string or a dict if you ask for one or the other, given that someone has already mentioned that the built in types are decoded by separate routines? Or more generally - as it already has different protocols - to define a protocol that won't pass executable stuff over, or one that will only pass and accept the built in types? - Hendrik From martin at v.loewis.de Tue Jul 31 16:31:46 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Tue, 31 Jul 2007 22:31:46 +0200 Subject: encode() question In-Reply-To: <5h9hjsF3j641tU3@mid.uni-berlin.de> References: <1185900791.595830.21290@d55g2000hsg.googlegroups.com> <1185903926.955444.43620@22g2000hsm.googlegroups.com> <5h9hjsF3j641tU3@mid.uni-berlin.de> Message-ID: <46AF9C32.7030602@v.loewis.de> >>> str.decode and unicode.encode should NOT exist, or at least issue a >>> warning (IMHO). >>> >> Yes, that sounds like a good idea. > > It sounds like horrible idea as those are the ones that are really needed. Correct. > One could argue about `str.encode` and `unicode.decode`. But there are at > least uses for `str.encode` like 'sting-escape', 'hex', 'bz2', 'base64' > etc. Indeed, in Py3k, those will be gone. Regards, Martin From hhartwig at gmail.com Thu Jul 5 11:58:58 2007 From: hhartwig at gmail.com (Hardy) Date: Thu, 05 Jul 2007 08:58:58 -0700 Subject: list.append not working? Message-ID: <1183651138.209079.37620@q75g2000hsh.googlegroups.com> I experience a problem with append(). This is a part of my code: for entity in temp: md['module']= entity.addr.get('module') md['id']=entity.addr.get('id') md['type']=entity.addr.get('type') #print md mbusentities.append(md) #print mbusentities I want something like: [{'module': 'home', 'id': 123, 'type': 'core'}, {'module': 'work', 'id': 456, 'type': 'core'}] md is always correct, BUT:mbusentities is wrong. Length of mbusentities is same of temp, so it appended everything. BUT: mbusentities only shows the values of the last append: [{'module': 'work', 'id': 456, 'type': 'core'}, {'module': 'work', 'id': 456, 'type': 'core'}] What's wrong? From the.mindstorm.mailinglist at gmail.com Wed Jul 18 07:43:33 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Wed, 18 Jul 2007 11:43:33 +0000 (UTC) Subject: how to find available classes in a file ? References: <2e302$469bf38f$d443bb3a$30036@news.speedlinq.nl> <1184627599.597658.267380@g4g2000hsf.googlegroups.com> <1184752801.010805.241490@e9g2000prf.googlegroups.com> Message-ID: Alex Popescu gmail.com> writes: > > On Jul 17, 4:41 am, "Gabriel Genellina" yahoo.com.ar> > wrote: > > En Mon, 16 Jul 2007 20:13:19 -0300, Alex Popescu > > gmail.com> escribi > I apologize for posting the previous message a couple of times, but I wasn't seeing it displayed on the Google groups. ./alex -- .w( the_mindstorm )p. From joejacob21 at gmail.com Sun Jul 22 23:22:07 2007 From: joejacob21 at gmail.com (joe jacob) Date: Mon, 23 Jul 2007 03:22:07 -0000 Subject: Configure apache to run python scripts Message-ID: <1185160927.844397.244290@e16g2000pri.googlegroups.com> I need to configure apache to run python scripts. I followed the steps mentioned in this site (http://www.thesitewizard.com/archive/ addcgitoapache.shtml). But I am not able to run python scripts from Firefox, I got a forbidden error "you do not have permission to access the file in the server" when I try to run the script form Firefox browser. Somebody please help me. From attn.steven.kuo at gmail.com Mon Jul 30 19:55:13 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Mon, 30 Jul 2007 16:55:13 -0700 Subject: What is the "functional" way of doing this? In-Reply-To: <7x3az5wjfa.fsf@ruckus.brouhaha.com> References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> <1185838434.596591.132640@d30g2000prg.googlegroups.com> <7x3az5wjfa.fsf@ruckus.brouhaha.com> Message-ID: <1185839713.412656.242950@i13g2000prf.googlegroups.com> On Jul 30, 4:39 pm, Paul Rubin wrote: > "attn.steven.... at gmail.com" writes: > > Recursion is common in functional programming: > > > def f(n, l=None): > > if l == None: > > l = [] > > if n > 0: > > return f(n/26, l + [n%26]) > > else: > > return l > > > print f(1000) > > Right, this is functional style, but quite painful in Python (no tail > recursion, and look at all that list copying). Yes, I agree that performance would greatly suffer. This is really idomatic Lisp re-written as Python and was the first thing that popped into my head when the OP mentioned 'functonal'. Your generator/iterator solution should run must faster. -- Regards, Steven From bbxx789_05ss at yahoo.com Sat Jul 28 18:28:33 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 28 Jul 2007 15:28:33 -0700 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1185661482.675336.134720@b79g2000hse.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> <1184458002.961657.267830@x35g2000prf.googlegroups.com> <1184466882.446791.127670@x35g2000prf.googlegroups.com> <1185658013.859359.47700@57g2000hsv.googlegroups.com> <1185660599.329035.193820@d55g2000hsg.googlegroups.com> <1185661482.675336.134720@b79g2000hse.googlegroups.com> Message-ID: <1185661713.452663.201550@19g2000hsx.googlegroups.com> My PATH environment variable looks like this: PATH=/Library/Frameworks/Python.framework/Versions/Current/bin:/bin:/ sbin:/usr/bin:/usr/sbin:/usr/local/mysql/bin From tylerca at jeld-wen.com Mon Jul 30 11:07:52 2007 From: tylerca at jeld-wen.com (Azazello) Date: Mon, 30 Jul 2007 15:07:52 -0000 Subject: Process Control Help In-Reply-To: References: <1185570527.665048.48780@e9g2000prf.googlegroups.com> Message-ID: <1185808072.695752.20720@z28g2000prd.googlegroups.com> On Jul 28, 1:40 am, "Hendrik van Rooyen" wrote: > wrote: > > > I'm attempting to start some process control using Python. I've have > > quite a bit of literature on networking, and have made some tinkering > > servers and clients for different protocols HTTP, FTP, etc... But now > > it's time for the murky web of industrial protocol. I'm looking to > > start with IO and servo controls via Ethernet. > > > Questions: > > > Is there an existing forum on this already? > > What protocols are the most python friendly? i.e. are transparent > > enough that i can create my own python driver. (or do these drivers > > exist?) > > What ethernet accesible servo and IO industrial devices have people > > had success with? > > What is it that you are trying to do? > Some of the commercial devices come with their own software, and > you may not need python or anything else. > A lot of the industrial connectivity is still RS-485 or RS-422 and not > Ethernet based - although some of the protocols, have, I think, been ported. > > If you say more, then someone can maybe help you, as there are quite a few > people on this group who seem to dabble in process control. > > - Hendrik- Hide quoted text - > > - Show quoted text We're looking to run some industrial machinery from a PC. Starting with some basic servo controls and IO port reading for something like an XYZ table (just X would be a good start!). Now there is some existing software out there for PC control but this software is, to my understanding, largely unnecessary and "black box". This "black box" creates a problem when trying to e.g. control servos and IO with the same program. And if we want to include an HMI like a touchscreen, or export the machinery's production into a RSS feed, the web of software becomes messy and slow. If we could consolidate this software into a single, non "black-box" package, we could see significant improvements in development time. Having to program 3 different devices with three different languages to control your PLC, Servos, and module X is the status quo we face, but it is quite frustrating and limited. Soo.... I need to find some ethernet friendly IO, serial would be fine but but it's a leash in many instances. I know some protocols have been ported to ethernet, but I am having extreme difficulty figuring out what these protocols entail. ModBus/TCP is the one I'd like to choose. I know that people have done this kind of software but it seems that industrial python remains a bit taboo because of proprietary issues... Ty From beliavsky at aol.com Mon Jul 16 13:40:06 2007 From: beliavsky at aol.com (Beliavsky) Date: Mon, 16 Jul 2007 10:40:06 -0700 Subject: Pass by reference or by value? In-Reply-To: <1184385535.558451.306630@22g2000hsm.googlegroups.com> References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> <1184385535.558451.306630@22g2000hsm.googlegroups.com> Message-ID: <1184607606.805940.56980@22g2000hsm.googlegroups.com> On Jul 13, 11:58 pm, sturlamolden wrote: > In Fortran you can only pass references. > > integer(4) :: a > a = 1 > call bar(a) > > subroutine bar(a) > integer(4) :: a > a = 0 ! side-effect > end subroutine > > That means, when a variable is used to call a function, the function > receives a pointer to the actual argument, not a local copy. That is > very different from C's copy-passing behaviour. In Fortran, if a procedure argument is modified within the procedure, that change is propagated to the value of the argument in the caller. The standard does NOT mandate how this is accomplished, and one could in theory write a compiler that makes a local copy of all procedure arguments, as long as the variables passed as arguments were updated in the caller. Early implementations of Fortran 90 often made copies of array arguments, hurting performance. Current compilers do this less often. It is common to pass constants and expressions to Fortran procedures, which does not fit the pass-by-reference paradigm. Fortran 2003 has the VALUE attribute to give the C pass-by-value behavior when desired. From horpner at yahoo.com Wed Jul 25 15:26:57 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 25 Jul 2007 19:26:57 GMT Subject: is_iterable function. References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> Message-ID: <5uNpi.36822$G23.3430@newsreading01.news.tds.net> On 2007-07-25, danmcleran at yahoo.com wrote: > You can use the built-in dir() function to determine whether or not > the __iter__ method exists: I think you might have to check for __getitem__, also, which may support the sequence protocol. > def is_iterable(thing): > return '__iter__' in dir(thing) So then: def is_iterable(thing): return '__iter__' in dir(thing) or '__getitem__' in dir(thing) Speaking of the iter builtin function, is there an example of the use of the optional sentinel object somewhere I could see? -- Neil Cerutti From steve at holdenweb.com Tue Jul 31 22:34:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 31 Jul 2007 22:34:50 -0400 Subject: Finding documentation (WAS: Iteration over strings) In-Reply-To: <46AFEE96.5050007@jayloden.com> References: <496954360707311055i1cd7d1begb6b84d11c668f6fa@mail.gmail.com> <46AF7A49.3040804@jayloden.com> <46AF8046.7090702@gmx.net> <496954360707311307y7d503b8eybd72795c8e699104@mail.gmail.com> <46AF9B2D.8040501@jayloden.com> <46AF9F55.20105@gmx.net> <46AFA1D9.1010707@gmx.net> <46AFCB8C.9060800@jayloden.com> <46AFEE96.5050007@jayloden.com> Message-ID: <46AFF14A.9030005@holdenweb.com> Jay Loden wrote: > Steve Holden wrote: >> In this particular case the documentation is quite explicit about the >> return value and the documentation for the function runs to almost 400 >> words. Do you expect *everything* to be in the source? That isn't >> practical, as documenting everything twice like that makes twice the >> work when the function changes and the documentation has to be rewritten. > > (starting a new thread so that we're not off topic for the original one) > Well, you *think* you have started a new thread, but in fact you have just changed the title of the existing one :-) > Hmmm. Jerry Hill pointed out also that this information is documented clearly in the online docs (as opposed to docstrings I was looking at with pydoc). I guess I'm just confused about the purpose of pydoc and module documentation. I was under the impression it was intended to serve as the API reference, so when people say "consult the documentation" I usually check pydoc first before hitting the web browser. I was under the impression earlier that docs.python.org was mostly generated from the docstrings similar to how javadocs are converted to html. > > That being said, it does make sense to me however that you should be able to use pydoc to tell you simple things like the return value of a function, the required parameters, etc. I'd be interested to hear from some more experienced programmers what your typical usage would be when reference documentation for a given module. > > Are the HTML docs (e.g. what's on http://docs.python.org/) the canonical source? Is that where I should generally be looking? Are there other documentation resources you all have found useful as well? I'm curious to see if there are useful resources I'm just missing due to lack of knowledge or experience. > When people say "read the documentation" they generally mean the docs as distributed with each release, and docs.python.org is the easiest way to find the docs for the current release. There are several groups whose plans for documentation world dominance would somehow merge the documentation and the source. Personally I think the documentation in the source should be just enough to remind you how to use something you have already used before, so not understanding them is a good clue you need to look at docs.python.org. 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 no at spam.com Fri Jul 27 12:37:55 2007 From: no at spam.com (Farshid Lashkari) Date: Fri, 27 Jul 2007 09:37:55 -0700 Subject: Another C API Question In-Reply-To: <1185545488.751250.200270@z24g2000prh.googlegroups.com> References: <1185498383.333248.225360@19g2000hsx.googlegroups.com> <1185545488.751250.200270@z24g2000prh.googlegroups.com> Message-ID: beginner wrote: > This works with PyFloat only. It does not work with integers. Did you try it out? I have used it on ints, bools, and objects that implement the __float__ method. It does not work on strings though. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jul 2 15:58:30 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 02 Jul 2007 21:58:30 +0200 Subject: subprocess -- broken pipe error References: <1183396350.429008.185200@n2g2000hse.googlegroups.com> <1183397577.959518.264230@g4g2000hsf.googlegroups.com> <1183400345.202323.133750@k29g2000hsd.googlegroups.com> Message-ID: <5et3n6F399q8uU1@mid.individual.net> 7stud wrote: > Thanks for the response. So are you saying that the only way you > can get data out of a pipe is when the subprocess has terminated? No, not only because Pipes aren't related to processes in any special way. He said that you can't write to a pipe whose reader has already terminated. Regards, Bj?rn -- BOFH excuse #36: dynamic software linking table corrupted From the.mindstorm.mailinglist at gmail.com Thu Jul 5 18:18:31 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Thu, 05 Jul 2007 15:18:31 -0700 Subject: MethodType/FunctionType and decorators In-Reply-To: <1183644112.049339.159460@c77g2000hse.googlegroups.com> References: <1183589529.198694.109440@m36g2000hse.googlegroups.com> <1183591053.434640.119550@o61g2000hsh.googlegroups.com> <1i0qoq9.u1fu2g63fkmxN%aleax@mac.com> <1183623479.913816.301230@g4g2000hsf.googlegroups.com> <1183626989.983470.94950@o61g2000hsh.googlegroups.com> <1183641471.753457.269030@m36g2000hse.googlegroups.com> <1183644112.049339.159460@c77g2000hse.googlegroups.com> Message-ID: <1183673911.790367.73090@n2g2000hse.googlegroups.com> On Jul 5, 5:01 pm, Michele Simionato wrote: > On Jul 5, 3:17 pm, Alex Popescu > wrote: > > > The true story is that > > while working on Groovy (I am a committer on this dynlang meant to run > > on the Java VM:http://groovy.codehaus.org) and reading some Python > > materials, my interest grew exponentially. And now I have decided to > > see how other succesfull java project I have co-created (TestNG:http://testng.org) would look like in Python (this giving me the > > opportunity to explore Python in more depth). > > If you are interested in testing, you should give a look at 1) > doctest; 2) py.test > (Python unittest framework should be old hat to you and not worth > looking at). > > Michele Simionato Thanks for the pointers Michele. I have heard about those and their are on my todo list. However, the features of TestNG are very advanced and I don't think they are available in other frameworks (TestNG is not a unit testing framework, but a full flavored testing framework that fits perfectly functional testing, integration testing, and with some of the very advanced features even performance and load testing). But I will make sure I am taking a look at the ones you pointed me to (and I think I have a longer list available around). bests, ./alex -- .w( the_mindstorm )p. From deets at nospam.web.de Tue Jul 10 03:36:56 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 10 Jul 2007 09:36:56 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xir8us3hm.fsf@ruckus.brouhaha.com> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <5engo8F38jdgaU1@mid.uni-berlin.de> <4686b9b0$0$27140$426a74cc@news.free.fr> <5epe7aF39ugprU1@mid.uni-berlin.de> <7xir8us3hm.fsf@ruckus.brouhaha.com> Message-ID: <5fgr8rF3covr2U1@mid.uni-berlin.de> Paul Rubin schrieb: > "Diez B. Roggisch" writes: >>> Which implies that even in ADA, runtime type errors are in fact >>> expected - else there would be no handler for such a case. >> Well, yes, runtime errors occur - in statically typed languages as >> well. That's essentially the halting-problem. > > Well, no, it's quite possible for a language to reject every program > that has any possibility of throwing a runtime type error. The > halting problem implies that no algorithm can tell EXACTLY which > programs throw errors and which do not. So the language cannot accept > all programs that are free of runtime type errors and reject all > programs that definitely have runtime type errors, with no uncertain > cases. But it's fine for a language to reject uncertain cases and > accept only those which it can rigorously demonstrate have no type > errors. Sure. But which class of programs are decidable? There's lot's of research going on with model checking and the like. But AFAIK, the consensus is that the very moment you allow recursive types, the type-checking is either incomplete, or possibly non-deterministic. Which makes then the compiler hang. Diez From vedrandekovic at v-programs.com Sun Jul 22 09:36:59 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Sun, 22 Jul 2007 06:36:59 -0700 Subject: problem with exec In-Reply-To: References: <1185099810.772825.284620@m3g2000hsh.googlegroups.com> Message-ID: <1185111419.177524.131870@d55g2000hsg.googlegroups.com> > I wasn't playing silly games at all, and I did prefix that part ofmy > answer with "I'm afraid I don't understand this question". The OP is > writing a program to "translate" a Python-like language that uses > non-English keywords into Python. Since the application is transforming > its input, it could transform braces into indentation. Of course *Python* > doesn't use braces, but the question was how to write "pseudo-Python" > without using indentation to indicate grouping. > > regards > Steve Hi, This previously is exactly what I need can you help me somehow about this code indentation, on any way you know.Plese help I will really appreciate this!!!!!!!!!!!!!! Regards, Vedran From fred at adventistcare.org Tue Jul 3 12:59:36 2007 From: fred at adventistcare.org (Sells, Fred) Date: Tue, 3 Jul 2007 12:59:36 -0400 Subject: python app to emulate terminal to dialup bulletin board Message-ID: We need to automate the download of data that is now done manually via a terminal session to a dialup bulletin board. The user uses this to upload and download files. Hard to believe in this day and age, but true. I've tried google, but the terms are just too common; all I get is clutter. So I need a python module (or snippets) that: 1. setup and execute a standard dialup with appropriate parity, stop-bits, etc 2. can emulate hyperterm including sending and receiving files I know anything worth doing has already been done in python by someone, but I have not had much luck finding it. Perhaps I just don't know the best words to put into google. can I get a few helpful links for y'all. thanks. --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From Eric_Dexter at msn.com Mon Jul 9 18:53:15 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Mon, 09 Jul 2007 15:53:15 -0700 Subject: Choosing Tkinter over wxPython... In-Reply-To: <3e384$4692a3c4$4275d90a$11745@FUSE.NET> References: <3e384$4692a3c4$4275d90a$11745@FUSE.NET> Message-ID: <1184021595.284867.20860@22g2000hsm.googlegroups.com> On Jul 9, 4:08 pm, Kevin Walzer wrote: > I've spent some time playing with both, and while wxPython is nice, > Tkinter just seems to fit my head better, and with appropriate selection > of widgets and interface design, seems to yield up perfectly usable GUI's. > > Can anyone else who finds Tkinter better for them than wxPython (or the > other toolkits) explain why it works for them? > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com You have very good documentation and examples of tkinter. .. I use both though I don't choose.. From carsten at uniqsys.com Thu Jul 19 11:27:34 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 19 Jul 2007 11:27:34 -0400 Subject: A way to re-organize a list In-Reply-To: <1184857535.033057.49150@m3g2000hsh.googlegroups.com> References: <1184857535.033057.49150@m3g2000hsh.googlegroups.com> Message-ID: <1184858854.3252.4.camel@localhost.localdomain> On Thu, 2007-07-19 at 15:05 +0000, 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)] > ] > ] That's easy with the magic of itertools.groupby and operator.itemgetter: >>> from itertools import groupby >>> from operator import itemgetter >>> from pprint import pprint >>> first = itemgetter(0) >>> second = itemgetter(1) >>> l = [ ("A", "a", 1), ("A", "a", 2), ("A", "a", 3), ("A", "b", 1), ("A", ... "b", 2), ("B", "a", 1), ("B", "b", 1)] >>> result = [[list(g2) for _,g2 in groupby(g1,second)] for _,g1 in groupby(l,first)] >>> pprint(result) [[[('A', 'a', 1), ('A', 'a', 2), ('A', 'a', 3)], [('A', 'b', 1), ('A', 'b', 2)]], [[('B', 'a', 1)], [('B', 'b', 1)]]] HTH, -- Carsten Haese http://informixdb.sourceforge.net From nicola.musatti at gmail.com Thu Jul 5 10:08:57 2007 From: nicola.musatti at gmail.com (Nicola Musatti) Date: Thu, 05 Jul 2007 14:08:57 -0000 Subject: The best platform and editor for Python In-Reply-To: References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> Message-ID: <1183644537.859604.27790@w5g2000hsg.googlegroups.com> On Jul 5, 1:23 pm, Gregor Horvath wrote: [...] > That's a property of open source projects. > Features nobody really needs are not implemented. No, no, you got it all wrong. It's in *commercial* projects that features nobody really needs are not implemented. Profit is fundamental in convincing you that you really need the features. On the other hand open source projects tend to lack features nobody enjoys implementing. Cheers, Nicola Musatti P.S. Maybe I should add a ;-) From simon.hibbs at gmail.com Fri Jul 13 14:00:21 2007 From: simon.hibbs at gmail.com (Simon Hibbs) Date: Fri, 13 Jul 2007 11:00:21 -0700 Subject: Can a low-level programmer learn OOP? In-Reply-To: <1184349549.484402.214860@o61g2000hsh.googlegroups.com> References: <1184349549.484402.214860@o61g2000hsh.googlegroups.com> Message-ID: <1184349621.481612.210100@d55g2000hsg.googlegroups.com> Sorry, here's the tutorial link: http://hetland.org/writing/instant-python.html Simon Hibbs From gh at ghaering.de Wed Jul 18 07:36:24 2007 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 18 Jul 2007 13:36:24 +0200 Subject: Compatibility of python2.5 with pytohn2.3 In-Reply-To: References: Message-ID: VISHAL KANAUJIA wrote: > Hi all, > I am new member of this post. I have a C application which uses > Python(version 2.3) extensively with SWIG wrappers. I want to upgrade > the Python to latest version2.5. > > Is there any compatibility issue between two versions? Does latest > Python2.5 provide backward compatibility to previous Python (Version > 2.3 in my case) constructs. Short answer: yes. I've never had any issues here (compiling Python extension code in newer Python versions). The other way around that's of course not the case. I have to test my extension code against Python 2.4 and Python 2.3 regularly, because otherwise issues arise where I wouldn't have expected them, like even simple macros like PyDict_CheckExact not being present in older Python versions. -- Gerhard From stesch at no-spoon.de Fri Jul 27 04:58:11 2007 From: stesch at no-spoon.de (Stefan Scholl) Date: Fri, 27 Jul 2007 10:58:11 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> <46A9931F.3020100@web.de> Message-ID: <1T49f0npIf2oNv8%stesch@parsec.no-spoon.de> Stefan Behnel wrote: > Stefan Scholl wrote: >> Stefan Behnel wrote: >>> The XML is *not* well-formed if you pass Python unicode instead of a byte >>> encoded string. Read the XML spec. >> >> Pointers, please. > > There you have it: > > http://www.w3.org/TR/xml/#charencoding > > """ > In the absence of information provided by an external transport protocol (e.g. > HTTP or MIME), it is a *fatal error* for an entity including an encoding > Byte Order Mark nor an encoding declaration to use an encoding other than UTF-8. > """ > specific). You might argue that there is some kind of "external transportation > protocol" as it is a Python Unicode string (I used that excuse when I Not the string itself. The method that ist called: parseString() From andre.roberge at gmail.com Fri Jul 27 16:46:20 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Fri, 27 Jul 2007 20:46:20 -0000 Subject: Is access to locals() of "parent" namespace possible? Message-ID: <1185569180.544092.283620@57g2000hsv.googlegroups.com> I want to give a user the possibility of "restarting" an interactive session, by removing all the objects defined by her since the beginning. The way I make this possible is by having a "function" that can be called during the interactive session using locals() as an argument, as follows: restart(locals()) It works. However, I would like to make this "friendlier", i.e. requiring the user to simply type restart() and have the code extract out the value of locals() of the "parent" namespace. I thought it might be possible using sys._getframe, but I have not been able to figure out why. Any help would be appreciated. Andr? ================== The code below defines the class I used. The interpreter is started via #-- exec user_code in symbols #-- where user_code is #-- interp = SingleConsole() interp.interact() #-- # InteractiveConsole is very similar to the class of the same name # in module code.py of the standard library class SingleConsole(InteractiveConsole): '''SingleConsole are isolated one from another''' def __init__(self, locals={}, filename="Isolated console"): self.locals = locals self.locals['restart'] = self.restart InteractiveConsole.__init__(self, self.locals, filename=filename) def restart(self, loc): """Call this function as follows: restart(locals()) Used to restart an interpreter session, removing all variables and functions introduced by the user, but leaving Crunchy specific ones in.""" to_delete = set() # We can't iterate over a dict while changing its size; we do it # in two steps; first identify the objects to be deleted while # iterating over the dict; then iterate over a set while removing # the objects in the dict. for x in loc: if x not in ['__builtins__', 'crunchy', 'restart']: to_delete.add(x) for x in to_delete: del loc[x] return From vasudevram at gmail.com Fri Jul 20 15:38:34 2007 From: vasudevram at gmail.com (vasudevram) Date: Fri, 20 Jul 2007 19:38:34 -0000 Subject: Python MAPI In-Reply-To: <1184959701.447824.70890@q75g2000hsh.googlegroups.com> References: <1184954229.222401.213380@k79g2000hse.googlegroups.com> <1184957337.367674.104760@i13g2000prf.googlegroups.com> <1184959701.447824.70890@q75g2000hsh.googlegroups.com> Message-ID: <1184960314.426690.238270@z28g2000prd.googlegroups.com> On Jul 21, 12:28 am, kyoso... at gmail.com wrote: > On Jul 20, 1:48 pm, vasudevram wrote: > > > > > > > On Jul 20, 10:57 pm, kyoso... at gmail.com wrote: > > > > Hi, > > > > I've been googling all over and can't find any good answers about this > > > problem. I would like to create some kind of MAPI interface with > > > Python such that when I open Microsoft Word (or another Office > > > program) and click File, Send To, Mail Recipient it opens a program I > > > wrote in Python and uses it to send the email rather than Outlook. > > > > The closest I've come is finding the registry key HKLM\Software\Clients > > > \Mail which seems to control the default email client. I did figure > > > out how to redirect mailto directives on websites to my program > > > successfully, but this is a whole 'nother ballgame. > > > > Any suggestions are welcome. I am considering writing some VBA hooks > > > in Office Apps in question, but would prefer to avoid that. > > > > Thanks! > > > > Mike > > > > P.S. Currently using Python 2.4, wxPython 2.8.3 (for GUI) on Windows > > > XP Pro. > > > Hi, > > > 1: I don't know much about Windows APIs, but am currently reading the > > "Windows Internals" book. Got this idea from it: > > > Go tohttp://www.microsoft.com/technet/sysinternals/default.mspx > > and check out the SysInternals utilities there. The book says that you > > can use some of them to "spy" on what an app is doing - what registry > > keys it is reading/writing, lots of other OS-level calls it makes as > > it runs. Digging around and using some of these utilities to check out > > what an Office app does when you use it to send mail, might help you > > figure out a way to do what you want. > > > 2. Try looking for registry entries specific to Office Apps, and look > > under those subtrees for likely email-related entries to modify (if > > you haven't tried that already). I guess you already know that > > fiddling with the registry can be risky and can crash your system, so > > take backups, etc. > > > Using COM via Python may also help - again, some digging required. You > > probably already have the PyWin32 Python extensions for Windows COM > > (earlier called win32all - seehttp://wiki.python.org/moin/Win32All) - > > if not, its available here: > > >http://www.python.org/download/releases/2.4.4/ > > (scroll down the page for the link) > > > Vasudev Ramwww.dancingbison.com > > jugad.livejournal.com > > sourceforge.net/projects/xtopdf > > Thanks for the ideas...I am already monitoring the registry to see > what happens when I switch between two email clients. In this case, I > am switching between Outlook 2003 and Thunderbird 2. The pertinent > registry files are as follows: > > # changes which email client to use > [HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail] > > # obviously changes the .eml file association > [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.eml] > > # haven't the fogiest idea what this does, if anything > [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\CLSID\{29F458BE-8866-11D5- > A3DD-00B0D0F3BAA7}] > > # change mailto functionality > [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\mailto\DefaultIcon] > @="C:\\Program Files\\Mozilla Thunderbird\\thunderbird.exe,0" > [HKEY_LOCAL_MACHINE\SOFTWARE\Classes\mailto\shell\open\command] > @="\"C:\\Program Files\\Mozilla Thunderbird\\thunderbird.exe\" -osint - > compose \"%1\"" > > I assume you're referring to "Process Monitor", which is a really cool > tool. Maybe it'll help, but I usually can't get it to filter out > enough of the noise to make the output useful. I'll give it a go > nonethless. > > I am running all my tests in a VM, so I really don't care if the > registry gets hosed at this point. > > Thanks again, > > Mike- Hide quoted text - > > - Show quoted text - You're welcome :) If Process Monitor has an option to save its output as text files / CSV files (some of the other SysInternals tools do), you might want to try using (a Windows version) of grep or awk to filter out the noise .. Vasudev From rcdailey at gmail.com Tue Jul 24 13:11:27 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 24 Jul 2007 17:11:27 -0000 Subject: datetime.time() class - How to pass it a time string? Message-ID: <1185297087.998644.53940@r34g2000hsd.googlegroups.com> Hi, I have a string in the following format: "00:00:25.886411" I would like to pass this string into the datetime.time() class and have it parse the string and use the values. However, the __init__() method only takes integers (which means I'd be forced to parse the string myself). Does anyone know of a way I can make it use the string? Thanks. From cito at online.de Thu Jul 5 17:21:03 2007 From: cito at online.de (Christoph Zwerschke) Date: Thu, 05 Jul 2007 23:21:03 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: <1183668029.470160.218230@q69g2000hsb.googlegroups.com> References: <1183668029.470160.218230@q69g2000hsb.googlegroups.com> Message-ID: Kay Schluehr wrote: > If you are sure that the exception isn't caught on another level just > use the following showtraceback() function, manipulate it's output > slightly and terminate your program with sys.exit() That's what I want to avoid. In my case the error is displayed and evaluated in a completly different piece of software. -- Chris From http Tue Jul 31 13:58:07 2007 From: http (Paul Rubin) Date: 31 Jul 2007 10:58:07 -0700 Subject: Encryption recommendation References: Message-ID: <7xbqds1mmo.fsf@ruckus.brouhaha.com> "JS" writes: > Can someone help me find the proper way to do AES encryption/decryption > using Python? http://google.com/search?q=AES+Python From claird at lairds.us Mon Jul 23 13:27:30 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 23 Jul 2007 17:27:30 +0000 Subject: Where do they tech Python officialy ? References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> Message-ID: <215fn4-60g.ln1@lairds.us> In article <1185209574.045112.163780 at g4g2000hsf.googlegroups.com>, NicolasG wrote: >Hi, > >I want to be a professional python programmer, unfortunately I'm >working on technical support and don't have the time/patience to start >making projects my self. I tried to apply to some Python positions but >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.. > >I'm planning to save some money and attend a course in any of the >universities that teach hard core Python. > >Does some one have any suggestions on which University to attend ? >Alternatives solutions are welcome.. . . . Autodidacticism is an alternative; feel free to regard as a member of that class. If you, for example, were to teach yourself Python, then volunteer with prominent extensions or even the core (there's plenty to do in regard to documentation and testing), you'd soon have accumulated quite a bit of experience that enlightened employers recognize is as professional as any other. I leave to others the chore of summarizing all the universities with Python offerings. From cam.ac.uk at mh391.invalid Wed Jul 4 22:38:45 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 05 Jul 2007 03:38:45 +0100 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182448413.966430.299590@m36g2000hse.googlegroups.com> <7xhcp0fom4.fsf@ruckus.brouhaha.com> <87tzt0tgol.fsf@benfinney.id.au> <1182533987.715191.159850@m36g2000hse.googlegroups.com> <468567b3$0$26422$426a74cc@news.free.fr> Message-ID: Eduardo "EdCrypt" O. Padoan wrote: > On 6/30/07, Bruno Desthuilliers > wrote: >> Eduardo "EdCrypt" O. Padoan a ?crit : >> > Remember that pure CPython has no different "compile time" and >> > runtiime. >> >> Oh yes ? So what's the compiler doing, and what are those .pyc files ? >> (hint: read the doc) > > Sorry, I surely know that Python has a compile time, I wanted to say > somthing like "compile time checks except from syntax". Well, if you try to reassign __debug__ or None you get a SyntaxError, but I don't think it is truly checking syntax. -- Michael Hoffman From lucaberto at libero.it Mon Jul 9 02:08:58 2007 From: lucaberto at libero.it (luca72) Date: Mon, 09 Jul 2007 06:08:58 -0000 Subject: unify els database In-Reply-To: <1183534314.073800.180560@q69g2000hsb.googlegroups.com> References: <1183383335.842730.41600@q69g2000hsb.googlegroups.com> <1183446552.345276.44930@k29g2000hsd.googlegroups.com> <1183465552.876190.66910@o61g2000hsh.googlegroups.com> <1183534314.073800.180560@q69g2000hsb.googlegroups.com> Message-ID: <1183961338.076364.94730@o61g2000hsh.googlegroups.com> Many thanks I will try with Jython Regards Luca From david.l.jones at gmail.com Wed Jul 11 13:04:06 2007 From: david.l.jones at gmail.com (David Jones) Date: Wed, 11 Jul 2007 17:04:06 -0000 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> Message-ID: <1184173446.779276.250530@k79g2000hse.googlegroups.com> On Jul 10, 12:47 am, "Jim Langston" wrote: > "Paul Rubin" wrote in message > > news:7xbqek7ty1.fsf at ruckus.brouhaha.com... > > > "Jim Langston" writes: > >> In Python 2.5 on intel, the statement > >> 2**2**2**2**2 > >> evaluates to > >> >>> 2**2**2**2**2 > > > I get the same number from hugs--why do you think it might be wrong? > > 2**2 = 4 > 4**2 = 16 > 16**2 = 256 > 256**2 = 65536 > 65536**2 = 4294967296 > > In fact, if I put (2**2)**2**2**2 > it comes up with the correct answer, 4294967296 Actually, the "correct" answer (even by your own demonstration) is 65536. Assuming left-associativity, i.e., (((2**2)**2)**2)**2, python returns 65536. The answer of 4294967296 is actually ((((2**2)**2)**2)**2)**2, which is one extra raise-to-the-power-of-two instruction. The statement (2**2)**2**2**2 is the same as 4**16, following right- associativity rules, which just happens to be the same as ((((2**2)**2)**2)**2)**2. David From bdesth.quelquechose at free.quelquepart.fr Thu Jul 5 00:51:25 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 05 Jul 2007 06:51:25 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7x4pkkun56.fsf@ruckus.brouhaha.com> References: <5dveb4F360un0U1@mid.individual.net> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> Message-ID: <468c0827$0$22906$426a74cc@news.free.fr> Paul Rubin a ?crit : > Bruno Desthuilliers writes: > >>Because static type checks impose a lot of arbitrary restrictions, >>boilerplate code etc, which tends to make code more complicated than >>it needs to be, which is a good way of introducing bugs that wouldn't >>have existed without static type checks. > > > Why do you say that? By metrics and anecdotal evidence, Haskell code > appears to be at least as compact as Python code. Haskell - as other languages using type-inference like OCaml - are in a different category. Yes, I know, don't say it, they are statically typed - but it's mostly structural typing, not declarative typing. Which makes them much more usable IMHO. It's too bad they are not more widely adopted. >>Depending on the application domain and some technical and >>non-technical constraints and requirements, it (often) happens that >>it's better to have the application deployed now with an occasional >>error message than to have it next year... > > > I suppose that includes the thing I'm currently working on. > > For > some other stuff I've done, such errors would have caused huge hassles, > lost customer money, etc. Still, static typechecking is not a garantee against runtime errors. Nor against logical errors. > >>And FWIW, when it comes to "weird piece of input data", statically >>typed languages are not specially better than dynamic ones... > > I know that ML gives compiler warning messages if you have a pattern > match (sort of a variant of a case statement, not a regexp match) I know what pattern matching is, I did play a bit with OCaml and Haskell. > which is non-exhaustive. And Haskell's Maybe monad is part of an > idiom that handles failing computations (like regexp matches) much > more gracefully than Python can. Both of those would help this > situation. I'd have to see a concrete use case. And I'd need much more real-world experience with some ML variant, but this is not something I can expect to happen in a near future - it's difficult enough to convince PHBs that Python is fine. From franciscodg at gmail.com Thu Jul 19 13:29:12 2007 From: franciscodg at gmail.com (franciscodg) Date: Thu, 19 Jul 2007 17:29:12 -0000 Subject: help with create menu in wxpython In-Reply-To: <6016c$469e529a$d443bb3a$21714@news.speedlinq.nl> References: <1184780361.171375.133400@j4g2000prf.googlegroups.com> <6016c$469e529a$d443bb3a$21714@news.speedlinq.nl> Message-ID: <1184866152.953693.324650@q75g2000hsh.googlegroups.com> On 18 jul, 13:55, Stef Mientki wrote: > better ask in the wx discussion group: > wxPython-us... at lists.wxwidgets.org > > cheers, > Stef Mientki thks From jstroud at mbi.ucla.edu Mon Jul 30 21:50:12 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 30 Jul 2007 18:50:12 -0700 Subject: What is the "functional" way of doing this? In-Reply-To: References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> <1185838434.596591.132640@d30g2000prg.googlegroups.com> <7x3az5wjfa.fsf@ruckus.brouhaha.com> <1185839713.412656.242950@i13g2000prf.googlegroups.com> Message-ID: Ricardo Ar?oz wrote: >>On Jul 30, 4:39 pm, Paul Rubin wrote: >> >>>"attn.steven.... at gmail.com" writes: >>> >>>>Recursion is common in functional programming: >>>>def f(n, l=None): >>>> if l == None: >>>> l = [] >>>> if n > 0: >>>> return f(n/26, l + [n%26]) >>>> else: >>>> return l >>>>print f(1000) >>> >>>Right, this is functional style, but quite painful in Python (no tail >>>recursion, and look at all that list copying). >> > > It might actually be : > > def f(n): > if n > 0: > return ([n%26] + f(n/26)) > else: > return [] > > Wouldn't that be ok? > You are still copying lists. This wouldn't: def f(n): if n>0: yield n%26 for i in f(n/26): yield i James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From albert_k_arhin at yahoo.com Wed Jul 11 14:40:02 2007 From: albert_k_arhin at yahoo.com (albert_k_arhin) Date: Wed, 11 Jul 2007 18:40:02 -0000 Subject: Encode Bytes Message-ID: Hi All, I am new to python and I am using a strip down version of python that does not support struc,pack,etc. I have a binary protocol that is define as follows: PART OffSet Lenght ============================ ID 0 2 VER 2 1 CMD 3 2 PGKID 5 2 DATE 7 3 TIME 10 3 CRC 13 2 DLEN 15 2 How do I encode these the offset is in Bytes. Thank you very much. From bdesth.quelquechose at free.quelquepart.fr Sun Jul 22 00:54:32 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 22 Jul 2007 06:54:32 +0200 Subject: Reading files, splitting on a delimiter and newlines. In-Reply-To: <1185378363.166434.172190@r34g2000hsd.googlegroups.com> References: <1185378363.166434.172190@r34g2000hsd.googlegroups.com> Message-ID: <46a7a5ab$0$29039$426a74cc@news.free.fr> chrispwd at gmail.com a ?crit : > Hello, > > I have a situation where I have a file that contains text similar to: > > myValue1 = contents of value1 > myValue2 = contents of value2 but > with a new line here > myValue3 = contents of value3 > > My first approach was to open the file, use readlines to split the > lines on the "=" delimiter into a key/value pair (to be stored in a > dict). > > After processing a couple files I noticed its possible that a newline > can be present in the value as shown in myValue2. > > In this case its not an option to say remove the newlines if its a > "multi line" value as the value data needs to stay intact. > > I'm a bit confused as how to go about getting this to work. > > Any suggestions on an approach would be greatly appreciated! > data = {} key = None for line in open('yourfile.txt'): line = line.strip() if not line: # skip empty lines continue if '=' in line: key, value = map(str.strip, line.split('=', 1)) data[key] = value elif key is None: # first line without a '=' raise ValueError("invalid format") else: # multiline data[key] += "\n" + line print data => {'myValue3': 'contents of value3', 'myValue2': 'contents of value2 but\nwith a new line here', 'myValue1': 'contents of value1'} HTH From ladaan at iptel.org Tue Jul 24 07:25:18 2007 From: ladaan at iptel.org (Ladislav Andel) Date: Tue, 24 Jul 2007 13:25:18 +0200 Subject: display image through cgi python html In-Reply-To: <5gm1ggF3gs3gfU3@mid.uni-berlin.de> References: <5gm1ggF3gs3gfU3@mid.uni-berlin.de> Message-ID: <46A5E19E.9080403@iptel.org> Thanks for quick reply. Yes, that's the hint I needed. Lada Marc 'BlackJack' Rintsch wrote: > On Tue, 24 Jul 2007 11:58:47 +0200, Ladislav Andel wrote: > > >> Here is what I have in image.cgi but it is incorrect and i'm not able to >> find it on the web. >> >> #!/usr/bin/python >> print "Content-Type: image/png\n" >> print 'image.png' >> > > You have to print the image, not the name. Read the binary file and print > it. > > Ciao, > Marc 'BlackJack' Rintsch > From westymatt at gmail.com Thu Jul 26 08:54:46 2007 From: westymatt at gmail.com (matt westerburg) Date: Thu, 26 Jul 2007 08:54:46 -0400 Subject: Why PHP is so much more popular for web-development Message-ID: <4b490f2f0707260554r73c14676v39a75a1475d01786@mail.gmail.com> Why are you praising PHP on a python mailing list are you trying to start a flame war? (Not evaluating PHP as a language), our company just switched over to using Django and my has it saved us time, and we can organize our code its really beautiful. PHP is full of new to programming users and thusly has no in my opinion comparable framework. Because its obvious that websites will if they haven't already be forced to use a framework for productivity. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Thu Jul 12 23:08:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jul 2007 00:08:06 -0300 Subject: Circular import problem References: <1184294176.550267.119980@n60g2000hse.googlegroups.com> Message-ID: En Thu, 12 Jul 2007 23:36:16 -0300, bvdp escribi?: > I'm going quite nutty here with an import problem. I've got a fairly > complicated program (about 12,000 lines in 34 modules). I just made > some "improvements" and get the following error: > > bob$ mma > Traceback (most recent call last): > File "/usr/local/bin/mma", line 55, in > import MMA.main > File "/usr/local/share/mma/MMA/main.py", line 33, in > import MMA.docs > File "/usr/local/share/mma/MMA/docs.py", line 34, in > import MMA.grooves > File "/usr/local/share/mma/MMA/grooves.py", line 41, in > import MMA.auto > File "/usr/local/share/mma/MMA/auto.py", line 35, in > import MMA.parse > File "/usr/local/share/mma/MMA/parse.py", line 2052, in > 'AUTHOR': MMA.docs.docAuthor, > AttributeError: 'module' object has no attribute 'docs' > > I can fix this by deleting a line in docs.py. Just take out the > "import MMA.grooves" and all works. What I really don't get is that in > the middle of this module which is now NOT loading "grooves.py" I have > a command to access a function in that module and it works. > > Yes, grooves.py has an import docs.py. And there are lots of other > such imports in the program. > > So, I have to assume that the error is being generated by some other > modules loading in the grooves.py stuff ... but really have no idea. > > Is there anything I can do to trace though this and get it working > properly? See http://effbot.org/zone/import-confusion.htm Try to move the circular references later in the code (maybe inside a function, when it is required), or much better, refactor it so there is no circularity. -- Gabriel Genellina From kyosohma at gmail.com Sat Jul 14 14:01:27 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sat, 14 Jul 2007 18:01:27 -0000 Subject: getting text inside the HTML tag In-Reply-To: References: Message-ID: <1184436087.239958.228710@r34g2000hsd.googlegroups.com> On Jul 14, 12:47 pm, Nikola Skoric wrote: > I'm using sgmllib.SGMLParser to parse HTML. I have successfuly parsed start > tags by implementing start_something method. But, now I have to fetch the > string inside the start tag and end tag too. I have been reading through > SGMLParser documentation, but just can't figure that out... can somebody > help? :-) > > -- > "Now the storm has passed over me > I'm left to drift on a dead calm sea > And watch her forever through the cracks in the beams > Nailed across the doorways of the bedrooms of my dreams" Oi! Try Beautiful Soup instead. That seems to be the defacto HTML parser for Python: http://www.crummy.com/software/BeautifulSoup/ You might find the minidom or lxml modules to your liking as well. Mike From researchbase at gmail.com Sun Jul 15 03:02:16 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Sun, 15 Jul 2007 12:32:16 +0530 Subject: how good does PyGTK work on windows? Message-ID: hello, I will be writing some code in PyGTK to run on linux. but I want to know if there are any installers or distutils available for PyGTK on windows? I have heard that installing gimp or even pygtk is next to impossible and is very tedious if at all one gets success. can any one share their experiences with installing and running pygtk on windos? any links for downloading proper packages will be highly appreciated. regards, Krishnakant. From steven at REMOVE.THIS.cybersource.com.au Mon Jul 16 22:52:33 2007 From: steven at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: 17 Jul 2007 02:52:33 GMT Subject: Implementaion of random.shuffle References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> <1184597148.692325.36590@x35g2000prf.googlegroups.com> Message-ID: On Mon, 16 Jul 2007 14:45:48 +0000, shabda raaj wrote: > On Jul 16, 5:53 pm, Steve Holden wrote: >> shabda raaj wrote: >> > I was going through the docs for module-random >> > And I came through >> > this, >> >> > * shuffle*( x[, random]) >> >> > Shuffle the sequence x in place. The optional argument random is >> > a 0-argument function returning a random float in [0.0, 1.0); by >> > default, this is the function random(). >> >> > Note that for even rather small |len(x)|, the total number of >> > permutations of x is larger than the period of most random number >> > generators; this implies that most permutations of a long >> > sequence can never be generated. [snip] > Oh, I wasn't aware that I could see the source of all python modules. I > guess, then the implementation is correct(its just the knuth shuffle, > moving downward), its just the doc which is in error. Might be we should > log a doc bug for this? No, it is not a doc error, you are confused. Suppose you have a random number generator that has the tiny period of 120. (Obviously that's a really lousy RNG, but it will do for an example.) That means it can only produce 120 different results (the current number, plus the state the generator it is in) before repeating. Note that the period is not the same as the spread of values returned, the two are independent, although naturally the period must be at least equal to the number of unique values returned. If you have a list of just six items, there are 6! = 720 possible permutations of the list, so AT BEST the random number generator can produce 120/720 or 17% of the permutations. That's an example of the pigeonhole principle, one of the most simple yet powerful mathematical principles around. If you've got more items than pigeonholes to put them in, either some will double up or some will miss out. In the case of CPython, the current implementation uses the Mersenne Twister, which has a huge period of 2**19937. However, 2081! is larger than that number, which means that at best a list of 2081 items or longer can't be perfectly shuffled (not every permutation can be selected by the algorithm). -- Steven. From duncan.booth at invalid.invalid Mon Jul 16 08:06:26 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Jul 2007 12:06:26 GMT Subject: questions about functions inside a function References: Message-ID: "fdu.xiaojf at gmail.com" wrote: > What I want is, the value of i should be bounded to the anonymous > function. And the output should like this: > > for f in a: > print f() > 0 > 1 > 4 > 9 > > How to achieve this? Use default arguments when defining your function: default arguments are evaluated when the function is defined, bound arguments get the current value of the variable at the point when it is referenced during the call. Also, since you give your function a name anyway ('b') you might as well use a named function as being clearer than using lambda: >>> a = [] >>> for i in range(4): def b(i=i): return i**2 a.append(b) >>> for f in a: f() 0 1 4 9 >>> From carsten at uniqsys.com Mon Jul 30 20:07:12 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 30 Jul 2007 20:07:12 -0400 Subject: Help text embedding in C code? In-Reply-To: References: Message-ID: <1185840432.4042.8.camel@localhost.localdomain> On Mon, 2007-07-30 at 16:24 -0700, James Stroud wrote: > Hello All, > > I have a python module I wrote in C some time ago and I have since > forgotten how to use my functions and so I wanted to add some > doc-strings such that "help(function_name)" would give some help in the > interactive interpreter. [...] Is it possible to > embed this information in the C source directly [...] ? Yes. A doc-string can be provided in the fourth slot of the PyMethodDef entry. See e.g. /path/to/python/source/Modules/cPickle.c for a randomly chosen module that has doc strings embedded in the C source. HTH, -- Carsten Haese http://informixdb.sourceforge.net From duncan.booth at invalid.invalid Sun Jul 1 05:36:37 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jul 2007 09:36:37 GMT Subject: os.path.isfile() References: <1183281482.668177.142470@c77g2000hse.googlegroups.com> Message-ID: 7stud wrote: > Here is a program to print out the files in a directory: > > ----------- > import os > > myfiles = os.listdir("../") > print myfiles > > for afile in myfiles: > print afile > if os.path.isfile(afile): > print afile, "___file" > if os.path.isdir(afile): > print afile, "___dir" > print > ------------ > > Here is what's in the directory: > > ---------- > $ ls -al ../ > > total 2576 > drwxr-xr-x 8 nnn nnn 272 Jul 1 03:03 . > drwxr-xr-x 25 nnn nnn 850 Jul 1 01:34 .. > -rw-r--r-- 1 nnn nnn 6148 Jul 1 03:02 .DS_Store > -rw-r--r-- 1 nnn nnn 1300000 Jun 27 14:02 aaa.txt > drwxr-xr-x 55 nnn nnn 1870 Jul 1 03:09 dir1 > -rwxrwxrwx 1 nnn nnn 263 Jun 27 22:40 mytest.py > -rw-r--r-- 1 nnn nnn 0 Mar 4 16:15 scratch.txt > -rw-r--r-- 1 nnn nnn 275 Apr 11 03:40 xmlFile.xml > ------------ Yes, but what does 'ls -al .' show you? You didn't put any kind of path in your calls to isfile/isdir, so you are checking for the existence of files/directories called '.DS_Store' etc. in the *current* directory, not the one above. From your output I'd guess you have .DS_Store and aaa.txt files but the other names are not duplicated. From bdesth.quelquechose at free.quelquepart.fr Thu Jul 5 02:03:13 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 05 Jul 2007 08:03:13 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7x3b03lusa.fsf@ruckus.brouhaha.com> References: <5dveb4F360un0U1@mid.individual.net> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <468c0827$0$22906$426a74cc@news.free.fr> <7x3b03lusa.fsf@ruckus.brouhaha.com> Message-ID: <468c18fc$0$26377$426a74cc@news.free.fr> Paul Rubin a ?crit : > Bruno Desthuilliers writes: > >>Haskell - as other languages using type-inference like OCaml - are in >>a different category. Yes, I know, don't say it, they are statically >>typed - but it's mostly structural typing, not declarative >>typing. Which makes them much more usable IMHO. > > > Some users in fact recommend writing an explicit type signature for > every Haskell function, which functions sort of like a unit test. Stop here. explicit type signature == declarative static typing != unit test. > That doesn't bloat the code up noticibly. The conciseness of those > languages comes more from polymorphism and convenient ways of writing > and using higher-order functions, than from type inference. Type inference is certainly helpful for genericity. > >>Still, static typechecking is not a garantee against runtime >>errors. Nor against logical errors. > > > Right, however the reality is it does seem to prevent a lot of > surprises. I have few "surprises" with typing in Python. Very few. Compared to the flexibility and simplicity gained from a dynamism that couldn't work with static typing - even using type inference -, I don't see it a such a wonderful gain. At least in my day to day work. > >>I'd have to see a concrete use case. And I'd need much more real-world >>experience with some ML variant, but this is not something I can >>expect to happen in a near future - it's difficult enough to convince >>PHBs that Python is fine. > > > Monad Reader #7 has an article about some Wall street company using ML: > > http://www.haskell.org/sitewiki/images/0/03/TMR-Issue7.pdf > > see the article by Yaron Minsky. Sorry, I don't live near Wall Street !-) From raims at dot.com Sat Jul 7 16:13:45 2007 From: raims at dot.com (Lawrence Oluyede) Date: Sat, 7 Jul 2007 22:13:45 +0200 Subject: Timing a python program run References: <1183836101.040882.56080@i38g2000prf.googlegroups.com> Message-ID: <1i0wj0t.xgnirj10r51cuN%raims@dot.com> David wrote: > Is there some way to do this in python on a mac os x from the terminal > window? Or whatever? You can use: % time script.py from the command line of the terminal -- 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 retrry at gmail.com Wed Jul 18 04:24:50 2007 From: retrry at gmail.com (ReTrY) Date: Wed, 18 Jul 2007 08:24:50 -0000 Subject: Real-time Update Message-ID: <1184747090.102324.265230@i13g2000prf.googlegroups.com> I'm writing a program with Tkinter GUI, When the program is running it need to be updated every five seconds (data comes from internet). How should I do that ? How to make a function in main loop ? From wildemar at freakmail.de Wed Jul 25 12:21:32 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 25 Jul 2007 18:21:32 +0200 Subject: Closures / Blocks in Python In-Reply-To: <1185374700.256479.228560@b79g2000hse.googlegroups.com> References: <1185289112.771239.200260@n60g2000hse.googlegroups.com> <1185291146.753573.280420@n60g2000hse.googlegroups.com> <7tvjn4-qas.ln1@lairds.us> <1185374700.256479.228560@b79g2000hse.googlegroups.com> Message-ID: <46A7788C.9040208@freakmail.de> Jeff wrote: > # Generic counter > def counter(min=None, max): > if not min: > min = 0 > for i in xrange(min, max): > yield i > i = i + 1 > Just for the record: >>> # Generic counter ... def counter(min=None, max): ... if not min: ... min = 0 ... for i in xrange(min, max): ... yield i ... i = i + 1 ... File "", line 2 SyntaxError: non-default argument follows default argument You'd have to add a little more parameter-checking for this to work like you intend. /W From attn.steven.kuo at gmail.com Wed Jul 11 23:24:51 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Thu, 12 Jul 2007 03:24:51 -0000 Subject: Where does str class represent its data? In-Reply-To: <1184210456.968677.110110@n60g2000hse.googlegroups.com> References: <1184196082.903895.176020@n60g2000hse.googlegroups.com> <1184210456.968677.110110@n60g2000hse.googlegroups.com> Message-ID: <1184210691.988204.170860@q75g2000hsh.googlegroups.com> On Jul 11, 8:20 pm, "attn.steven.... at gmail.com" wrote: > On Jul 11, 4:21 pm, ChrisEdge... at gmail.com wrote: > > > > > I'd like to implement a subclass of string that works like this: > > > >>>m = MyString('mail') > > >>>m == 'fail' > > True > > >>>m == 'mail' > > False > > >>>m in ['fail', hail'] > > > True > > > My best attempt for something like this is: > > > class MyString(str): > > def __init__(self, seq): > > if self == self.clean(seq): pass > > else: self = MyString(self.clean(seq)) > > > def clean(self, seq): > > seq = seq.replace("m", "f") > > > but this doesn't work. Nothing gets changed. > > What about subclassing str and redefining __eq__: > > >>> class MyString(str): > > ... def __eq__(self, other): > ... return not str.__eq__(self, other) > ...>>> m = MyString('mail') > >>> m == 'fail' > True > >>> m == 'mail' > False > >>> m in ['fail', 'hail'] > > True ... Um, nevermind -- I *completely* misunderstood the question... -- Regards, Steven From wbrehaut at mcsnet.ca Fri Jul 13 15:52:53 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Fri, 13 Jul 2007 13:52:53 -0600 Subject: 2**2**2**2**2 wrong? Bug? References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> <1184351416.166930.290710@k79g2000hse.googlegroups.com> Message-ID: On Fri, 13 Jul 2007 11:30:16 -0700, Paul McGuire wrote: >On Jul 13, 1:20 pm, Wayne Brehaut wrote: >> On Mon, 09 Jul 2007 23:51:25 -0700, "mensana... at aol.com" >> >> >> >> >> >> wrote: >> >On Jul 9, 11:42?pm, Paul McGuire wrote: >> >> On Jul 9, 11:21 pm, "Jim Langston" wrote:> In Python 2.5 on intel, the statement >> >> > 2**2**2**2**2 >> >> > evaluates to>>> 2**2**2**2**2 >> >> >> > 200352993040684646497907235156025575044782547556975141926501697371089405955 63114 >> >> > 530895061308809333481010382343429072631818229493821188126688695063647615470 29165 >> >> > 041871916351587966347219442930927982084309104855990570159318959639524863372 36720 >> >> >> >> >> >> Exponentiation is right associative, so this is the same as: >> >> >> 2**(2**(2**(2**2))) >> >> 2**2**2**4 >> >> 2**2**16 >> >> 2**65536 >> >> >> 2=10**0.3010, so 2**65536 is approx 10**19726 >> >> >> There are 19730 digits in your answer, >> >> >>>> import gmpy >> >>>> n = 2**2**2**2**2 >> >>>> gmpy.numdigits(n) >> >19729 >> >> >Did you count the 'L'? >> >> numdigits(n)? >> >> What? 'L' is a digit in Python? I'm going back to Fortran! >> >> wwwayne >> >> >> >> >>so this seems to be at least in >> >> the ball park. >> >> >> -- Paul- Hide quoted text - >> >> - Show quoted text -- Hide quoted text - >> >> - Show quoted text - > >'L' counts for 50, but only when you use Roman font. WTL?! Not Times New Roman I hope? Now I'll have to extend my remarks below to include: L**L**L D**D**D M**M**M etc. (since I don't recall what comes next) though these (L, D, M, ...) would seem to be numbers rather than digits: the Romans used a base-1 system [for purposes of this argument, at least] so I is the only Roman digit* and the others are just shorthand for: I = 1 V = IIIII X = I*10 L = I*50 D = I*500 M = I*1000 etc. --- For those who don't know which Roman digit I represents: | _\|/__ wwwayne > >-- Paul From tenax.raccoon at gmail.com Mon Jul 23 13:57:25 2007 From: tenax.raccoon at gmail.com (Jason) Date: Mon, 23 Jul 2007 17:57:25 -0000 Subject: decorators tutorials In-Reply-To: <1185211521.843260.8200@k79g2000hse.googlegroups.com> References: <1185178383.499234.299850@z24g2000prh.googlegroups.com> <1185211521.843260.8200@k79g2000hse.googlegroups.com> Message-ID: <1185213445.322126.305990@d55g2000hsg.googlegroups.com> On Jul 23, 11:25 am, Jason wrote: > On Jul 23, 2:13 am, james_027 wrote: > > > Hi, > > > I am learning python by learning django, and I stumble upon decorator > > which is very cool, any beginners resources for python decorators, > > although I can google it, I just want to get a good tutorial for this > > topic. > > > Thanks > > james With apologies, there is an error in my previous WrapWithHelpDebug. The last part of the function should read: # Back in the WrapWithHelpDebug scope. # HelpDebug is now a function objected defined in this scope. return HelpDebug # This line was missing Now, my prior post shows how decorators work. Functions are objects created by Python's def statement. They have access to the names in all their enclosing scopes: the module's global scope and any functions that they are nested in. The WrapWithHelpDebug decorator wraps a function so uncaught exceptions get caught, logged, and the Python debugger is started. You won't notice much output from the logger usually, because the default log level is set to "DEBUG". That might be fine, but maybe you want to pass the debugging level as a parameter. import logging def WrapWithHelpDebug(func, logLevel): """Returns a function object that transparently wraps the parameter with the HelpDebug function""" # The def statement actually defines a function object and binds # it to a name. Since it is nested in this function, the def # statement isn't evaluated until def HelpDebug(*args, **keyargs): "Assist with debugging a function." # The func argument is a Pythong function object # arg is the positional arguments that follow the # first parameter, and keyargs has the keyword arguments. try: # The name "func" comes from the outer scope, WrapWithHelpDebug returnValue = func(*args, **keyargs) return returnValue except SystemExit: raise # Reraise the system exit exception except Exception, error: from logging import log from sys import exc_info import pdb log(logLevel, "Caught Exception: %s", error) # Start the debugger at the place where the # exception occurred pdb.post_mortem(exc_info()[2]) return # Nothing to return when an exception occurred # Back in the WrapWithHelpDebug scope. # HelpDebug is now a function objected defined in this scope. return HelpDebug def DivXY(x, y): "Divides X by Y" return x / y DivXY = WrapWithHelpDebug(DivXY, logging.DEBUG) # Debug the following calls DivXY(5.0, 2.1) # This will succeed DivXY(10.0, 0.0) # Causes a ZeroDivisionError exception So, if we just need to add a new parameter, how do we do that with a decorator? Could we use "@WrapWithHelpDebug(logging.DEBUG)"? No. Remember, the decorator symbol is just a bit of syntactic sugar. It turns: @WrapWithHelpDebug(logging.DEBUG) def DivXY(x, y): "Divides X by Y" return x / y Into: def DivXY(x, y): "Divides X by Y" return x / y DivXY = WrapWithHelpDebug(logging.DEBUG)(DivXY) Oops! That implies that we're calling "WrapWithHelpDebug" with our logging parameter. To accommodate the extra parameter, we're going to need to use Python's nested scopes again. Here's a final version that does everything we want: import logging def HelpDebugDecorator(logLevel): "Returns a function object that will properly decorate a function." # Note that logLevel used in the nested function HelpDebug # comes from this scope. def WrapWithHelpDebug(func): """Returns a function object that transparently wraps the parameter with the HelpDebug function""" # The def statement actually defines a function object and binds # it to a name. Since it is nested in this function, the def # statement isn't evaluated until def HelpDebug(*args, **keyargs): "Assist with debugging a function." # The func argument is a Pythong function object # arg is the positional arguments that follow the # first parameter, and keyargs has the keyword arguments. try: # The name "func" comes from the outer scope, WrapWithHelpDebug returnValue = func(*args, **keyargs) return returnValue except SystemExit: raise # Reraise the system exit exception except Exception, error: from logging import log from sys import exc_info import pdb log(logLevel, "Caught Exception: %s", error) # Start the debugger at the place where the # exception occurred pdb.post_mortem(exc_info()[2]) return # Nothing to return when an exception occurred # Back in the WrapWithHelpDebug scope. # HelpDebug is now a function objected defined in this scope. return HelpDebug # Back in the HelpDebugDecorate scope. # Return the WrapWithHelpDebug function object return WrapWithHelpDebug @HelpDebugDecorator(logging.ERROR) def DivXY(x, y): "Divides X by Y" return x / y #DivXY = WrapWithHelpDebug(DivXY, logging.DEBUG) # Debug the following calls DivXY(5.0, 2.1) # This will succeed DivXY(10.0, 0.0) # Causes a ZeroDivisionError exception Just a few final notes about decorators: o Multiple decorators can be applied to a function. o Any callable (such as classes and instances with a __call__ method) can be used as a decorator. This can be tremendously useful if you need to save state between multiple decorated calls. For example, you might want the log when certain functions are called. Perhaps you want to indent each successive call, and dedent with every decorated return. Use an instance to keep track of the indents and dedents. I hope that I haven't made any egregious errors in these two posts. However, decorates are a very nifty Python feature, and I hope this helps you understand them. --Jason From orsenthil at users.sourceforge.net Tue Jul 17 22:39:43 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Wed, 18 Jul 2007 08:09:43 +0530 Subject: urllib to cache 301 redirections? In-Reply-To: References: <87wsxds6sq.fsf@pobox.com> <20070716190319.GA7184@gmail.com> Message-ID: <20070718023943.GA5654@gmail.com> * John J Lee [2007-07-16 20:17:40]: > > I spent a little time thinking about a solution and figured out that the > > following changes to HTTPRedirectHandler, might be helpful in implementing > > this. > > Did you post it on the Python SF patch tracker? > > If not, please do, and point us at it. I'll comment there. Posted: http://www.python.org/sf/1755841 Thanks, -- O.R.Senthil Kumaran http://uthcode.sarovar.org From ahlongxp at gmail.com Sun Jul 8 09:08:06 2007 From: ahlongxp at gmail.com (ahlongxp) Date: Sun, 08 Jul 2007 13:08:06 -0000 Subject: socket: connection reset by server before client gets response In-Reply-To: References: <1183819907.249945.239700@o11g2000prd.googlegroups.com> <1183827514.109496.252870@d30g2000prg.googlegroups.com> Message-ID: <1183900086.021428.83580@e9g2000prf.googlegroups.com> > Try to wait a while in the server thread, after sending the > message before closing the connection, to give the message > time to get transmitted. > > time.sleep(0.5) should do it... > > - Hendrik OMG, it works. I can't believe the problem can be solved so easily. Thanks very much. From horpner at yahoo.com Mon Jul 30 11:27:32 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 30 Jul 2007 15:27:32 GMT Subject: Replacing overloaded functions with closures. References: <1185807536.021216.278500@22g2000hsm.googlegroups.com> Message-ID: On 2007-07-30, king kikapu wrote: > i am trying, to no avail yet, to take a C#'s overloaded > functions skeleton and rewrite it in Python by using closures. > I read somewhere on the net > (http://dirtsimple.org/2004/12/python-is- not-java.html) that > in Python we can reduce code duplication for overloaded > functions by using closures. > > I do not quite understand this. Let's say we have the following > simple C# code: > > int func(int i) { return i * 2; } > string func(string s) { return s + s; } > bool func(bool f) { return !f; } > > I wasn't able to find a way to express this thing in closures. The closures discussed in the article are not a solution for function overloading. They are a solution for function composition. Python generally has no need for function name overloading--if you really want it you must do it manually using runtime type checking. def func(obj): if isinstance(obj, bool): return not obj elif isinstance(obj, int): return obj * 2 elif isinstance(obj, basestring): return obj + obj else: raise NotImplementedError('type %r not supported' % type(obj)) The article you linked, when discussing Python closures is really just advocating the use of higher-order functions. But Java's verbosity and lack of free functions are the only irritating obstacle to using them just as you would in Python. I'm not sure what the author was getting at, exactly. -- Neil Cerutti From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Jul 21 06:02:59 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 21 Jul 2007 12:02:59 +0200 Subject: Sorting dict keys References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> <1185007449.179903.5480@w3g2000hsg.googlegroups.com> Message-ID: <5ge3ujF3fk7i6U2@mid.individual.net> montyphyton at gmail.com wrote: > I'd like to do it in one line because what I am trying to do is, > after all, a single, simple enough action. No, it's two actions: 1. You extract a list of keys from the dict 2. you sort it > I find the suggested b = sorted(a.keys()) much more readable than > breaking it up in two lines. In the long run, I guess it's a > matter of personal taste... Yes. You'll see, at least if you do a third thing with the list it will start to become less well-readable. Regards, Bj?rn -- BOFH excuse #450: Terrorists crashed an airplane into the server room, have to remove /bin/laden. (rm -rf /bin/laden) From wildemar at freakmail.de Thu Jul 12 18:51:47 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Fri, 13 Jul 2007 00:51:47 +0200 Subject: [Fwd: RE: Lists in classes] Message-ID: <4696B083.70801@freakmail.de> Another one bitten by the 'missing' reply-to munging ;) You might want to ensure that you always reply to python-list at python.org intsead of the message author. -------- Original Message -------- Subject: RE: Lists in classes Date: Thu, 12 Jul 2007 16:58:50 -0500 From: Adam Pletcher To: Wildemar Wildenburger References: <1184254414.236260.108860 at m3g2000hsh.googlegroups.com> <46964E1E.3050203 at freakmail.de> I'm curious (and somewhat new to Python)... What's the benefit of inheriting from 'object'? The docs aren't clear on that, nor is that used in the class examples I've seen. Thanks in advance. - Adam From bj_666 at gmx.net Wed Jul 4 10:32:36 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 4 Jul 2007 14:32:36 GMT Subject: Proposal: s1.intersects(s2) References: <87sl84l16r.fsf@grogan.peloton> Message-ID: <5f1pc4F3a62csU4@mid.uni-berlin.de> On Wed, 04 Jul 2007 16:18:58 +0200, Thomas Jollans wrote: > On Wednesday 04 July 2007, David Abrahams wrote: >> Right now, the only convenient thing to do is >> >> if s1 & s2 ... >> >> but that builds a whole new set. IMO that query should be available >> as a method of set itself. > >>>> s1 = set(xrange(5)) >>>> s2 = set(xrange(3,9)) >>>> s1 > set([0, 1, 2, 3, 4]) >>>> s2 > set([3, 4, 5, 6, 7, 8]) >>>> s1 | s2 > set([0, 1, 2, 3, 4, 5, 6, 7, 8]) >>>> s1 & s2 > set([3, 4]) >>>> > > It's all in python already. And documented on the web too. The OP already knows that but does not want to build a new `set`. He just wants to know efficiently if the sets intersect without actually *doing* the intersection. Ciao, Marc 'BlackJack' Rintsch From mensanator at aol.com Wed Jul 25 21:17:19 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Wed, 25 Jul 2007 18:17:19 -0700 Subject: From D In-Reply-To: <87ps2ghtd7.fsf@benfinney.id.au> References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> <87ps2ghtd7.fsf@benfinney.id.au> Message-ID: <1185412639.075218.186290@z24g2000prh.googlegroups.com> On Jul 25, 8:00 pm, Ben Finney wrote: > "mensana... at aol.com" writes: > > On Jul 24, 6:08 pm, Steven D'Aprano > > wrote: > > > Python already does: > > > "hello-" "world" => "hello-world" > > > > Propose: > > > 123 456 789 => 123456789 > > > 123.456 789 => 123.456789 > > > So, spaces will no longer be delimiters? > > I don't see how you get that conclusion from Steven's proposal. IDLE 1.2c1 >>> s = '123 456' >>> s.split() ['123', '456'] The only way to get '123 456' would be to treat a space as a non-delimiter. But what if those actually WERE two different numbers? > If the > latter implied that "spaces will no longer be delimiters", then surely > the former must also imply that. > > The former already exists, spaces are still delimiters when syntax > allows, so your conclusion is baseless. > > -- > \ "I got food poisoning today. I don't know when I'll use it." | > `\ -- Steven Wright | > _o__) | > Ben Finney From __peter__ at web.de Thu Jul 5 04:34:54 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Jul 2007 10:34:54 +0200 Subject: Find This Module References: <1183579207.226611.192520@57g2000hsv.googlegroups.com> Message-ID: gregpinero at gmail.com wrote: > I'm looking at the source for the module sre_compile.py and it does > this import: > > import _sre > > But I can't find a file related to _sre anywhere. Where is it? If you want the source code, have a look at http://svn.python.org/view/python/trunk/Modules/_sre.c?rev=52147&view=markup > And more generally, how does one find the location of a built in module? For the source of modules written in C, built in or not, you have to look in the source distribution. Peter From sjmachin at lexicon.net Sat Jul 7 20:13:48 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 07 Jul 2007 17:13:48 -0700 Subject: Where is the syntax for the dict() constructor ?! In-Reply-To: <5f8rrpF3c8qopU1@mid.uni-berlin.de> References: <468D1D9D.6060002@gmail.com> <468D3445.2060408@gmail.com> <1183675552.466967.136360@i13g2000prf.googlegroups.com> <5f6fo1F3b25tsU1@mid.uni-berlin.de> <5f8rrpF3c8qopU1@mid.uni-berlin.de> Message-ID: <1183853628.296224.107400@i13g2000prf.googlegroups.com> On Jul 7, 4:58 pm, Marc 'BlackJack' Rintsch wrote: > On Sat, 07 Jul 2007 08:32:52 +0200, Hendrik van Rooyen wrote: > >> erik,viking,"ham, spam and eggs","He said ""Ni!""","line one > >> line two" > > >> That's 5 elements: > > >> 1: eric > >> 2: viking > >> 3: ham, spam and eggs > >> 4: He said "Ni!" > >> 5: line one > >> line two > > > Also true - What can I say - I can only wriggle and mutter... > > > I see that you escaped the quotes by doubling them up - > > That's how Excel and the `csv` module do it. > > > What would the following parse to?: > > > erik,viking,ham, spam and eggs,He said "Ni!",line one > > line two > > Why don't you try yourself? The `csv` module returns two records, the > first has six items: > > 1: erik > 2: viking > 3: ham > 4: spam and eggs > 5: He said "Ni!" > 6: line one > > 'line two' is the only item in the next record then. > The rules for quoting when writing can be expressed as: def outrow(inrow, quotechar='"', delimiter=','): out = [] for field in inrow: if quotechar in field: field = quotechar + field.replace(quotechar, quotechar*2) + quotechar elif delimiter in field or '\n' in field: # See note below. field = quotechar + field + quotechar out.append(field) return delimiter.join(out) Note: characters other than delimiter and \n can be included in the "to be quoted" list. What readers do with data that can *not* have been produced by a writer following the rules can get worse than BlackJack's example. Consider this: file nihao1.csv contains the following single line: 'Is the "," a mistake in "Ni, hao!"?\r\n' Openoffice.org's Calc 2.1 shows the equivalent of ['Is the "', ' a mistake in Ni', ' hao!"?\n'] in a Text Import window, but then silently produces nothing. A file with two such lines causes 5 fields to be shown in the window -- it apparently thinks the newlines are inside quoted fields! Gnumeric 1.7.6 silently produces the equivalent of result = ['Is the "', ' a mistake in ', 'hao!"?'] map(len, result) -> [8, 14, 6] What happened to Ni? Multiple such lines produce multiple rows. Excel 11.0 (2003) silently produces in effect result = ['Is the "', ' a mistake in Ni', ' hao!"?'] map(len, result) -> [8, 16, 7] Multiple such lines produce multiple rows. The csv module does what Excel does. Consumers of csv files are exhorted to apply whatever sanity checks they can. Examples: (1) If the csv file was produced as a result of a database query, the number of columns should be known and used as a check on the length of each row received. (2) A field containing an odd number of " characters (or more generally, not meeting whatever quoting convention might be expected in the underlying data) should be treated with suspicion. Cheers, John From python at jayloden.com Sat Jul 21 01:27:24 2007 From: python at jayloden.com (Jay Loden) Date: Sat, 21 Jul 2007 01:27:24 -0400 Subject: NTLM APS python version 0.98 In-Reply-To: <1184945759.346727.190650@j4g2000prf.googlegroups.com> References: <1184945759.346727.190650@j4g2000prf.googlegroups.com> Message-ID: <46A1993C.9040304@jayloden.com> pycraze wrote: > Hi , > > I am working on NTLM (Windows NT Lan Manager )APS > (Authentication Proxy Server ) , to port to C language . the 'wget' utility supports NTLM authentication as of version 1.1.0 or so, you might try just looking at the C source code to wget if you're looking to implement an NTLM client in C (I think that's what you were asking?). -Jay From p at ulmcnett.com Thu Jul 12 17:35:19 2007 From: p at ulmcnett.com (Paul McNett) Date: Thu, 12 Jul 2007 14:35:19 -0700 Subject: New guy help with setup In-Reply-To: <1184275783.250640.327630@g4g2000hsf.googlegroups.com> References: <1184275051.504507.116080@57g2000hsv.googlegroups.com> <1184275783.250640.327630@g4g2000hsf.googlegroups.com> Message-ID: <46969E97.4000504@ulmcnett.com> meg99 wrote: > On Jul 12, 4:24 pm, Paul McNett wrote: >> meg99 wrote: >>> I just downloaded 2.5 and read the readme file. It says "Before you >>> can build Python, you must first confiigure it....Start by running the >>> script "./configure". >>> I can't find "./configure" >>> I am running Windows XP SP2 >> You downloaded the wrong file. You want the Windows Installer:http://python.org/ftp/python/2.5.1/python-2.5.1.msi > My applogies - I did download and install 2.5.1 In that case, open up your command window (Start|Run "cmd" ). Type 'python' at the c:\ prompt. Or, Start|All Programs|Python 2.5|IDLE Enjoy! -- pkm ~ http://paulmcnett.com From cito at online.de Sun Jul 15 05:01:51 2007 From: cito at online.de (Christoph Zwerschke) Date: Sun, 15 Jul 2007 11:01:51 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: References: <1183863713.876365.111820@57g2000hsv.googlegroups.com> <1184239885.828717.271410@r34g2000hsd.googlegroups.com> <1184258925.321462.50270@k79g2000hse.googlegroups.com> <1184345588.791872.79010@d55g2000hsg.googlegroups.com> Message-ID: Christoph Zwerschke wrote: > But my __getattr__ solution does not work either, since the attributes > are set to None when initialized, so __getattr__ is never called. Here is a simple solution, but it depends on the existence of the args attribute that "will eventually be deprecated" according to the docs: def PoliteException(e): E = e.__class__ class PoliteException(E): def __str__(self): return str(e) + ", sorry!" PoliteException.__name__ = E.__name__ return PoliteException(*e.args) try: unicode('\xe4') except Exception, e: p = PoliteException(e) assert p.reason == e.reason raise p From sjmachin at lexicon.net Thu Jul 12 08:20:14 2007 From: sjmachin at lexicon.net (John Machin) Date: Thu, 12 Jul 2007 05:20:14 -0700 Subject: allow scripts to use .pth files? In-Reply-To: <1184241309.629557.226820@w3g2000hsg.googlegroups.com> References: <1183899193.766331.13210@22g2000hsm.googlegroups.com> <1183928022.719873.49470@i38g2000prf.googlegroups.com> <1184241309.629557.226820@w3g2000hsg.googlegroups.com> Message-ID: <1184242814.390394.324200@n60g2000hse.googlegroups.com> On Jul 12, 9:55 pm, samwyse wrote: > On Jul 8, 3:53 pm, John Machin wrote: > > > > > I got the impression that the OP was suggesting that the interpreter > > look in the directory in which it found the script. > [...] > > I got the impression that the problem was that the package was not > > only not on sys.path but also not in the same directory as the script > > that wanted to import it. Otherwise the OP's script.p?h file need only > > contain ".\n" (or the path to the directory in which it resided!!), > > and I doubt that he was proposing something so silly. > > And as I'm sure you realize, those two impression slightly contradict > each other. Your sureness is misplaced. Please explain. From george.sakkis at gmail.com Tue Jul 3 15:13:32 2007 From: george.sakkis at gmail.com (George Sakkis) Date: Tue, 03 Jul 2007 19:13:32 -0000 Subject: try/finally in threads In-Reply-To: <5euhq4F3aje0iU1@mid.uni-berlin.de> References: <1183430999.552755.83550@57g2000hsv.googlegroups.com> <5euhq4F3aje0iU1@mid.uni-berlin.de> Message-ID: <1183490012.388811.97330@k29g2000hsd.googlegroups.com> On Jul 3, 5:05 am, "Diez B. Roggisch" wrote: > George Sakkis wrote: > > I posted this on the Pyro list but I'm not sure if it's related > > specifically to Pyro. The "finally" clause below is not executed when > > f() runs on on a (daemon) thread and the program exits. DAEMON here is > > a global Pyro.code.Daemon instance. > > > def f(): > > try: DAEMON.requestLoop() > > finally: > > # nothing is printed if f() runs in a thread > > print "i am here!!" > > DAEMON.shutdown() > > print "i am over!!" > > > Is "finally" not guaranteed to be executed in a non-main thread or is > > there something else going on ? > > Well, that's pretty much the idea behind daemon threads - that they are > terminated immediately. If it were otherwise, a little endless-loop in that > finally-statement of yours would cause the program termination to hang > endlessly. Thanks, that makes sense; if the thread is non-daemon, it enters the finally block as expected. George From wbrehaut at mcsnet.ca Sun Jul 15 18:37:20 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Sun, 15 Jul 2007 16:37:20 -0600 Subject: 2**2**2**2**2 wrong? Bug? References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> <1184351416.166930.290710@k79g2000hse.googlegroups.com> <1184362323.476796.22570@w3g2000hsg.googlegroups.com> Message-ID: <746l93p0mkhljcuc7qsdk7pl908qnpenni@4ax.com> On Sun, 15 Jul 2007 17:37:13 -0400, Steve Holden wrote: >Wayne Brehaut wrote: >> On Fri, 13 Jul 2007 14:32:03 -0700, "mensanator at aol.com" >[...] >> But I digress (but only because provoked!)... >> >>>> [for purposes of this argument, at least] >> >> This statement is the informal equivalent to saying "Define a base-1 >> number system as...", as I noted above. If you'd noted this, and >> understood it, or were willing to accept it whether or not you >> understood it, you'd have saved us both some bother--but me more than >> you I guess, so maybe you were just trolling? >> >wwway to beat a response to a pulp. Sometimes it's easier and better for >your blood pressure just to let someone else have the last word, however >ill-informed or hostile. Best answer: Not hit Reply or Send. [Too late!] Short answer: Yes, I agree--and thank you for this sage advice! My answer: Guilty with an explanation. I tend to use a "stream of consciousness approach" when I have time, so my responses tend to grow until I run out of time or energy, or I'm called to dinner (so not without bounds). Also, I tend to follow the general Evolutionarily Stable Strategy generally called "Retaliator". In the simple game of Hawk vs. Dove a Hawk always attacks and defends to the death, whereas a Dove always runs. A mixed strategy would be to sometimes attack-and-defend and sometimes run, and a special case is to always run except when you're attacked--then defend to the death; i.e., behave like a Dove to a Dove and like a Hawk to a Hawk. In Game Theory, if not in practice, Retaliator is dominant over both pure Hawk and pure Dove, partly because some who present like Hawks are actually Bullies--who behave like Hawks until an opponent defends, then behave like Doves. Of course this should be a cooperative group to help one another learn more about Python and solve problems--perhaps with an occasional sidebar of humour for relaxation-- rather than attacking and defending; but when someone attacks my attempt at humour, or makes a demonstrably incorrect statement attacking my peaceable, well-reasoned one, I get really POd and my Hawk-like tendencies emerge. And my blood pressure is fine, though I am monitoring it... Moreover, I find it's sometimes harder on my blood pressure to lie awake at night thinking of all the things I would have liked to say and didn't. But thank you for this sage advice! w >regards > Steve From kar1107 at gmail.com Tue Jul 17 16:43:38 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Tue, 17 Jul 2007 13:43:38 -0700 Subject: a=0100; print a ; 64 how to reverse this? In-Reply-To: <469cb76f$0$7584$426a34cc@news.free.fr> References: <1184670575.205759.115360@i13g2000prf.googlegroups.com> <469cb76f$0$7584$426a34cc@news.free.fr> Message-ID: <1184705018.586170.59080@g12g2000prg.googlegroups.com> On Jul 17, 5:35 am, Bruno Desthuilliers wrote: > mosi a ?crit : > > > > > Problem: > > how to get binary from integer and vice versa? > > The simplest way I know is: > > a = 0100 > > a > > 64 > > > but: > > a = 100 (I want binary number) > > does not work that way. > > > a.__hex__ exists > > a.__oct__ exists > > > but where is a.__bin__ ??? > > > What`s the simplest way to do this? > > bruno at bruno:~$ 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. > >>> help(int) > Help on class int in module __builtin__: > > class int(object) > | int(x[, base]) -> integer > | > | Convert a string or number to an integer, if possible. A floating > point > | argument will be truncated towards zero (this does not include a string > | representation of a floating point number!) When converting a > string, use > | the optional base. It is an error to supply a base when converting a > | non-string. If the argument is outside the integer range a long object > | will be returned instead. > > >>> a = int('100', 2) > >>> a > 4 > >>> > > HTH While it's interesting to know we can go from binary to int, the OP wanted the other way. I think it will be a nice enhancement to add to % operator (like %x, something for binary, %b or %t say) or something like a.__bin__ as suggested by the OP. FWIW, gdb has a /t format to print in binary. (gdb) p 100 $28 = 100 (gdb) p /x 100 $29 = 0x64 (gdb) p /t 100 $30 = 1100100 (gdb) --Karthik From carsten at uniqsys.com Tue Jul 24 11:12:36 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 24 Jul 2007 11:12:36 -0400 Subject: Closures / Blocks in Python In-Reply-To: <1185289112.771239.200260@n60g2000hse.googlegroups.com> References: <1185289112.771239.200260@n60g2000hse.googlegroups.com> Message-ID: <1185289956.3370.21.camel@dot.uniqsys.com> On Tue, 2007-07-24 at 14:58 +0000, treble54 wrote: > Does anyone know a way to use closures or blocks in python like those > used in Ruby? Particularly those used in the { } braces. Please describe the problem you're trying to solve. Even if Python had a direct equivalent of "Ruby closures or blocks", which I don't think it does, it may not be the best solution to your problem. -- Carsten Haese http://informixdb.sourceforge.net From http Sun Jul 1 19:48:42 2007 From: http (Paul Rubin) Date: 01 Jul 2007 16:48:42 -0700 Subject: Portable general timestamp format, not 2038-limited References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <7xsl88eyud.fsf@ruckus.brouhaha.com> Message-ID: <7xd4zbd6sl.fsf@ruckus.brouhaha.com> Dennis Lee Bieber writes: > What is not mentioned is that, as part of the data stream picked up > by GPS receivers, is a term specifying the "correction factor" between > GPS and UTC; so receivers can display UTC time. Oh yes, good point, the article ought to mention that. From robert.rawlins at thinkbluemedia.co.uk Wed Jul 4 05:58:43 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 4 Jul 2007 10:58:43 +0100 Subject: Which Python Version Message-ID: <00ac01c7be22$01202d80$03608880$@rawlins@thinkbluemedia.co.uk> Hello Chaps, Is there a command I can run to confirm which version of python I'm running? Another thing I've always wondered, should i be running my applications using './MyFile.py' or 'Python MyFile.Py' what are the benefits of each method? One thing I have noticed is that when I used 'Python MyFile.Py' my processor usage was a lot higher, is that normal? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From rhc28 at cornell.edu Thu Jul 12 01:14:38 2007 From: rhc28 at cornell.edu (Rob Clewley) Date: Thu, 12 Jul 2007 01:14:38 -0400 Subject: ANN: PyDSTool 0.85 released Message-ID: We have released an update to the PyDSTool dynamical systems and modeling package at http://sourceforge.net/projects/pydstool. There are lots of minor improvements and fixes in this version, but a powerful new feature is the support for user-defined functions for continuation using PyCont. We have also added some tools for basic phase-plane analysis, calculation of phase response curves for oscillators, and support for some special math functions. Please see the release notes for more details, and the documentation at http://pydstool.sourceforge.net. We plan to continue to add features and improve our code over the coming months, and we look forward to hearing feedback on our progress. In particular, contributions are very welcome. Thanks again to the Scipy, Numpy, Matplotlib, and SWIG developers for facilitating our work! -- The PyDSTool developers From moranar at gmail.com Sun Jul 8 04:28:35 2007 From: moranar at gmail.com (Adriano Varoli Piazza) Date: Sun, 08 Jul 2007 01:28:35 -0700 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1183856442.027967.272530@g4g2000hsf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1183841277.333384.188950@g4g2000hsf.googlegroups.com> <1183856442.027967.272530@g4g2000hsf.googlegroups.com> Message-ID: <1183883315.265068.61600@n60g2000hse.googlegroups.com> Twisted wrote: [...] BASTA. Basta, cazzo (unprintable, Italian). Stop it. It wasn't funny 10 messages into your subthread, and it's even less fun now. It's obvious you're trolling, but nevertheless, in the undescribably improbable case you _are_ being serious: a) Notepad is over there: --->* b) If you do want to keep an antediluvian copy of emacs -probably versioned in the negative numbers, for all you've said- please do. Do be so kind as to send a copy, since it might be quite valuable as an antique. c) Powerful programming editors assume some willingness to learn their interface. Deal. d) Your capacity of denial is remarkable. Please do send us your contact info, so that we may avoid dealing with you on a professional basis. -- killfile-ly yours, Adriano From larry.bates at websafe.com Thu Jul 12 18:10:57 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 12 Jul 2007 17:10:57 -0500 Subject: How to create new files? In-Reply-To: <1184274877.612434.26870@k79g2000hse.googlegroups.com> References: <1184274877.612434.26870@k79g2000hse.googlegroups.com> Message-ID: <-dGdnQZsf9R5OwvbnZ2dnUVZ_jydnZ2d@comcast.com> Robert Dailey wrote: > Hi, > > I'm trying to create a Python equivalent of the C++ "ifstream" class, > with slight behavior changes. > > Basically, I want to have a "filestream" object that will allow you to > overload the '<<' and '>>' operators to stream out and stream in data, > respectively. So far this is what I have: > > class filestream: > def __init__( self, filename ): > self.m_file = open( filename, "rwb" ) > > # def __del__( self ): > # self.m_file.close() > > def __lshift__( self, data ): > self.m_file.write( data ) > > def __rshift__( self, data ): > self.m_file.read( data ) > > > So far, I've found that unlike with the C++ version of fopen(), the > Python 'open()' call does not create the file for you when opened > using the mode 'w'. I get an exception saying that the file doesn't > exist. I expected it would create the file for me. Is there a way to > make open() create the file if it doesn't exist, or perhaps there's > another function I can use to create the file? I read the python docs, > I wasn't able to find a solution. > > Also, you might notice that my "self.m_file.read()" function is wrong, > according to the python docs at least. read() takes the number of > bytes to read, however I was not able to find a C++ equivalent of > "sizeof()" in Python. If I wanted to read in a 1 byte, 2 byte, or 4 > byte value from data into python I have no idea how I would do this. > > Any help is greatly appreciated. Thanks. > open creates files for me, so I'm uncertain why you think it isn't for you. the .read() method accepts the number of bytes not the buffer to store bytes read. data=self.m_file.read(4) would read 4 bytes into string object pointed to by data. sizeof() in Python is len() -Larry From gh at ghaering.de Mon Jul 9 09:11:56 2007 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Mon, 09 Jul 2007 15:11:56 +0200 Subject: Per thread data In-Reply-To: <469230a0$0$5856$da0feed9@news.zen.co.uk> References: <469230a0$0$5856$da0feed9@news.zen.co.uk> Message-ID: <5feqgsF3ce9q7U1@mid.uni-berlin.de> Will McGugan wrote: > Hi, > > Is there a canonical way of storing per-thread data in Python? Good question. There's threading.local() which creates a thread-local object for you. Maybe this Cookbook entry is helpful: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302088 -- Gerhard From bj_666 at gmx.net Fri Jul 27 13:02:29 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 27 Jul 2007 17:02:29 GMT Subject: 128 or 96 bit integer types? References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com> Message-ID: <5gump5F3iotlrU1@mid.uni-berlin.de> On Fri, 27 Jul 2007 16:45:05 +0000, Robert Dailey wrote: > Is there build-in or third party support for large integer types, such > as 96 or 128 bits in size? Yes there is, just use integer values. If it don't fit into an `int` it gets promoted to a `long`. Python `long`\s are only bounded by available memory. In [59]: 2**128 Out[59]: 340282366920938463463374607431768211456L Ciao, Marc 'BlackJack' Rintsch From rbygscrsepda at gmail.com Fri Jul 27 14:11:14 2007 From: rbygscrsepda at gmail.com (rbygscrsepda at gmail.com) Date: Fri, 27 Jul 2007 11:11:14 -0700 Subject: Relative-importing * Message-ID: <1185559874.299008.167010@x40g2000prg.googlegroups.com> Hi, I'm a newbie at Python. :) Right now it's not letting me import * from any relative package name--i.e., a name that starts with a dot. For instance, none of the following work: from . import * from .sibiling import * from .. import * from ..parent_sibling import * ...and so on. The same error occurs: SyntaxError: 'import *' not allowed with 'from .' (I have Python 2.5.1.) Why would it not let me import * from a relative module at all? I read that they're planning to make absolute imports the default, so I'd think that this sort of thing would become more common in the future. Thanks in advance! :) From steve at holdenweb.com Wed Jul 25 17:52:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Jul 2007 17:52:44 -0400 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185388827.4432.34.camel@dot.uniqsys.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185388827.4432.34.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: > On Wed, 2007-07-25 at 10:42 -0700, walterbyrd wrote: >> "Once you start down the Dark path, forever will it dominate your >> desiny. Consume you, it will." >> - Yoda >> >> I'm fairly new to web-development, and I'm trying out different >> technologies. Some people wonder why PHP is so popular, when the >> language is flawed in so many ways. To me, it's obvious: it's because >> it's much easier to get started with PHP, and once somebody gets >> started with a particular language, that person is likely to stay with >> that language. > > That's a major reason, yes. [...] > What exactly could Python learn from PHP? PHP is a one-trick pony. It > was designed for web applications. People claim they write desktop > applications in PHP, but I don't believe them. > > Python is more powerful and offers a lot more choices. In order for > Python to become more like PHP, somebody would have to make One True Way > of developing web applications in Python, and that's never going to > happen. > > Just my two cents, > I had a client who produced AJAX-based electronic cash registers. For the second generation of their technology they decided to use some bastardized version of PHP with GUI capabilities bolted on. At that point we parted company. I literally couldn't help 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 arkanes at gmail.com Mon Jul 9 11:09:54 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 9 Jul 2007 10:09:54 -0500 Subject: Broken MUA interactions (was: Restarting a Python Application) In-Reply-To: References: <1183498045.092504.229250@m36g2000hse.googlegroups.com> <94ccbe710707071511o3beee718wc12f15082b3c6e18@mail.gmail.com> <87vecvmqw5.fsf_-_@benfinney.id.au> <4866bea60707090648v772e81d2r261e8d927310591c@mail.gmail.com> Message-ID: <4866bea60707090809m3d50c2dane6a6e03cc74896ce@mail.gmail.com> On 7/9/07, Gabriel Genellina wrote: > En Mon, 09 Jul 2007 10:48:39 -0300, Chris Mellon > escribi?: > > > It's working as instructed, but that doesn't mean that it's doing the > > best thing. It's common practice for mailing lists to set the reply-to > > to the list itself, because that's the common case, and because it's > > encouraged to keep discussion on the list. > > > > If whoever manages the python lists doesn't want to do it, either > > because they have some practical reason or because they've got a bug > > up their ass about mail readers without list support, thats fine. But > > it's hardly incorrect to configure it with the reply-to set to the > > list, either. > > No, it's not correct to modify Reply-To. Some reasons: > http://www.unicom.com/pw/reply-to-harmful.html > None of those are reasons, they're opinions and weary old excuses. I'm not necessarily saying munging is the correct thing to do (although, personally, I support it and would prefer if the python lists did it) but it's about a clash of opinions about what cases and behaviors should be supported and encouraged. Since it's obviously not my call as I'm not the admin of the python lists I adjust to what the list does, but claiming that people asking for the other behavior are incorrect or out of line in some way is just unjustified. From crcarleRemoveThis at BOGUSsandia.gov Fri Jul 13 12:06:44 2007 From: crcarleRemoveThis at BOGUSsandia.gov (Chris Carlen) Date: Fri, 13 Jul 2007 09:06:44 -0700 Subject: Can a low-level programmer learn OOP? Message-ID: Hi: From what I've read of OOP, I don't get it. I have also found some articles profoundly critical of OOP. I tend to relate to these articles. However, those articles were no more objective than the descriptions of OOP I've read in making a case. Ie., what objective data/studies/research indicates that a particular problem can be solved more quickly by the programmer, or that the solution is more efficient in execution time/memory usage when implemented via OOP vs. procedural programming? The problem for me is that I've programmed extensively in C and .asm on PC DOS way back in 1988. Then didn't program for nearly 10 years during which time OOP was popularized. Starting in 1999 I got back into programming, but the high-level-ness of PC programming and the completely foreign language of OOP repelled me. My work was in analog and digital electronics hardware design, so naturally I started working with microcontrollers in .asm and C. Most of my work involves low-level signal conditioning and real-time control algorithms, so C is about as high-level as one can go without seriously loosing efficiency. The close-to-the-machine-ness of C is ideal here. This is a realm that I truly enjoy and am comfortable with. Hence, being a hardware designer rather than a computer scientist, I am conditioned to think like a machine. I think this is the main reason why OOP has always repelled me. Perhaps the only thing that may have clicked regarding OOP is that in certain cases I might prefer a higher-level approach to tasks which involve dynamic memory allocation. If I don't need the execution efficiency of C, then OOP might produce working results faster by not having to worry about the details of memory management, pointers, etc. But I wonder if the OOP programmers spend as much time creating classes and trying to organize everything into the OOP paradigm as the C programmer spends just writing the code? Ultimately I don't care what the *name* is for how I program. I just need to produce results. So that leads back to objectivity. I have a problem to solve, and I want to find a solution that is as quick as possible to learn and implement. Problem: 1. How to most easily learn to write simple PC GUI programs that will send data to remote embedded devices via serial comms, and perhaps incorporate some basic (x,y) type graphics display and manipulation (simple drawing program). Data may result from user GUI input, or from parsing a text config file. Solution need not be efficient in machine resource utilization. Emphasis is on quickness with which programmer can learn and implement solution. 2. Must be cross-platform: Linux + Windows. This factor can have a big impact on whether it is necessary to learn a new language, or stick with C. If my platform was only Linux I could just learn GTK and be done with it. I wouldn't be here in that case. Possible solutions: Form 1: Use C and choose a library that will enable cross-platform GUI development. Pro: Don't have to learn new language. Con: Probably will have difficulty with cross-platform implementation of serial comms. This will probably need to be done twice. This will waste time. Form 2: Use Python and PySerial and TkInter or wxWidgets. Pro: Cross-platform goal will likely be achieved fully. Have a programmer nearby with extensive experience who can help. Con: Must learn new language and library. Must possibly learn a completely new way of thinking (OOP) not just a new language syntax. This might be difficult. Form 3: Use LabVIEW Pro: I think that the cross-platform goal can be met. Con: Expensive. I would prefer to use an Open Source solution. But that isn't as important as the $$$. I have also generally found the 2D diagrammatical programming language of "G" as repelling as OOP. I suspect that it may take as much time to learn LabVIEW as Python. In that case the time spent on Python might be better spent since I would be learning something foundational as opposed to basically just learning how to negotiate someone's proprietary environment and drivers. Comments appreciated. -- Good day! ________________________________________ Christopher R. Carlen Principal Laser&Electronics Technologist Sandia National Laboratories CA USA crcarleRemoveThis at BOGUSsandia.gov NOTE, delete texts: "RemoveThis" and "BOGUS" from email address to reply. From aboudouvas at panafonet.gr Tue Jul 31 04:04:18 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: Tue, 31 Jul 2007 01:04:18 -0700 Subject: Replacing overloaded functions with closures. In-Reply-To: References: <1185807536.021216.278500@22g2000hsm.googlegroups.com> <1185810128.237758.17550@k79g2000hse.googlegroups.com> Message-ID: <1185869058.238937.163730@l70g2000hse.googlegroups.com> Ok, i see... Thank you all :) From faulkner891 at gmail.com Sun Jul 22 15:36:44 2007 From: faulkner891 at gmail.com (faulkner) Date: Sun, 22 Jul 2007 12:36:44 -0700 Subject: custom plugin architecture: how to see parent namespace? In-Reply-To: <1185113192.049692.258310@k79g2000hse.googlegroups.com> References: <1185113192.049692.258310@k79g2000hse.googlegroups.com> Message-ID: <1185133004.233815.268980@w3g2000hsg.googlegroups.com> On Jul 22, 10:06 am, escalation746 wrote: > I've got a namespace query that amounts to this: How can an imported > function see data in the parent custom namespace? I have read through > numerous posts which skirt this issue without answering it. > > To illustrate, create plugin.py with a couple of functions. The second > will obviously fail. > > ---- > def Hello(): > print 'hello' > > def ViewValuable(): > print VALUABLE > ---- > > Then create master.py which loads the plugin at runtime, later running > various code fragments against it. > > ---- > # location of plugin module > filespec = '/path/to/plugins/plugin.py' > filepath, filename = os.path.split(filespec) > filename = os.path.splitext(filename)[0] > > # add to system path > if filepath not in sys.path: > sys.path.append(filepath) > > # import into our namespace > space = __import__(filename, globals(), locals(), []) > namespace = space.__dict__ > > # sometime later in the code... define a new function > def _plus(): > print 'plus' > > # add that to our namespace > namespace.update({'Plus': _plus, 'VALUABLE': 'gold'}) > > # run custom code > code = """ > Hello() > Plus() > Valuable() > """ > exec code in namespace > ---- > > This code will echo the lines: > hello > plus > > Followed by a traceback for: > NameError: global name 'VALUABLE' is not defined > > The question is: How do I get a function in plugin.py to see VALUABLE? > Using external storage of some sort is not viable since many different > instances of plugin.py, all with different values of VALUABLE, might > be running at once. (In fact VALUABLE is to be a key into a whole > whack of data stored in a separate module space.) > > Extensive modifications to plugin.py is also not a viable approach, > since that module will be created by users. Rather, I need to be able > to pass something at execution time to make this happen. Or create an > access function along the lines of _plus() that I can inject into the > namespace. > > Any help, please? I've been losing sleep over this one. > > -- robin sys._getframe(1).f_locals From bbxx789_05ss at yahoo.com Mon Jul 2 15:16:22 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 02 Jul 2007 12:16:22 -0700 Subject: subprocess -- broken pipe error In-Reply-To: <1183397577.959518.264230@g4g2000hsf.googlegroups.com> References: <1183396350.429008.185200@n2g2000hse.googlegroups.com> <1183397577.959518.264230@g4g2000hsf.googlegroups.com> Message-ID: <1183403782.214378.270510@m36g2000hse.googlegroups.com> Why doesn't the following program write to the file? driver.py ------- import subprocess as sub p = sub.Popen(["python", "-u", "test1.py"], stdin=sub.PIPE, stdout=sub.PIPE) p.stdin.write("text3") while True: pass ------- test1.py: --------- import sys data = sys.stdin.read() f = open("aaa.txt", "w") f.write(data + "\n") f.close() ----------- After I hit Ctrl+C to end the program and look in the file, the text wasn't written to the file. But, if I change driver.py to the following it works: driver.py: ---------- import subprocess as sub p = sub.Popen(["python", "-u", "test1.py"], stdin=sub.PIPE, stdout=sub.PIPE) p.stdin.write("text3") ------- Ok. So that looks like the data is caught in a buffer--even though the pipes should be unbuffered by default. But this doesn't work: driver.py ---------- import subprocess as sub p = sub.Popen(["python", "-u", "test1.py"], stdin=sub.PIPE, stdout=sub.PIPE) p.stdin.write("text4") p.stdin.flush() while True: pass ------- It just hangs, and then when I hit Ctrl+C and look in the file, the data isn't in there. From vasudevram at gmail.com Sun Jul 1 15:55:21 2007 From: vasudevram at gmail.com (vasudevram) Date: Sun, 01 Jul 2007 19:55:21 -0000 Subject: How does py2exe work? In-Reply-To: References: <1183314093.002061.310700@m37g2000prh.googlegroups.com> <200707012138.10254.thomas@jollans.com> Message-ID: <1183319721.837735.95320@e16g2000pri.googlegroups.com> On Jul 2, 12:43 am, Wildemar Wildenburger wrote: > Thomas Jollans wrote: > > On Sunday 01 July 2007, vasudevram wrote: > > >> Wondering how it works? Does it actually compile the Python source of > >> your script into machine language, or does it do something more like > >> bundling the Python interpreter, the Python libraries and the script > >> itself, into a file? > > > essentially, that's what it does. > > Q: A or B? > A: Yes. > > *nudgenudge* > /W He should have said "the 2nd way" but thanks, I did guess what he meant :-) - Vasudev From mail at microcorp.co.za Mon Jul 9 02:47:58 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 9 Jul 2007 08:47:58 +0200 Subject: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc) References: <1183939608.088756.178320@m37g2000prh.googlegroups.com> Message-ID: <010501c7c1f6$0c6f8820$03000080@hendrik> wrote: > i hope someone here can help me. > > basically, me and my friend have a summer project. > > in this project, we need something that would basically function as a > blender. we know we'll need to buy a motor that spins, but what we're > having trouble with is figuring out how to program it. we want to be > able to control the speed of the motor. how would we accomplish this? > > i'm new to all of this, so i'm having a hard time wrapping my mind > around how it'd be possible to program one of those things :\ > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then > turn the other direction. > > would you program it the same way you would on a personal computer > (via c, python, etc)? It needs a bit more than just the motor - you need to organise some i/o (lines that the computer can control) and some kind of interface to control the power, and you have to put it all together - can you solder? It may be easier to forget about the computer stuff and just use relay logic for direction control - given that it is a DC motor that would turn the other way, and not a universal motor (like the one in a drill, that turns the same way given either AC or DC). Speed control for a small motor can be accomplished by a heavy rheostat in series with the motor. And that should be good enough for a summer project. On the other hand, if you (or your parents) have pots of money then you can buy digital to analog hardware that can be used to tell a powerful DC coupled amplifier what to do, and have a stab at programming the resultant combination. But if I were you, I would do the first kind of thing, and use the rest of the summer to soak up the sun, instead of breathing solder fumes in a basement, or crouching over a keyboard ruining your eyes watching a screen... HTH - Hendrik From steven.klass at gmail.com Mon Jul 9 01:03:22 2007 From: steven.klass at gmail.com (rh0dium) Date: Mon, 09 Jul 2007 05:03:22 -0000 Subject: A clean way to program an interface Message-ID: <1183957402.819499.227350@o11g2000prd.googlegroups.com> Hi all, I got this new radio scanner (toy!!) this weekend and I can access it via a serial cable. I want to write a interface around it but I am looking for some suggestions. I thought at first I would simply class the Scanner and write the various methods as attibutes similar to below.. But then I thought about it and I don't like it for a couple of obvious reasons - there isn't any data checking, and it's terribly repetitive. So I started searching on google - and I think it might be better to use a (sub)class for each function ( class STS, PRG, etc.). where the attributes are accessible as both dict items and lists - which ultimately go and "set" the scanner. I guess my question is this. I have a function SIN which when one argument is given does an effective "get" from the scanner - this returns some 10+ values. When some 10+ parameters are given it does an effective "set" to the scanner. Given that I can't remember all 10+ parameters I attempted below to represent them as a dict where the key tells me what the heck the parameter is supposed to represent. So a simple translation occurs on both the set and get which splits the list into a named dict and vice versa. Question 1 - I think I should be checking the data before a set - is this a smart thing or should I just do a try/ except? Question 2 - Since I only want to do this once (ok twice) should I represent each function as a class or should I keep the code I have below? Thanks == My garbage.. == class Scanner(): def __init__(self, *args, **kwargs): self.uniden=UnidenConnection.UnidenConnection(port=kwargs.get('port', PORT), bps=kwargs.get('bps', 115200), loglevel=self.loglevel) def STS(self): return self.uniden.write("STS") def PRG(self): """Go into programming mode""" if self.uniden.write(sys._getframe().f_code.co_name)[0]=="OK": return True else: return False def PRGWrite(self,command): data = self.uniden.write(command) if data[0] == "NG": if self.PRG(): data = self.uniden.write(command) if not self.EPG(): raise IOError, "Unable to exit programming mode" if data[0] == "ERR": raise IOError, "Error when running command %s" % command return data def EPG(self): """Get out of programming mode""" if self.uniden.write(sys._getframe().f_code.co_name)[0]=="OK": return True else: return False def SCT(self): """Get the system count""" self.systems = int(self.PRGWrite(sys._getframe().f_code.co_name)[0]) return self.systems def SIH(self): """Get the site index head""" self.sih = int(self.PRGWrite(sys._getframe().f_code.co_name) [0]) return self.sih def SIT(self): """Get the site index tail""" self.sit = int(self.PRGWrite(sys._getframe().f_code.co_name) [0]) return self.sit def FWD(self,idx): """Get the next site index""" fwd = int(self.PRGWrite("%s,%s" % (sys._getframe().f_code.co_name,idx))[0]) return fwd def SIF(self, idx, args=None): """Get / Set Site Info""" if args is None: p=self.PRGWrite("%s,%s" % (sys._getframe().f_code.co_name,idx)) t={} t["site_type"],t["name"],t["quick_key"],t["hld"],t["lout"],t["mod"], \ t["att"],t["c- ch"],t["apco"],t["threshold"],t["rev_index"],t["fwd_index"], \ t["sys_index"],t["chn_head"],t["chn_tail"],t["seq_no"],t["start_key"], \ t["latitude"],t["longitude"],t["range"],t["gps_enable"],t["rsv"]=p delitems=[] for item in t: if t[item]=="": delitems.append(item) for x in delitems: del t[x] if len(t.keys())==0: raise IOError, "Unable to program %s - Returned Nothing" % (sys._getframe().f_code.co_name) else: return t else: args["rsv"]="" s=[ args["index"],args["name"],args["quick_key"],args["hld"],args["lout"],args["mod"], \ args["att"],args["c- ch"],args["apco"],args["threshold"],args["start_key"], \ args["latitude"],args["longitude"],args["range"],args["gps_enable"],args["rsv"]] p=self.PRGWrite("%s,%s" % (sys._getframe().f_code.co_name,",".join(s))) if p[0] != "OK": raise IOError, "Unable to program %s - Returned %s" % (sys._getframe().f_code.co_name,p[0]) else: return True def SIN(self, idx, args=None): """Get / Set System Info""" if args is None: p=self.PRGWrite("%s,%s" % (sys._getframe().f_code.co_name,idx)) t={} t["sys_type"],t["name"],t["quick_key"],t["hld"],t["lout"], \ t["dly"],t["skp"],t["rsv"],t["rsv"],t["apco"],t["threshold"], \ t["rev_index"],t["fwd_index"],t["chn_grp_head"],t["chn_grp_tail"], \ t["seq_no"],t["start_key"],t["record"],t["latitude"],t["longitude"], \ t["range"],t["gps enable"],t["rsv"]=p delitems=[] for item in t: if t[item]=="": delitems.append(item) for x in delitems: del t[x] if len(t.keys())==0: raise IOError, "Unable to program %s - Returned Nothing" % (sys._getframe().f_code.co_name) else: return t else: args["rsv"]="" s=[ args["index"],args["name"],args["quick_key"],args["hld"],args["lout"],args["dly"], \ args["skp"],args["rsv"],args["rsv"],args["apco"],args["threshold"],args["start_key"], \ args["record"],args["latitude"],args["longitude"],args["range"],args["gps_enable"],args["rsv"]] p=self.PRGWrite("%s,%s" % (sys._getframe().f_code.co_name,",".join(s))) if p[0] != "OK": raise IOError, "Unable to program %s - Returned %s" % (sys._getframe().f_code.co_name,p[0]) else: return True From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 13 11:07:51 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 13 Jul 2007 17:07:51 +0200 Subject: How to create new files? In-Reply-To: <1184338589.129432.178560@w3g2000hsg.googlegroups.com> References: <1184274877.612434.26870@k79g2000hse.googlegroups.com> <469731ea$0$18333$426a74cc@news.free.fr> <1184338589.129432.178560@w3g2000hsg.googlegroups.com> Message-ID: <4697951d$0$19182$426a34cc@news.free.fr> Robert Dailey a ?crit : > On Jul 13, 3:04 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: (snip) > Thanks for the variable naming tips. Is it normal for Python > programmers to create class members with a _ prefixed? This is the convention to denote implementation attributes. This won't of course prevent anyone to access these attributes, but anyone doing so is on it's own since it has been warned the attribute was not part of the interface. From stefan.behnel-n05pAM at web.de Mon Jul 9 14:31:59 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Mon, 09 Jul 2007 20:31:59 +0200 Subject: Htmllib help In-Reply-To: References: Message-ID: <46927F1F.5010301@web.de> axjacob at comcast.net wrote: > The NullWriter worked perfectly. I will certainly look at HTMLParser. You should rather take a look at lxml. It's much easier to use and much more powerful. http://codespeak.net/lxml/ There is even an improved branch with a package called "lxml.html" that will be merged into lxml 2.0. It features improved support for loads of things you might want to do with HTML, including HTML doctests and simple HTML generation. http://codespeak.net/svn/lxml/branch/html/ http://codespeak.net/svn/lxml/branch/html/doc/lxmlhtml.txt http://codespeak.net/svn/lxml/branch/html/doc/cssselect.txt Have fun, Stefan From anadajames at gmail.com Sat Jul 28 16:52:51 2007 From: anadajames at gmail.com (Ana James) Date: Sat, 28 Jul 2007 13:52:51 -0700 Subject: =?utf-8?B?4peY4pa6RlJFRSBTYXRlbGxpdGUgVFYgb24geW91ciBQQ+KXhOKXmA==?= Message-ID: <1185655971.116595.114930@z24g2000prh.googlegroups.com> 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 For More Details: http://tvonpc.cq.bz From jstroud at mbi.ucla.edu Mon Jul 16 18:12:53 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 16 Jul 2007 15:12:53 -0700 Subject: Break up list into groups In-Reply-To: <1184620307.340479.253430@z28g2000prd.googlegroups.com> References: <1184620307.340479.253430@z28g2000prd.googlegroups.com> Message-ID: danmcleran at yahoo.com wrote: > All, > > I can't seem to find an answer to this question anywhere, but I'm > still looking. My problem is I have a list of values like this: > > l = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, > 13, 0xF0, 14, 0xF1, 15] > > A value with bit 0x80 set delineates the start of a new packet of > information. What I want to do is to group the packets so that 1, 2, 3 > go with the 1st packet tagged 0xF0, 4 ,5, 6 go with the 2nd packet > tagged 0xF0, 7 & 8 go with the packet tagged 0xF1 and so on. The > length of the data associated with each tag can vary. I've already > written an algorithm to do this but I was wondering if some > combination of itertools functions could do the job faster? > > Here's what I've done and the expected output of the algorithm: > > def splitIntoGroups(data): > groups = [] > local = [] > > for value in data: > if 0x80 & value: > if len(local) > 0: > groups.append(local) > > local = [] > local.append(value) > else: > local.append(value) > > if len(local) > 0: > groups.append(local) > > return groups > > l = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, > 13, 0xF0, 14, 0xF1, 15] > > print splitIntoGroups(l) > > Desired result: > > [[240, 1, 2, 3], [240, 4, 5, 6], [241, 7, 8], [242, 9, 10, 11, 12, > 13], [240, 14], [241, 15]] > > Thanks, > > Dan McLeran > Here's how I *would* do it: py> def doit(alist): ... ary = [] ... for i in alist: ... if 0xf0 & i: ... ary.append([i]) ... else: ... ary[-1].append(i) ... return [x for x in ary if x] ... py> doit(alist) [[240, 1, 2, 3], [240, 4, 5, 6], [241, 7, 8], [242, 9, 10, 11, 12, 13], [240, 14], [241, 15]] Here's an ugly way I wouldn't recommended (using itertools groupby): py> from itertools import groupby py> alist = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, ... 0xF1, 7, 8, 0xF2, 9, 10, 11, 12, 13, ... 0xF0, 14, 0xF1, 15] py> def doit(alist): ... i = (list(g) for k,g in groupby(alist, lambda x: 0xf0&x)) ... return [k for k in [j + i.next() for j in i] if len(k)>1] ... py> doit(alist) [[240, 1, 2, 3], [240, 4, 5, 6], [241, 7, 8], [242, 9, 10, 11, 12, 13], [240, 14], [241, 15]] 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 Tue Jul 3 13:24:24 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 03 Jul 2007 17:24:24 GMT Subject: Pretty Scheme, ??? Python References: <46895e12$0$5078$ba4acef3@news.orange.fr> <_Ddii.36114$G23.10348@newsreading01.news.tds.net> <1183418938.911025.55340@w5g2000hsg.googlegroups.com> <1183469909.444902.147310@57g2000hsv.googlegroups.com> <1183480202.655654.100160@k29g2000hsd.googlegroups.com> Message-ID: On 2007-07-03, Paul McGuire wrote: > 2. Change the parse actions to deref the 0'th element of t for > binop and with_. > > num.setParseAction(lambda t: Num(int(t.number))) > id_.setParseAction(lambda t: Id(t.name)) > binop.setParseAction(lambda t: BinOp(t[0].op, t[0].lhs, t[0].rhs)) > with_.setParseAction(lambda t: With(t[0].bound_id, t[0].named_expr, > t[0].bound_body)) Thanks, that solves it. Now to get on with this exercise and find out which version turns out to be easier to modify and extend as the book progresses through all the different programming language features it covers. Scheme is bound to have an unfair advantage, though, as the book was composed for Scheme. I plan to see if I can create a class factory that behaves like the define-type macro, though. That should prove rather useful. The most tedious thing about the Python version is the cruft required by the class hierarchy. -- Neil Cerutti I pulled into a lay-by with smoke coming from under the bonnet. I realized the car was on fire so took my dog and smothered it with a blanket. --Insurance Claim Blooper From iladijas at gmail.com Tue Jul 24 08:36:37 2007 From: iladijas at gmail.com (fynali iladijas) Date: Tue, 24 Jul 2007 05:36:37 -0700 Subject: How to programmatically insert pages into MDI. Message-ID: <1185280597.184328.152920@k79g2000hse.googlegroups.com> Hi, this query is regarding automating page insertions in Microsoft Document Imaging. I have two sets of MDIs generated fortnightly: Invoices and their corresponding Broadcast Certificates; about 150 of each. My billing application can generate one big MDI with all 150 invoices and another with all the Broadcast Certificates. At the moment I take the pages of, say invoice #1 and insert them into a new MDI (calling it in001.mdi). Then I grab the corresponding Broadcast-Certificate- pages of invoice #1 and insert them into in001.mdi. I proceed to complete the rest the same way (quite a pain). Once done, I print each inxxxxx.mdi, setting various printer options such as binding direction, staple & hole-punch etc. What I would like to automate is the coupling of an Invoice & its corresponding Broadcast-Certificate-pages into a new appropriately named MDI & then printing it into one step; iterating over all the xxxxx until done. My billing app can be set to generate each invoice & broadcast certificate separately with a convenient naming convention to aid in program logic (for eg. inxxxxx.mdi & bcxxxxx.mdi) where xxxxx indicates corresponding invoice & respective broadcast certificates. All help and advice will be most appreciated. Thank you. s|a fynali From mccredie at gmail.com Thu Jul 19 19:20:55 2007 From: mccredie at gmail.com (Matt McCredie) Date: Thu, 19 Jul 2007 16:20:55 -0700 Subject: class C: vs class C(object): In-Reply-To: References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> Message-ID: <9e95df10707191620y70de99f4ndd2b369fa8d4f77f@mail.gmail.com> > > >How about "broke" instead of "deprecated": > > > > > > >>> class Old: > >... def __init__(self): > >... self._value = 'broke' > >... value = property(lambda self: self._value) > >... > > How is this broken? Properties are not supported for old-style classes. > They may not support features introduced in new-style classes, but that's > hardly the same as "broken". > What does that give you that this does not: class Old: def __init__(self): self.value = 'broke' To further illustrate, what happens when you do this: class Old: def __init__(self): self._value = 'broke' def _set_value(self, val): print "set called" def _get_value(self): print "get called" return self._value value = property(_get_value, _set_value) x = Old() print x.value x.value = "not broke" print x.value print type(x.value) print x._value This is what happens: >>> x = Old() >>> print x.value get called broke >>> x.value = "not broke" >>> print x.value not broke >>> print type(x.value) >>> print x._value broke Now, no exceptions were raised or anything, but with old-style classes I'm having difficulty thinking of a scenario where they might actually be useful. I suppose you could use it to do a calculation on instance variables and return the result. You are probably better of using a method for that anyway though. Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: From bignose+hates-spam at benfinney.id.au Fri Jul 6 02:24:26 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 06 Jul 2007 16:24:26 +1000 Subject: The best platform and editor for Python References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183646799.400176.144570@k79g2000hse.googlegroups.com> <1183655933.475488.157270@m36g2000hse.googlegroups.com> <1183670009.035673.256680@w5g2000hsg.googlegroups.com> <1i0so61.10qnto712c7dhpN%aleax@mac.com> Message-ID: <87bqeqnj6s.fsf@benfinney.id.au> aleax at mac.com (Alex Martelli) writes: > Kay Schluehr wrote: > > half of the community is happy with Emacs and the other half wants > > to program in a VS-like environment, neither consensus nor > > progress has > > Calling all vi/vim users (and we'll heartily appreciate the support > of TextMate fans, BBEdit ones, etc, etc) -- we're at risk being > defined out of existence, since we're neither happy with Emacs nor > wanting anything like Visual Studio, and yet Kay claims that people > in either category make up the whole (one half plus the other half) > and so that WE DON'T EXIST!!! A ridiculous claim to be sure, but > we'd better let Herr Schluehr know that in no uncertain terms... Bah, it's clear. Vim users are in the *third* half -- the larger one. Anyone not already in those three categories can presumably find a decent half as well. -- \ "Intellectual property is to the 21st century what the slave | `\ trade was to the 16th." -- David Mertz | _o__) | Ben Finney From aisaac at american.edu Tue Jul 10 15:02:29 2007 From: aisaac at american.edu (Alan G Isaac) Date: Tue, 10 Jul 2007 15:02:29 -0400 Subject: bool behavior in Python 3000? In-Reply-To: References: Message-ID: Peter Otten wrote: > The last I have seen is > http://mail.python.org/pipermail/python-3000/2007-January/005284.html OK. Thanks. > Do you care to explain what is broken? I suppose one either finds coercion of arithmetic operations to int to be odd/broken or does not. But that's all I meant. My preference would be for the arithmetic operations *,+,- to be given the standard interpretation for a two element boolean algebra: http://en.wikipedia.org/wiki/Two-element_Boolean_algebra In contrast with the link above, it does not bother me that arithmetic with ints and bools produces ints. Cheers, Alan Isaac From gherzig at fmed.uba.ar Tue Jul 31 17:46:27 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Tue, 31 Jul 2007 18:46:27 -0300 Subject: (May be OT) developing in jython, using in java? Message-ID: <46AFADB3.1@fmed.uba.ar> Hi all. I dont know if this is the right place for asking this, but maybe some of you know where i must go. The thing is: Im writing a very simple class (in python) to access some LDAP server. A companion will access to the same LDAP server too, but his developing in java. So i said "ok, wait, i dont think we have to make the exact same thing twice! Let me see if jython can help us"....I can find (after a quick review) an answer to this: "Can i, using jython, make a package so my companion can import that package as a webservice??" As im farly new in python, *very* new at Java, and *even newer* at jython, my brain just said to me "ok, i dont know, i want a beer", so maybe some of you can gide me to where i must go in order to clarify my ideas. Thanks!!! Gerardo From irmen.NOSPAM at xs4all.nl Tue Jul 3 18:39:54 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 04 Jul 2007 00:39:54 +0200 Subject: Python and ARexx (was Re: Tiny/small/minimalist Python?) In-Reply-To: <18wii.3176$rR.859@newsread2.news.pas.earthlink.net> References: <1183332951.122782.212720@o11g2000prd.googlegroups.com> <7xved3satm.fsf@ruckus.brouhaha.com> <1183389420.175712.59460@z28g2000prd.googlegroups.com> <7xmyyeizf8.fsf@ruckus.brouhaha.com> <468997c7$0$327$e4fe514c@news.xs4all.nl> <18wii.3176$rR.859@newsread2.news.pas.earthlink.net> Message-ID: <468ad03e$0$327$e4fe514c@news.xs4all.nl> Dennis Lee Bieber wrote: > On 3 Jul 2007 10:03:45 GMT, Jorgen Grahn > declaimed the following in > comp.lang.python: > >> How does Python combine with ARexx? Can you control applications >> which provide an ARexx interface? >> > Irmen had supplied a Python module that had ARexx port operations. It was not only possible to control a program with an ARexx port from your Python programs, but it was also possible to create an ARexx host program in Python. That is: a program exposing an ARexx command port to receive ARexx messages. This could be done in a few lines of (python) code. If you're interested, a bit more info is on the AmigaPython page: http://www.monkeyhouse.eclipse.co.uk/amiga/python/ --Irmen From basti.wiesner at gmx.net Tue Jul 3 09:56:42 2007 From: basti.wiesner at gmx.net (Sebastian Wiesner) Date: Tue, 3 Jul 2007 15:56:42 +0200 Subject: The file executing In-Reply-To: <1183470421.012591.243300@k79g2000hse.googlegroups.com> References: <1183426846.550981.11910@m36g2000hse.googlegroups.com> <1183430828.997331.84340@e9g2000prf.googlegroups.com> <1183470421.012591.243300@k79g2000hse.googlegroups.com> Message-ID: <200707031556.47046.basti.wiesner@gmx.net> [ Benjamin ] > On Jul 2, 9:47 pm, Justin Ezequiel > > wrote: > > On Jul 3, 9:40 am, Benjamin wrote: > > > How does one get the path to the file currently executing (not the > > > cwd). Thank you > > > > os.path.dirname(sys.argv[0]) > > The returns the file that was called first, but not the one currently > executing... Use __file__ instead of sys.argv[0] -- Freedom is always the freedom of dissenters. (Rosa Luxemburg) -------------- 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 steve at holdenweb.com Thu Jul 19 21:19:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Jul 2007 21:19:39 -0400 Subject: Data type conversion In-Reply-To: <9f2909fa0707191329g22bdae44oe7e8215947afe973@mail.gmail.com> References: <9f2909fa0707191329g22bdae44oe7e8215947afe973@mail.gmail.com> Message-ID: ervin ramonllari wrote: > Hello everybody, > > I'm trying to read some tables from a MS Access database and dump them > into a Postgres database. > When I read the attributes data types, I get some numeric values, i.e. > if the data type > of an attribute is TEXT, I get a value 202. I don't know how to convert > this number into > a valid data type in Postgres. If someone can help me with this problem, > I would really > appreciate that. > > Thank you in advance, > Given that you already have something that partly solves your problem you might be abel to ge thte rest of hte information you need from this Cookbook recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52267 Hope it 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 http Tue Jul 10 19:56:36 2007 From: http (Paul Rubin) Date: 10 Jul 2007 16:56:36 -0700 Subject: bool behavior in Python 3000? References: Message-ID: <7xodijdd8r.fsf@ruckus.brouhaha.com> Steven Bethard writes: > So it seems like you're really arguing for raising exceptions in all > these situations. That would actually be fine with me since I never > use bools as ints, but I suspect getting it past python-dev will be an > uphill battle since it will break large chunks of code. We had a huge discussion of this stuff when bools were introduced in Python 2.3 or thereabouts. The current system is about the best way that doesn't break everything in sight. The weirdness is basically a consequence of bools being an afterthought in Python. Python has a long tradition of implicitly casting other values to bool, e.g. strings, lists, sets etc. are all false if empty, etc. From stargaming at gmail.com Thu Jul 26 16:19:17 2007 From: stargaming at gmail.com (Stargaming) Date: 26 Jul 2007 20:19:17 GMT Subject: question about math module notation References: Message-ID: <46a901c5$0$25771$9b622d9e@news.freenet.de> On Thu, 26 Jul 2007 15:54:11 -0400, brad wrote: > How does one make the math module spit out actual values without using > engineer or scientific notation? > > I get this from print math.pow(2,64): 1.84467440737e+19 > > I want this: > 18,446,744,073,709,551,616 > > I'm lazy... I don't want to convert it manually :) Explicitly converting it to `int` works for me. (Without the 3-digit- block notation, of course.) From maciej.blizinski at gmail.com Mon Jul 16 10:31:58 2007 From: maciej.blizinski at gmail.com (=?utf-8?B?TWFjaWVqIEJsaXppxYRza2k=?=) Date: Mon, 16 Jul 2007 14:31:58 -0000 Subject: Private functions and inheritance Message-ID: <1184596318.146981.242830@n60g2000hse.googlegroups.com> Hello, I've come across something that I don't quite understand about Python's inheritance. Consider the following code snippet: class A(object): def call_bar(self): return self.bar() def call___bar(self): return self.__bar() def __bar(self): return "A::__bar()" def bar(self): return "A::bar()" class B(A): def __bar(self): return "B::__bar()" def bar(self): return "B::bar()" b = B() print "calling B::call_bar():", b.call_bar() print "calling B::call___bar():", b.call___bar() The result is: calling B::call_bar(): B::bar() calling B::call___bar(): A::__bar() In the latter case, it calls the base class' implementation. It probably goes along with Python's spec, but I found it surprising. I don't want to expose the __bar() function outside, but on the other hand i want to defer its implementation to a subclass. It seems like I need to make it public, doesn't it? From numeralblue at gmail.com Sun Jul 8 15:25:02 2007 From: numeralblue at gmail.com (numeralblue at gmail.com) Date: Sun, 08 Jul 2007 19:25:02 -0000 Subject: Validating XML in Windows In-Reply-To: References: Message-ID: <1183922702.368213.27460@n60g2000hse.googlegroups.com> On Jul 8, 10:01 am, Omari Norman wrote: > My app needs to validate XML. That's easy enough in Unix. What is the > best way to do it in Windows? > > The most obvious choice would of course be PyXML. However, apparently it > is no longer maintained: > > http://sourceforge.net/project/showfiles.php?group_id=6473 I use the xmlproc parser that is included in PyXML. It is pure Python so as a temporary solution it is easy to include it with my source. I haven't had problems with it yet even though it is dated as you mentioned. --Miguel From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 13 03:19:32 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 13 Jul 2007 09:19:32 +0200 Subject: Function parameter type safety? In-Reply-To: <1184277163.803229.318660@g4g2000hsf.googlegroups.com> References: <1184277163.803229.318660@g4g2000hsf.googlegroups.com> Message-ID: <4697275c$0$15029$426a74cc@news.free.fr> Robert Dailey a ?crit : > Hi, > > Is there a way to force a specific parameter in a function to be a > specific type? No, and that's considered a GoodThing(tm). > For example, say the first parameter in a function of > mine is required to be a string. If the user passes in an integer, I > want to notify them that they should pass in a string, not an integer. > Document the fact that the function expects a string as it's first param. If someone pass an int, it's likely that he'll soon find out there's something wrong (either from an exception or from obviously incoherent results). This is usually enough. If you're in the case that passing a non-string will not raise an exception in the function but just lead to strange results or raise somewhere else, you can eventually use an assertion to ease debugging - but don't get into the habit of systematically type-check functions arguments, this would be fighting against the language. My 2 cents... From anoweb at gmail.com Tue Jul 17 13:29:41 2007 From: anoweb at gmail.com (anoweb) Date: Tue, 17 Jul 2007 17:29:41 -0000 Subject: merge two ranges Message-ID: <1184693381.008061.116840@m37g2000prh.googlegroups.com> I have two ranges of numbers and I need to determine if they overlap or adjacent and if so return a new range containing the values. The values are low and high for each pair, such that the first value of the tuple is always less than or equal to the second value in the tuple. for example: a = (0, 5) b = (5, 10) print getAdjacent(a, b) # output: (0, 10) print getAdjacent(b, a) # output: (0, 10) print getOverlap(a, b) # output: None print getOverlap(b, a) # output: None a = (0, 7) b = (3, 10) print getAdjacent(a, b) # output: None print getAdjacent(b, a) # output: None print getOverlap(a, b) # output: (0, 10) print getOverlap(b, a) # output: (0, 10) a = (0, 90) b = (5, 10) print getAdjacent(a, b) # output: None print getAdjacent(b, a) # output: None print getOverlap(a, b) # output: (0, 90) print getOverlap(b, a) # output: (0, 90) a = (0, 5) b = (12, 20) print getAdjacent(a, b) # output: None print getAdjacent(b, a) # output: None print getOverlap(a, b) # output:None print getOverlap(b, a) # output: None any easy way of doing this? From steve at holdenweb.com Wed Jul 4 08:43:45 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Jul 2007 08:43:45 -0400 Subject: what is wrong with that r"\" In-Reply-To: <61910.22236.qm@web50105.mail.re2.yahoo.com> References: <61910.22236.qm@web50105.mail.re2.yahoo.com> Message-ID: Matthieu TC wrote: > May I suggest giving the possibility to use any delimiter for a raw string? just like in Vi or ruby. > Of course you may. Thank you for your suggestion. Now, on to other business. 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 Sat Jul 14 23:30:59 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sun, 15 Jul 2007 00:30:59 -0300 Subject: CSV without first line? Message-ID: <9e2f512b0707142030if7cd91ay53f82924e3c686eb@mail.gmail.com> Hi, In my CSV file, the first line has the name of the variables. So the data I want to parse resides from line 2 up to the end. Here is what I do: import csv lines=csv.reader(open("MYFILE")) lines.next() #this is just to avoid the first line for line in lines: DATA PARSING This works fine. But I don't like to do "lines.next()" just to get rid of the first line. So I wonder if the reader function on the csv module has something that could let me parse the file from the second line (w/o doing that lines.next()). -- Sebasti?n Bassi (???????) Diplomado en Ciencia y Tecnolog?a. GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D From AArlinghaus at Volt.com Thu Jul 26 13:24:17 2007 From: AArlinghaus at Volt.com (Arlinghaus, Andrea) Date: Thu, 26 Jul 2007 10:24:17 -0700 Subject: Cincinnati PUG Message-ID: Hello! I am a recruiter in the area and I am currently looking to fill a Python opportunity. I was wondering if you or anyone you might know would be interested in a job opportunity OR if I could possibly give you the job description to post. I would be happy to give you more information and answer any questions. I look forward to hearing from you. Thanks so much! Andrea Arlinghaus Technical Recruiter Volt Workforce Solutions 8044 Montgomery Road, Suite 630 | Cincinnati, Oh 45236 aarlinghaus at volt.com| t: 513-791-2600| f: 513-791-4292 -------------- next part -------------- An HTML attachment was scrubbed... URL: From mail at microcorp.co.za Sat Jul 21 02:28:30 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 21 Jul 2007 08:28:30 +0200 Subject: Pickled objects over the network References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com><011401c7caa0$3e3e5900$03000080@hendrik> Message-ID: <012901c7cb60$5ba530c0$03000080@hendrik> "Steve Holden" wrote: > Hmm, I suspect I detect the sounds of the square wheel being reinvented. Very helpful, thank you, Steve - Now how about pointing out in which direction the round wheels are kept, and what their monikers are? - Hendrik From miki.tebeka at gmail.com Fri Jul 20 16:34:34 2007 From: miki.tebeka at gmail.com (Miki) Date: Fri, 20 Jul 2007 20:34:34 -0000 Subject: code packaging In-Reply-To: <7xfy3jpem8.fsf_-_@ruckus.brouhaha.com> References: <7xfy3jpem8.fsf_-_@ruckus.brouhaha.com> Message-ID: <1184963674.333306.231180@j4g2000prf.googlegroups.com> Hello Paul, > I'm now wondering where this type of thing is best addressed in more > general terms. What I usually see happening, in projects I've worked > on and in others, is that developers get the code working on their own > computers, using source control tools and (if we're lucky) tests > developed in parallel with the code, but without much attention to > final packaging until the very end when the code is about to be > shipped. [snipped] IMO you should invest the time a build automated packaging and some smoke tests for the product. After this is done, start using some "continuous automation" tools (like http://cruisecontrol.sourceforge.net/, http://buildbot.net/trac and others). HTH, -- Miki http://pythonwise.blogspot.com From timr at probo.com Fri Jul 6 01:20:10 2007 From: timr at probo.com (Tim Roberts) Date: Fri, 06 Jul 2007 05:20:10 GMT Subject: what is wrong with that r"\" References: Message-ID: <27kr83lv67n38fmirvs5vvh5f80cr27joi@4ax.com> Matthieu TC wrote: >May I suggest giving the possibility to use any delimiter for a raw string? just like in Vi or ruby. > >Vi: > %s_a_b_g is valid and so is %s/a/b/g > >Ruby: > %q{dj'\ks'a\'"} or %q-dj'\ks'a\'"- > >So as long as your regex does not use all the valid characters, readability is maintained. But what about my program that wants to use r_a_b_ as an identifier? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From steve at holdenweb.com Mon Jul 9 14:56:02 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 09 Jul 2007 14:56:02 -0400 Subject: Python's "only one way to do it" philosophy isn't good? In-Reply-To: References: <9uRhi.17027$xk5.14289@edtnps82> Message-ID: Douglas Alan wrote: > "Chris Mellon" writes: [...] >> The Python language reference explicitly does *not* guarantee the >> behavior of the refcounter. > > Are you suggesting that it is likely to change? If so, I think you > will find a huge uproar about it. > >> By relying on it, you are relying on an implementation specific, >> non-specified behavior. > > I'm relying on a feature that has worked fine since the early '90s, > and if it is ever changed in the future, I'm sure that plenty of other > language changes will come along with it that will make adapting code > that relies on this feature to be the least of my porting worries. > Damn, it seems to be broken on my Jython/IronPython installations, maybe I should complain. Oh no, I can't, because it *isn't* *part* *of* *the* *language*. ... >> Exactly like you'd be doing if you rely on the value of >> uninitialized variables in C. > > Exactly like I'd be doing if I made Unix system calls in my C code. > After all, system calls are implementation dependent, aren't they? > That doesn't mean that I don't rely on them every day. > That depends on whether you program to a specific standard or not. >>> There are languages other than C that guarantee that values are >>> initialized in certain ways. Are you going to also assert that in >>> those languages you should not rely on the initialization rules? > >> Of course not. Because they *do* guarantee and specify that. C >> doesn't, and neither does Python. > > CPython does by tradition *and* by popular will. > But you make the mistake of assuming that Python is CPython, which it isn't. > Also the language reference manual specifically indicates that CPython > uses a refcounter and documents that it collects objects as soon as > they become unreachable (with the appropriate caveats about circular > references, tracing, debugging, and stored tracebacks). > Indeed, but that *is* implementation dependent. As long as you stick to CPython you'll be fine. That's allowed. Just be careful about the discussions you get into :-) 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 Jul 19 11:32:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Jul 2007 11:32:41 -0400 Subject: odbc module for python In-Reply-To: <1184816453.519242.187940@g12g2000prg.googlegroups.com> References: <1184816453.519242.187940@g12g2000prg.googlegroups.com> Message-ID: Sean Davis wrote: > What are the alternatives for accessing an ODBC source from python > (linux 64-bit, python 2.5)? It looks like mxODBC is the only one > available? > There is, I understand, a pyodbc module as well. Having never used it I can't say how good it is. 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 jayloden.com Sat Jul 14 12:25:37 2007 From: python at jayloden.com (Jay Loden) Date: Sat, 14 Jul 2007 12:25:37 -0400 Subject: pattern match ! In-Reply-To: <1184428068.894263.41560@22g2000hsm.googlegroups.com> References: <1184125206.034047.175340@n60g2000hse.googlegroups.com> <4694BF24.1050706@igpm.rwth-aachen.de> <1184428068.894263.41560@22g2000hsm.googlegroups.com> Message-ID: <4698F901.2000500@jayloden.com> hari.siri74 at gmail.com wrote: >> A slightly more generic match in case your package names turn out to be less consistent than given in the test cases: >> >> #!/usr/bin/python >> >> import re >> pattern = re.compile(r'(\w+?-(\d+[\.-])+\d+?)-\D+.*RPM') >> pkgnames = ["hpsmh-1.1.1.2-0-RHEL3-Linux.RPM", "hpsmh-1.1.1.2-RHEL3-Linux.RPM"] >> for pkg in pkgnames: >> matchObj = pattern.search(pkg) >> if matchObj: >> print matchObj.group(1) >> >> Still assumes it will end in RPM (all caps), but if you add the flag "re.I" to the re.compile() call, it will match case-insensitive. >> >> Hope that helps, >> >> -Jay > > How about if i had something like 1-3 words in the application name: > websphere-pk543-1.1.4.2-1-RHEL3-i386.rpm (in this case are 2 words)? Try this instead then: #!/usr/bin/python import re pattern = re.compile(r'((\w+?-)+?(\d+[\.-])+\d+?)-\D+.*RPM', re.I) pkgnames = ["hpsmh-1.1.1.2-0-RHEL3-Linux.RPM", "hpsmh-1.1.1.2-RHEL3-Linux.RPM", "websphere-pk543-1.1.4.2-1-RHEL3-i386.rpm"] for pkg in pkgnames: matchObj = pattern.search(pkg) if matchObj: print matchObj.group(1) From Afro.Systems at gmail.com Fri Jul 13 06:38:01 2007 From: Afro.Systems at gmail.com (Tzury) Date: Fri, 13 Jul 2007 10:38:01 -0000 Subject: MaildirMessage In-Reply-To: <874pk8kedo.fsf@benfinney.id.au> References: <1184287592.509355.310110@g4g2000hsf.googlegroups.com> <874pk8kedo.fsf@benfinney.id.au> Message-ID: <1184323081.806809.160380@m3g2000hsh.googlegroups.com> > Which is a bug in the 'email.message' module, in my view. If it's > attempting to support a mapping protocol, it should allow iteration > the same way standard Python mappings do: by iterating over the keys. I thought it is a bug as well, but who am I a python newbie to say so. I found inspect.getmembers(msg) as a good solution to map the message properties. 10x, Tzury From vedrandekovic at v-programs.com Wed Jul 25 14:22:03 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Wed, 25 Jul 2007 11:22:03 -0700 Subject: code indentation In-Reply-To: References: <1185297657.186852.136950@k79g2000hse.googlegroups.com> <87lkd5jt83.fsf@benfinney.id.au> <1185357861.989194.117000@r34g2000hsd.googlegroups.com> Message-ID: <1185387723.155661.311510@b79g2000hse.googlegroups.com> On 25 srp, 17:31, Wildemar Wildenburger wrote: > vedrandeko... at v-programs.com wrote: > >> And while we're on the topic of communication: The original poster > >> would do well to learn that increasing the number of consecutive > >> punctuation marks (!!!, ???) is a sure way to turn away many people > >> who would otherwise be helpful. Sentences need at most one '!' or '?', > >> adding more does not improve the chances of being taken seriously. > > > And if you can help me than please help me , but if you can't then > > please don't leave me some stupid messages > > Whats stupid about this? It's sane advice. > > Which looks more serious to you: > > this: > I can't do it!!!! Can you PLEASE help me????!!!?! > > or this: > I don't know the answer. Can you please help me? > > Even if it makes no difference to you, to many people it does. So Ben is > right: People *will* take your posts more seriously if you restrict your > use of punctuation (if only because its easier to read). > Don't feel offended, nobody was trying to put you down. > > /W HELLO, On this group I ask for serious help and now we talk about communication. Then I you don't know how to help me then please DON'T SAY ANYTHING Regards, Vedran From steve at holdenweb.com Fri Jul 6 06:42:08 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Jul 2007 06:42:08 -0400 Subject: SMTP server w/o using Twisted framework In-Reply-To: <5f68a6F3adj19U1@mid.uni-berlin.de> References: <1183661809.613856.312100@57g2000hsv.googlegroups.com> <1183664445.020890.226520@c77g2000hse.googlegroups.com> <5f68a6F3adj19U1@mid.uni-berlin.de> Message-ID: <468E1C80.7030308@holdenweb.com> Gerhard H?ring wrote: > _spitFIRE wrote: >> [looking up DNS MX records] >> Thanks for the pointer. However, as I said currently, I can't use >> anything other than the standard libraries. > > Sure you can. You just need to get rid of the "only standard library" > requirement rule. > > That works best by showing the alternatives to whoever set that requirement: > > - use pyDNS > - use an existing (probably non-Python) SMTP daemon > - reimplement some parts of pyDNS yourself and develop a basic (crappy) > SMTP daemon yourself > > For doing the latter, you should budget at least one week. > > FWIW another reason why SMTP servers should retry on temporary failure > is that increasing use of Greylisting (*), which was precisely designed > to filter out mail from "crappy" servers, like botnets, and - well - > cheap custom written ones ;-) > I'd actually use dnspython in preference to pyDNS, it's very easy to use. I have some MX-server lookup code somewhere in the vault, if you can use an external library. 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 nytrokiss at gmail.com Sun Jul 8 15:21:38 2007 From: nytrokiss at gmail.com (James Matthews) Date: Sun, 8 Jul 2007 12:21:38 -0700 Subject: Changing the user-agent in urllib Message-ID: <8a6b8e350707081221k6d010246t832e6d6f9c9235a@mail.gmail.com> Is there anyway of changing the user-agent in urllib without sub classing it? -- http://www.goldwatches.com/watches.asp?Brand=14 http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From kay.schluehr at gmx.net Tue Jul 17 00:51:47 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: Mon, 16 Jul 2007 21:51:47 -0700 Subject: In a dynamic language, why % operator asks user for type info? In-Reply-To: <1184631007.920803.147790@j4g2000prf.googlegroups.com> References: <1184631007.920803.147790@j4g2000prf.googlegroups.com> Message-ID: <1184647907.339213.284330@22g2000hsm.googlegroups.com> On Jul 17, 3:10 am, Karthik Gurusamy wrote: > output = '%d foo %d bar" % (foo_count, bar_count), > why we need to use %d? I'm thinking some general common placeholder, > say %x (currently it's hex..) could be used. You already answered it in the parenthesized remark: the %d placeholder is not only type bound but provides an additonal distinction e.g. the one between decimals and hexadecimals. The kind of general placeholder you want %x being requested for is actually %s which formats decimals quite well unless you want leading zeros. From crcarleRemoveThis at BOGUSsandia.gov Fri Jul 13 12:41:39 2007 From: crcarleRemoveThis at BOGUSsandia.gov (Chris Carlen) Date: Fri, 13 Jul 2007 09:41:39 -0700 Subject: Understanding python functions - Instant Python tutorial In-Reply-To: <878x9kkeif.fsf@benfinney.id.au> References: <878x9kkeif.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Chris Carlen writes: > > def change(some_list): > some_list[1] = 4 > > x = [1,2,3] > change(x) > print x # Prints out [1,4,3] > --- > def nochange(x): > x = 0 > > y = 1 > nochange(y) > print y # Prints out 1 > >>I don't understand Hetland's terminology though, when he is speaking >>of "binding" and "reference." Actually, Hetland's entire first >>paragraph is unclear. >> >>Can anyone reword this in a way that is understandable? > > I've had some success with the following way of thinking about it. > > Some languages have "variables", which act like boxes that have names > etched on the side. Once created, the box can contain an object, and > it can be inspected while in the box; to change the variable, you > throw out the object and put a different object in the same box. Yes, so y = x takes a copy of the stuff in the x box and puts it in the y box. Which is what really happens in the hardware. > That's not how Python works. Every value is an object; the assignment > operator binds a name to an object. This is more like writing the name > on a sticky-note, and sticking it onto the object. > > * The object itself doesn't change or "move". > > * The object can be referred to by that name, but isn't "inside" the > name in any way. > > * Assigning multiple names to the same object just means you can > refer to that same object by all those names. > > * When a name goes away, the object still exists -- but it can't be > referred to if there are no longer any names left on it. > > * Assigning a different object to an existing name just means that > the same sticky-note has moved from the original object to the new > one. Referring to the same name now references a different object, > while the existing object keeps all the other names it had. Excellent description. This understandable to me since I can envision doing this with pointers. But I have no idea how Python actually implements this. It also appears that I am being guided away from thinking about it in terms of internal implementation. > When you pass an object as a parameter to a function, the object > receives a new sticky-label: the parameter name under which it was > received into the function scope. Assignment is an act of binding a > name to an object; no new object is created, and it still has all the > other names it had before. Ok, so I can understand the code above now. In the first case I pass the reference to the list to change(). In the function, some_list is another name referring to the actual object [1,2,3]. Then the function changes the object referred to by the second element of the list to be a 4 instead of a 2. (Oh, the concept applies here too!) Out of the function, the name x refers to the list which has been changed. In the second case, y refers to a '1' object and when the function is called the object 1 now gets a new reference (name) x inside the function. But then a new object '0' is assigned to the x name. But the y name still refers to a '1'. I get it. But I don't like it. Yet. Not sure how this will grow on me. > When the function ends, all the names that were created inside that > function's scope disappear; but the objects still exist under any > names they had previously, and if you use those names you'll be > looking at the same object as was manipulated inside the function. > > When the object has lost all its names -- for example, they've > disappeared because the scope they were in has closed, or they've been > re-bound to other objects -- they can no longer be referenced. At some > point after that, the automatic garbage collection will clean that > object out of memory. > > This sticky-note analogy, and the behaviour described, is what is > meant by "references". A name refers to an object; changing the object > means that by referring to that same object under its different names, > you will see the same, modified, object. > > In Python, all names are references to objects. The assignment > operator '=' doesn't create or change a "variable"; instead, it binds > a name as reference to an object. All functions receive their > parameters as the existing object with a new name -- a reference to > that object, just like any other name. > > Hope that helps. A great deal of help, thanks. Excellent explanation. Wow. This is strange. A part of me wants to run and hide under the nearest 8-bit microcontroller. But I will continue learning Python. -- Good day! ________________________________________ Christopher R. Carlen Principal Laser&Electronics Technologist Sandia National Laboratories CA USA crcarleRemoveThis at BOGUSsandia.gov NOTE, delete texts: "RemoveThis" and "BOGUS" from email address to reply. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jul 12 04:53:59 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 12 Jul 2007 10:53:59 +0200 Subject: Anonymous Classes In-Reply-To: <139bkaf7m30iu49@corp.supernews.com> References: <139bkaf7m30iu49@corp.supernews.com> Message-ID: <4695ec04$0$8947$426a74cc@news.free.fr> Lachlan Gunn a ?crit : > Hello. > > I have a library (SQLObject) that stores data as class variables. I would > like to set a class variable in a certain context, specific to a certain > instance of an object. This would require some sort of anonymous class. I > have attempted to use the following code to set the connection string: > > | class SQLStorage: You probably want: class SQLStorage(object): > | def __init__(self, c, debug = False): > | config = StorageConfiguration(c) > | > | connection = sqlobject.connectionForURI(config.databaseString) > | if debug: > | connection.debug = True > | > | # I don't know whether this is right. My belief is that we can > | # subclass each table and use _connection on them. > | class newDatum(DatumTable): > | _connection = connection > | > | class newMetadatum(MetadatumTable): > | _connection = connection > | > | class newChecksum(ChecksumTable): > | _connection = connection > | > | self.__SQLDatum = newDatum > | self.__SQLMetadatum = newMetadatum > | self.__SQLChecksum = newChecksum Are you sure you need name mangling here ? > This does not work; Python complains that the classes already exist when > SQLObject is instantiated for a second time. This has led me to try > instantiating a subclass using DatumTable.__class__ and friends, but this > requires setting a class name, which, again, limits me to a single > instance. I *could* have a counter that appends a number to each class > name, but that's a fairly ugly solution; is it possible to create an > anonymous class in Python? Yes. Using type() : Help on class type in module __builtin__: class type(object) | type(object) -> the object's type | type(name, bases, dict) -> a new type >>> class Toto(object): ... pass ... >>> class Tutu(object): ... def __init__(self, what): ... self._toto = type('Autototo', (Toto,), dict(_what=what)) ... >>> t = Tutu(42) >>> t._toto >>> t._toto._what 42 >>> t._toto() <__main__.Autototo object at 0xb7c3806c> >>> t2 = Tutu(1138) >>> t2._toto >>> t2._toto._what 1138 From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Jul 26 09:10:25 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 26 Jul 2007 15:10:25 +0200 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185453726.559470.122480@x40g2000prg.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> <46a7b908$0$32130$426a34cc@news.free.fr> <1185453726.559470.122480@x40g2000prg.googlegroups.com> Message-ID: <46a89d2d$0$17815$426a74cc@news.free.fr> walterbyrd a ?crit : > On Jul 22, 12:17 am, Bruno Desthuilliers > wrote: > >> Either you are a casual user with 101 web >> development skills trying to set up your personal home page > > But this, sort of, brings me back to my original point. Nobody starts > out being advanced. Nope. But some start out being already seasoned programmers, even if they never done web development !-) > There are substantial differences in cost, and > deployment, between PHP and Python. Depends on the context. But true, it's easier to get PHP than Python on a budget shared hosting (except possibly for python cgi). > It is much easier to get started > with PHP. If you are not programmer and don't know anything about the HTTP protocol, yes, indeed. > And once somebody has started with PHP, that person is > likely to stay with PHP. FWIW, I started web programming with PHP. Then I quickly started to look for Python-based solutions. > Most PHP developers do not see a compelling > reason to start all over again with Python. If I judge by the average quality of the php code I've seen so far - and I've seen quite a lot - most "PHP developers" don't know zilch about both programming and the web. The others are usually not "PHP developers" but developers using PHP - which is not exactly the same thing. There are, of course, well-designed, well-written php apps, but that's certainly not the most common case. > BTW: I have a certain amount of respect for PHP, I don't. > and PHP developers. That's another problem. > PHP5 is a big step forward over PHP4. Because it introduced a Java-like object model ? > And, there have been substantial > web projects completed with PHP Indeed. As well as with Java and Perl. A good programmer is usually able to write good code whatever the language. > - probably more so than with Python. There certainly are more "substantial" web projects written in Java than in Python, and believe me, deploying a Java web app is orders of magnitude more difficult and costly than with a Python one, whatever the Python framework used. Heck, compared to any Java solution, even Zope looks lightweight and agile. From frank at chagford.com Mon Jul 23 01:10:31 2007 From: frank at chagford.com (Frank Millman) Date: Sun, 22 Jul 2007 22:10:31 -0700 Subject: Advice on sending images to clients over network In-Reply-To: <1185095666.627415.108450@w3g2000hsg.googlegroups.com> References: <1185095666.627415.108450@w3g2000hsg.googlegroups.com> Message-ID: <1185167431.527584.66330@22g2000hsm.googlegroups.com> Frank Millman wrote: > Hi all > > This is not strictly a Python question, but as the system to which > relates is written in Python, hopefully it is not too off-topic. > [...] > I now want to add the capability of displaying images on the client. > For example, if the application deals with properties, I want to > display various photographs of the property on the client. wxPython is > perfectly capable of displaying the image. My question is, what is the > best way to get the image to the client? > Thanks for all the responses. The verdict seems unanimous - use http. Thanks for pointing me in the right direction. Frank From wildemar at freakmail.de Wed Jul 18 09:36:37 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Wed, 18 Jul 2007 15:36:37 +0200 Subject: Charlotte Python Group In-Reply-To: <76fd5acf0707180544y497bfd42t6b699b8f62b6b4e5@mail.gmail.com> References: <76fd5acf0707180544y497bfd42t6b699b8f62b6b4e5@mail.gmail.com> Message-ID: <469E1765.1010801@freakmail.de> Calvin Spealman wrote: > I am looking to start a meetup in or near Charlotte. I already have a > couple people interested, and I see some folks subscribing to new > python groups on meetup. If I can find a few more people, it could be > worth it. > > Is anyone in the area and interested in a group? Anyone who might want > to do a talk, about anything interesting? Does anyone have suggestions > of a good place in Charlotte to meet, maybe at a cafe with enough > room? I'm from up in the Kannapolis/Concord area myself, so I'm not > familiar with many places in the city proper, but I see a few > possibilities at Google Maps. > > Hey, can you get a little less specific, please? I can just about make out what place you're talking about. This one , right? /W (your personal know-nothing nitpicker) From noreply at python.org Mon Jul 23 06:47:19 2007 From: noreply at python.org (Post Office) Date: Mon, 23 Jul 2007 12:47:19 +0200 Subject: Returned mail: Data format error Message-ID: <200707230939.l6N9de4C027973@mbox.infotel.bg> ----Virus Warning Message (from InterScanVirusWall mbox.infotel.bg) Found virus WORM_MYDOOM.GEN in file DOCUMENT.SCR (in document.zip) The uncleanable file is deleted. If you have questions, contact administrator. --------------------------------------------------------- -------------- next part -------------- The original message was received at Mon, 23 Jul 2007 12:47:19 +0200 from python.org [74.255.151.9] ----- The following addresses had permanent fatal errors ----- -------------- next part -------------- ----Virus Warning Message (from InterScanVirusWall mbox.infotel.bg) document.zip is removed from here because it contains a virus. --------------------------------------------------------- From gregpinero at gmail.com Wed Jul 4 16:00:07 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: Wed, 04 Jul 2007 20:00:07 -0000 Subject: Find This Module Message-ID: <1183579207.226611.192520@57g2000hsv.googlegroups.com> I'm looking at the source for the module sre_compile.py and it does this import: import _sre But I can't find a file related to _sre anywhere. Where is it? And more generally, how does one find the location of a built in module? Thanks, Greg From bignose+hates-spam at benfinney.id.au Sat Jul 28 08:00:03 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 28 Jul 2007 22:00:03 +1000 Subject: Relative-importing * References: <1185559874.299008.167010@x40g2000prg.googlegroups.com> <871weth2gg.fsf@benfinney.id.au> <7xsl79uhm7.fsf@ruckus.brouhaha.com> Message-ID: <87ejisg2m4.fsf@benfinney.id.au> Paul Rubin writes: > Steven D'Aprano writes: > > I read "from module import *" as explicitly saying "clobber the > > current namespace with whatever names module exports". That's what > > from does: it imports names into the current namespace. It isn't > > some sort of easy to miss side-effect. If a name already existed, > > it gets clobbered, just like any other import: > > Seems to me that there should be a compiler warning when this > happens. The import happens at run-time. The compiler can't catch it. -- \ "I stayed up all night playing poker with tarot cards. I got a | `\ full house and four people died." -- Steven Wright | _o__) | Ben Finney From trentm at activestate.com Tue Jul 3 14:56:08 2007 From: trentm at activestate.com (Trent Mick) Date: Tue, 03 Jul 2007 11:56:08 -0700 Subject: what is the PythonWin In-Reply-To: <9Lcii.2986$Od7.2957@newsread1.news.pas.earthlink.net> References: <1183330410.164963.151790@c77g2000hse.googlegroups.com> <9Lcii.2986$Od7.2957@newsread1.news.pas.earthlink.net> Message-ID: <468A9BC8.3010103@activestate.com> Dennis Lee Bieber wrote: > PythonWin is (or was) part of the win32 extension library for > Python. It is a separate download -- unless you downloaded the > ActiveState Windows build of Python. The ActiveState build includes the > win32 libraries and "PythonWin" (but lacks a few of the, otherwise > standard, encryption stuff -- which can be copied from a comparable > [version-wise] python.org release). Note that it is no longer true that ActivePython does not include the standard encryption stuff (namely OpenSSL support for the socket module and the hashlib libraries). As of ActivePython 2.5.0.0 full SSL support is available. Cheers, Trent -- Trent Mick trentm at activestate.com From martin at v.loewis.de Fri Jul 20 17:43:36 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 20 Jul 2007 23:43:36 +0200 Subject: Interpreting os.lstat() In-Reply-To: References: <1184806559.224636.266500@e9g2000prf.googlegroups.com> <46a057e8$0$19051$9b622d9e@news.freenet.de> Message-ID: <46A12C88.7070403@v.loewis.de> > But it obviously does a lot of other stuff, including formatting > the results of the system call for display. It most decisively does *not* format the results of the system call "for display". Instead, it converts the C data type holding the stat result into a Python data type. That data type historically was a tuple, but now is struct-like type with the same fields as the C data type. It's the same as saying "+ does not do addition. It does a lot of other stuff, including the formatting of the result of the operation for display". > Since what it really > at issue here is presentation of the results, I'd say that the > stat system call and the stat program wrapping it are very > different things. This is probably a matter of opinion. I think it is important to understand that Python does *not* do any significant code to os.stat and os.lstat; entirely unlike libraries in other languages that attempt to also change the programming API in the process of wrapping the system API. Regards, Martin From star.public at gmail.com Wed Jul 11 12:50:10 2007 From: star.public at gmail.com (star.public at gmail.com) Date: Wed, 11 Jul 2007 16:50:10 -0000 Subject: wxPython vs. Tkinter event loops In-Reply-To: References: <392e8$4694ee0a$4275d90a$27942@FUSE.NET> Message-ID: <1184172610.044256.288400@n60g2000hse.googlegroups.com> On Jul 11, 11:17 am, "Chris Mellon" wrote: > No again. wxPython provides a Process class for executing external > applications and providing events in response to input, app exit, and > similar. You can also implement it in a similar way to your Tkinter > implementation, but backwards - poll the pipe repeatedly using > wx.CallAfter or wx.CallLater calls. You can also set up a callback on the idle event and do a little processing every time it's called, though that can be odd because it tends to e.g. update more often when the mouse is moving over the window and such. There may be other ways, too, I don't have access to my docs or the demo here (just poked my head in because I'm waiting for my work program to stop being frozen ...). -Weaver From alexandre.ferrieux at gmail.com Sun Jul 22 12:10:50 2007 From: alexandre.ferrieux at gmail.com (Alexandre Ferrieux) Date: Sun, 22 Jul 2007 09:10:50 -0700 Subject: Lazy "for line in f" ? Message-ID: <1185120650.412694.314280@o61g2000hsh.googlegroups.com> Hi, I'm a total newbie in Python, but did give quite a try to the documentation before coming here. Sorry if I missed the obvious. The Tutorial says about the "for line in f" idiom that it is "space- efficient". Short of further explanation, I interpret this as "doesn't read the whole file before spitting out lines". In other words, I would say "lazy". Which would be a Good Thing, a much nicer idiom than the usual while loop calling readline()... But when I use it on the standard input, be it the tty or a pipe, it seems to wait for EOF before yielding the first line. So, is it lazy or not ? Is there some external condition that may trigger one behavior or the other ? If not, why is it said "space efficient" ? TIA, -Alex From jeremy+complangpython at jeremysanders.net Tue Jul 10 06:37:02 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 10 Jul 2007 11:37:02 +0100 Subject: stripping the first byte from a binary file References: <1184063032.195000.25880@i13g2000prf.googlegroups.com> Message-ID: rvr wrote: > Would someone mind showing me how to strip the first byte from a > binary file? For some reason I can't figure this out from the binary > file editing examples I've read. Thanks. Do you mean something like this? f = open('test.dat', 'rb') f.read(1) # read 1st byte and ignore it rest = f.read() # read rest or data = f.read() data = data[1:] # skip 1st byte ? -- Jeremy Sanders http://www.jeremysanders.net/ From exarkun at divmod.com Sun Jul 22 15:37:32 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 22 Jul 2007 15:37:32 -0400 Subject: split on NO-BREAK SPACE In-Reply-To: Message-ID: <20070722193732.4947.752757075.divmod.quotient.14354@ohm> On Sun, 22 Jul 2007 21:13:02 +0200, Peter Kleiweg wrote: >Carsten Haese schreef op de 22e dag van de hooimaand van het jaar 2007: > >> On Sun, 2007-07-22 at 17:44 +0200, Peter Kleiweg wrote: >> > > It's a feature. See help(str.split): "If sep is not specified or is >> > > None, any whitespace string is a separator." >> > >> > Define "any whitespace". >> >> Any string for which isspace returns True. > >Define white space to isspace() > >> > Why is it different in and ? >> >> >>> '\xa0'.isspace() >> False >> >>> u'\xa0'.isspace() >> True > >Here is another "space": > > >>> u'\uFEFF'.isspace() > False > >isspace() is inconsistent It's only inconsistent if you think it should behave based on the name of a unicode code point. It doesn't use the name, though. It uses the category. NO-BREAK SPACE is in the Zs category (Separator, Space). ZERO WIDTH NO-BREAK SPACE is in the Cf category (Other, Format). Maybe that makes unicode inconsistent (I won't try to argue either way), but it's pretty clear that isspace is being consistent based on the data it has to work with. Jean-Paul From roy at panix.com Fri Jul 27 00:40:11 2007 From: roy at panix.com (Roy Smith) Date: Fri, 27 Jul 2007 00:40:11 -0400 Subject: How to tell when a socket is closed on the other end? References: <1185371863.622473.205010@19g2000hsx.googlegroups.com> Message-ID: Jay Loden wrote: > The goal of this > portion of the test suite we are writing for the project is to determine if a > remote server is behaving properly by closing a socket from the server side > based on a client-side command. > > Really what's needed is a way to make sure the socket gets closed, and > preferably determine if it was closed from the remote end as expected. This really is way out of scope for a Python newsgroup, but what the heck. There is no way to tell through the Socket API *why* the connection was shut down, because this information isn't transmitted by the TCP protocol. All you know is that the connection did indeed get shut down. It could be because the user code at the remote end called close(). Or, it could be because the process exited (normally or abnormally) and the kernel closed the connection as part of the cleanup. All the TCP stack at this end knows is it got a packet with the FIN bit set. If you really want to know if the other end completed normally, you need to design your user-level protocol to include some "end of session" indication. For example: > bash-3.2$ telnet mx.panix.com smtp > Trying 166.84.1.72... > Connected to mx.panix.com. > Escape character is '^]'. > 220 mail1.panix.com ESMTP Postfix > helo foo > 250 mail1.panix.com > quit > 221 Bye > Connection closed by foreign host. The SMTP user-level protocol sent "221 Bye", then, my telnet client saw the actual TCP connection close, and printed the "Connection closed by foreign host" message. I know the remote end closed down the connection normally because I saw the "221" message in response to my "quit" command. > Do you > know if this is possible to determine from the client side > reliably/accurately? Would select()'s exceptional condition flag actually > indicate whether or not the root cause of the condition was a socket closed > by the remote peer? I've read through the select's manpage and I can't seem > to find a reference that indicates what the possible values are for the I/O > descriptor sets returned by select. Is there another man page, or a place in > the header file for select I can look? You need to read up about how TCP/IP works. A good place to start might be the Wikipedia article on "Transmission Control Protocol". The canonical textbook on the subject would be: Richard Stevens UNIX Network Programming, Volume 1, Second Edition: Networking APIs: Sockets and XTI Prentice Hall 1998 ISBN 0-13-490012-X From kw at codebykevin.com Thu Jul 26 08:01:08 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 26 Jul 2007 08:01:08 -0400 Subject: Tix.Tk() on Mac Intel In-Reply-To: References: Message-ID: <46A88D04.7070701@codebykevin.com> Alan wrote: > Hi List! > > I have I Macbook Pro Intel running OSX 10.4.10. > > I downloaded Python 2.5 and tried > TclTkAquaBI-8.4.10.0.dmg, but I got: > > Traceback (most recent call last): > File "", line 1, in > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py", > > line 210, in __init__ > self.tk.eval('package require Tix') > _tkinter.TclError: no suitable image found. Did find: > /Library/Tcl/Tix8.4/libTix8.4.dylib: mach-o, but wrong architecture > > Which make sense since tcltkaqua is released only for PPC. Googling a > bit, since tcltkaqua stopped development, I found they recommended > ActiveTcl, but Tix is not included in the package. > > So removing tcltkaqua and ActiveTcl, when trying Tix.Tk() I got: >>>> Tix.Tk() > Traceback (most recent call last): > File "", line 1, in > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py", > > line 210, in __init__ > self.tk.eval('package require Tix') > _tkinter.TclError: can't find package Tix > > The only way I got Tix.Tk() working so far was using Fink but I want > the nice aqua visual for python. Is there any way of getting it > working? > > I would appreciate any help here. > Many thanks in advance. > Cheers, > Alan You'll need to build Tix yourself from source, and Tix must be built in the same directory as the Tcl/Tk source tree (so you'll at least need to download and untar those source trees). -- Kevin Walzer Code by Kevin http://www.codebykevin.com From kyosohma at gmail.com Sat Jul 14 09:39:18 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Sat, 14 Jul 2007 13:39:18 -0000 Subject: Access Denied while trying to delete file from python script In-Reply-To: <1184402387.265806.322680@z28g2000prd.googlegroups.com> References: <1184402387.265806.322680@z28g2000prd.googlegroups.com> Message-ID: <1184420358.061236.150000@22g2000hsm.googlegroups.com> On Jul 14, 3:39 am, "Viewer T." wrote: > I am trying to write a script that deletes certain files based on > certain criteria. > > What I am trying to do is to automate the process of deleting certain > malware files that disguise themselves as system files and hidden > files. When I use os.remove() after importing the os module is raises > a Windows Error: Access denied probably because the files have > disguised themselves as system files. Is there anway to get adequate > privileges under windows to be able to delete system files from within > a python script. I know it is probably a windows security feature but > is there anyway to gain such privileges. You'll need to use the PyWin32 package (AKA win32all). There's a win32security module. These links might help: http://mail.python.org/pipermail/python-list/2006-February/367441.html http://www.thescripts.com/forum/thread28850.html http://aspn.activestate.com/ASPN/docs/ActivePython/2.5/pywin32/Windows_NT_Files_.2d.2d_Locking.html Sometimes you can beat windows over the head using its own delete commands: os.system('DEL /F /S /Q "%s"' % item) os.system(r'RD /S /Q "%s"' % item) I know there's a cookbook recipe on it, but I can't seem to find it right now. Hopefully this will help you some though. Mike From vasudevram at gmail.com Mon Jul 30 11:03:53 2007 From: vasudevram at gmail.com (vasudevram) Date: Mon, 30 Jul 2007 15:03:53 -0000 Subject: Cross platform Python app deployment In-Reply-To: <5h614lF3j21toU1@mid.uni-berlin.de> References: <46adbbec$0$15210$fa0fcedb@news.zen.co.uk> <5h614lF3j21toU1@mid.uni-berlin.de> Message-ID: <1185807833.776851.98190@z24g2000prh.googlegroups.com> On Jul 30, 4:42 pm, "Diez B. Roggisch" wrote: > Will McGugan wrote: > > Hi, > > > Is there some reference regarding how to package a Python application > > for the various platforms? I'm familiar with Windows deployment - I use > > Py2Exe & InnoSetup - but I would like more information on deploying on > > Mac and Linux. > > On mac, there is py2app that allows to create application-bundles you can > then install. Either including a python interpreter, or using an installed > one. > > Diez You could also try PyInstaller - see http://pyinstaller.hpcf.upr.edu/cgi-bin/trac.cgi The site says it works on Windows, Linux and IRIX, so no Mac ... Vasudev Ram Biz site: http://www.dancingbison.com Blog (on software innovation): http://jugad.livejournal.com PDF creation/construction toolkit: http://sourceforge.net/projects/xtopdf From jstroud at mbi.ucla.edu Wed Jul 18 19:27:48 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 18 Jul 2007 16:27:48 -0700 Subject: Exiting from python shell In-Reply-To: <469e8068$0$8912$88260bb3@free.teranews.com> References: <469e8068$0$8912$88260bb3@free.teranews.com> Message-ID: Tobiah wrote: > For years now, I've been exiting the shell by typing 'exit\n', > being chid by the shell, and then typing ^D. I can't > remember a time that I typed the ^D the first time. Call > me an idiot if you must, but since someone took the trouble > to catch the command 'exit' in a special way, would it have > been so awful to just let it be a way to exit when the shell? > > Thanks, > > Toby > Yes, this would have required a ground-up approach to redesigning the python language, transmuting it to something like a cross between lisp and COBOL and would have rendered it impossible to author with C because of the way C implements pointers--hardcoding in assembly would likely be required. Beyond that, exiting an interpreter is not known in computer science and has been shown impossible by Goedel himself in a series of monographs on the topic. Thus, to exit python via a keyword would require also reformulating mathematics as we know it. Furthermore, such a change would propagate itself, via the observer effect, to the behavior of sub atomic particles via ill-defined quantum-mechanical affects and would likely result in the reversal of the Second Law of Thermodynamics, wherein your refrigerator would end up heating its contents and milk would spontaneously spoil, among other anomalies. For these reasons, you might propose a "quit" keyword. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From dwarnold45 at suddenlink.net Sat Jul 7 14:35:40 2007 From: dwarnold45 at suddenlink.net (David) Date: Sat, 07 Jul 2007 11:35:40 -0700 Subject: Pretty Printing Like Tidy for HTML Message-ID: <1183833340.610662.197060@o11g2000prd.googlegroups.com> All, Is there a pretty printing utility for Python, something like Tidy for HTML? That will change: xp=self.uleft[0]+percentx*(self.xwidth) To: xp = self.uleft[0] + percentx * (self.xwidth) And other formatting issues. From http Wed Jul 25 19:50:44 2007 From: http (Paul Rubin) Date: 25 Jul 2007 16:50:44 -0700 Subject: first, second, etc line of text file References: Message-ID: <7xbqe0kppn.fsf@ruckus.brouhaha.com> "Daniel Nogradi" writes: > A very simple question: I currently use a cumbersome-looking way of > getting the first, second, etc. line of a text file: > > for i, line in enumerate( open( textfile ) ): > if i == 0: > print 'First line is: ' + line > elif i == 1: > print 'Second line is: ' + line > ....... > ....... from itertools import islice first_five_lines = list(islice(open(textfile), 5)) print 'first line is', first_five_lines[0] print 'second line is', first_five_lines[1] ... From arkanes at gmail.com Mon Jul 16 10:23:58 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 16 Jul 2007 09:23:58 -0500 Subject: running a Delphi part from Python ? In-Reply-To: <47dce$469b3a07$d443bb3a$26795@news.speedlinq.nl> References: <889c1$469b275c$d443bb3a$2876@news.speedlinq.nl> <469b2b65$0$21672$426a74cc@news.free.fr> <86c61$469b30d1$d443bb3a$15805@news.speedlinq.nl> <469b3530$0$26995$426a74cc@news.free.fr> <47dce$469b3a07$d443bb3a$26795@news.speedlinq.nl> Message-ID: <4866bea60707160723p5a4cf45dy2437152f3605429a@mail.gmail.com> On 7/16/07, Stef Mientki wrote: > tool69 wrote: > > Stef Mientki a ?crit : > > > >> AFAIK, Scintilla is a code editor. > >> What I need looks more like ms-word, > >> handling lists, tables, images, formulas. > >> > >> thanks, > >> Stef Mientki > > > > > > So you'll need the RichTextCtrl > > > > http://www.wxpython.org/docs/api/wx.richtext.RichTextCtrl-class.html > > > > See a sample in the demo under "Recent Additions". > > Well it's better, > - it has lists > - it has images, but no image editing, > It doesn't have > - drag & drop > - tables, > - formula editing, > - screen capture, > - links > - embedded code > - CSS > - .... > so unfortunately it's not yet sufficient :-( > This goes far beyond the requirement for a rich text editor. You're now talking about rich object integration, which is about 80% of a full featured word processor. You won't find a cross platform implementation that's suitable for use as a component in anything. Delphi components are tightly tied to the Delphi runtime environment and its' gui abstractions, so embedding it as is is will be a massive hack (and require extensive C code) if its even possible. However, any company who writes such a full featured control is likely to package it as an ActiveX control so they can get the sales from the VB guys, and you can embed ActiveX control in wxPython applications (Windows only, of course). From tedpottel at gmail.com Sat Jul 7 08:41:59 2007 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Sat, 07 Jul 2007 05:41:59 -0700 Subject: having problems in changing directories doing ftp in python Message-ID: <1183812119.335649.292470@w3g2000hsg.googlegroups.com> Hi, I'm trying to write a ftp in python to send files to my webserverr. Curtly I will change the directory to the folder name, down load the file, then do a chnag dir ..\ to go back to the root diretory, chnag the directory, save the file, do a ../. Instad of going back one directory by doing ..\, could I just go to the root directory? Currtly I get a error saying file does not exist. When I log onto my server using my ftp program, The current path reads /home/admin/ I change the directory to mainwebsite_html. The line that tells you the current directory now reads VAR/WWW/HTML. When I use python, I 1. change the directory to mainwebsite_html 2. change the directory to ted 3. try to go back by changing the directory to "var/www/html" in which I get an error saying it does not exist. When changing a directory in ftp must it be relative?? Help!!!! From nagle at animats.com Wed Jul 11 12:57:56 2007 From: nagle at animats.com (John Nagle) Date: Wed, 11 Jul 2007 09:57:56 -0700 Subject: Problem with Python's "robots.txt" file parser in module robotparser Message-ID: <0T7li.5316$rL1.2716@newssvr19.news.prodigy.net> Python's "robots.txt" file parser may be misinterpreting a special case. Given a robots.txt file like this: User-agent: * Disallow: // Disallow: /account/registration Disallow: /account/mypro Disallow: /account/myint ... the python library "robotparser.RobotFileParser()" considers all pages of the site to be disallowed. Apparently "Disallow: //" is being interpreted as "Disallow: /". Even the home page of the site is locked out. This may be incorrect. This is the robots.txt file for "http://ibm.com". Some IBM operating systems recognize filenames starting with "//" as a special case like a network root, so they may be trying to handle some problem like that. The spec for "robots.txt", at http://www.robotstxt.org/wc/norobots.html says "Disallow: The value of this field specifies a partial URL that is not to be visited. This can be a full path, or a partial path; any URL that starts with this value will not be retrieved." That suggests that "//" should only disallow paths beginning with "//". John Nagle SiteTruth From jdobson at laika.com Mon Jul 23 16:33:22 2007 From: jdobson at laika.com (Jon Dobson) Date: Mon, 23 Jul 2007 13:33:22 -0700 (PDT) Subject: sys.ps1 with formatting (linux) Message-ID: <25433392.55821185222802061.JavaMail.root@zimbra01.laika.com> I'm trying to set sys.ps1 and sys.ps2 with some formatting (linux) using: python -i -c 'import sys; sys.ps1="\033[1m\033[32mspy>\033[0m";sys.ps2="\033[1m\033[32m .\033[0m"' I get the colored prompt(s) as you might expect, but I'm getting some strange behavior with wrapping. Once the interactive command gets long enough to wrap, it wraps back to the same line (overwriting the beginning). It doesn't break anything - the command gets interpreted correctly, it's just an ugly way to work. What's even "cooler" is when I middle-mouse-paste a command and then try to edit the line, it moves up one line in the shell and prints the command I'm editing (minus the character I just deleted). Once again, it's just a display issue - the commands still work. I realize this is pretty obscure, but I'm just hoping someone else has seen and dealt with something like this... tx _____________________________________________________________________ The information contained in this message and its attachments is confidential and proprietary to LAIKA, Inc. By opening this email or any of its attachments, you agree to keep all such information confidential and not to use, distribute, disclose or copy any part of such information without the prior written consent of LAIKA, Inc. If you are not the intended recipient of this message, any use, distribution, disclosure or copying of such information is prohibited. If received in error, please contact the sender. From martin at v.loewis.de Sun Jul 22 05:03:08 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 22 Jul 2007 11:03:08 +0200 Subject: Sorting dict keys In-Reply-To: <1185007449.179903.5480@w3g2000hsg.googlegroups.com> References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> <1185007449.179903.5480@w3g2000hsg.googlegroups.com> Message-ID: <46a31d3f$0$15059$9b622d9e@news.freenet.de> > I'd like to do it in one line because what I am trying to do is, after > all, a single, simple enough action. I find the suggested > b = sorted(a.keys()) much more readable than breaking it up in two > lines. I think you have demonstrated that a single-line statements with multiple functions and methods is *not* more readable for you, contrary to your own beliefs. You were aware that sort is "in-place", and recognized that b = d.keys().sort() does not "work". What you here failed to recognize is that b is assigned the result of .sort(), not the result of .keys(). You then made the same mistake again in thinking that b=copy.copy(d.keys()).sort() should work better, because it sorts a copy - still failing to see that it is again the result of .sort() that gets assigned to b. So ISTM that you got puzzled by the order in which multiple things happen when written into a single line. My guess would be that methods are particularly puzzling, more so than functions (which make it somewhat more obvious that they entirely wrap their arguments, and are entitled to return whatever they want to). Regards, Martin From memracom at yahoo.com Sun Jul 22 16:00:53 2007 From: memracom at yahoo.com (memracom at yahoo.com) Date: Sun, 22 Jul 2007 13:00:53 -0700 Subject: Python MAPI In-Reply-To: <1184965933.212060.214800@m3g2000hsh.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> Message-ID: <1185134453.934837.325310@w3g2000hsg.googlegroups.com> > 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? I expect you will find it easier figuring out how to install your app in the SendTo menu rather than making your app callable via MAPI. This probably involves ShellExtensions but I believe there are utilities that can be used to add any arbitrary application to the SendTo menu. That may be enough for your application. You might want to have a look at SpamBayes for an example of an Outlook extension written in Python to get an idea of how you can interface with Outlook. From vasudevram at gmail.com Mon Jul 9 13:14:07 2007 From: vasudevram at gmail.com (vasudevram) Date: Mon, 09 Jul 2007 17:14:07 -0000 Subject: execute script in certain directory In-Reply-To: References: Message-ID: <1184001247.332648.100520@x35g2000prf.googlegroups.com> On Jul 9, 8:31 pm, brad wrote: > When I use idle or a shell to execute a python script, the script > executes in the directory it is currently in (in this case, my desktop). > However, when using GNOME and right clicking the py script and selecting > 'open with python', the execution occurs in my home directory, not my > desktop. > > Is there a way to force py scripts to always run within the directory > that they reside in? > > Thanks > > Brad > > /home/brad/Desktop/output - python from shell > /home/brad/Desktop/output - python from idle > /home/brad/output - python from Gnome 'right click' open with menu Any program that runs has a concept of a "current directory". All its work is done relative to that, unless you open files with absolute paths. Don't know if there's a generic way to do what you want. (There may be, just can't think of it right now). But there are specific ways - script-specific, that is: Add these lines to the top of your script: import os os.chdir(rundir) # Replace rundir above with the absolute path (in quotes) of whatever directory you want the script to have as its current directory when it runs. Looks like GNOME is doing a chdir to your home directory (probably for convenience or security reasons) before running your script, thats why you see that behaviour. This is why I say there may not be an easy generic way to do it - because it would involve modifying all possible execution environments from which your script could be launched. E.g.: even if you modify GNOME to do what you want, how about if tomorrow someone else wants to run your script from KDE or some other window manager? these could do things differently. HTH Vasudev Ram http://www.dancingbison.com http://jugad.livejournal.com http://sourceforge.net/projects/xtopdf From ccpsceo at gmail.com Wed Jul 11 00:06:54 2007 From: ccpsceo at gmail.com (DeveloperX) Date: Wed, 11 Jul 2007 04:06:54 -0000 Subject: How would I write this C code in Python? In-Reply-To: <469367e5$0$26831$426a74cc@news.free.fr> References: <1183743110.399675.180570@n60g2000hse.googlegroups.com> <5f7d2vF3b25tsU3@mid.uni-berlin.de> <469367e5$0$26831$426a74cc@news.free.fr> Message-ID: <1184126814.537520.242520@n60g2000hse.googlegroups.com> On Jul 10, 5:05 am, Bruno Desthuilliers wrote: > Mmm... We can't tell for sure since we have no use case, but I'm not > sure that the OP wants an immutable object here. > > > or an `array.array`. > > or a StringIO. > > > And is `BLOCK` > > really just a structure with *one* member? Looks a bit odd IMHO. > > +1 > > > Unless you have behaviours attached to this type, you may as well just > use lists. > > > And while we're at it, Python's conventions are that ALL_UPPER names > denotes (pseudo) constants. For types, the conventions is to use > CantRememberIfItsCamelOrMixedCaseButYouShouldGetTheIdeaByNow. > > HTH I just used the same convention that the C code used in this post. I write my python classes and functions in CamelCaps. Not completely certain what to do at this point. From jeremy.lynch at gmail.com Thu Jul 12 12:19:24 2007 From: jeremy.lynch at gmail.com (Jeremy Lynch) Date: Thu, 12 Jul 2007 09:19:24 -0700 Subject: Lists in classes In-Reply-To: <1184253811.052346.220470@22g2000hsm.googlegroups.com> References: <1184253811.052346.220470@22g2000hsm.googlegroups.com> Message-ID: <1184257164.737719.274870@w3g2000hsg.googlegroups.com> Thanks for all the replies, very impressive. Got it now. Jeremy. On Jul 12, 4:23 pm, Jeremy Lynch wrote: > Hello, > > Learning python from a c++ background. Very confused about this: > > ============ > class jeremy: > list=[] > def additem(self): > self.list.append("hi") > return > > temp = jeremy() > temp.additem() > temp.additem() > print temp.list > > temp2 = jeremy() > print temp2.list > ============== > The output gives: > ['hi','hi'] > ['hi','hi'] > > Why does adding items to one instance produce items in a separate > instance? Doesn't each instance of jeremy have its' own "list"? > > Many thanks for clearing up this newbie confusion. > > Jeremy. From tereus at lionek.pl Mon Jul 16 15:01:03 2007 From: tereus at lionek.pl (Piotr Hrebieniuk) Date: Mon, 16 Jul 2007 21:01:03 +0200 Subject: testing with coverage.py problem Message-ID: Hi there. I've spent few hours and found nothing, so here's my question: How can i run tests wrote by myself on a module, using coverage.py ? Let's assume i have a module mymod.py which i want to test with tests from file mytest.py (i.e. class inherited from unittest.TestCase). How to do that with coverage.py? Where i should put the code that runs the tests? -- Regards Piotr Hrebieniuk From steve at holdenweb.com Fri Jul 20 14:38:34 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Jul 2007 14:38:34 -0400 Subject: subprocess (spawned by os.system) inherits open TCP/UDP/IP port In-Reply-To: <87abtrqf47.fsf@mulj.homelinux.net> References: <87abtrqf47.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: > alf writes: > >> still would like to find out why it is happening (now FD_CLOEXEC >> narrowed may yahooing/googling searches). While realize that file >> descriptors are shared by forked processes it is still weird why the >> port moves to the child process once parent gets killed. what it the >> parent got multiple subprocesses. > > Netstat probably shows only one of the processes that hold to the > port, possibly the one with the lowest PID (the parent). > >> Plus it is kind of unintuitive os.system does not protect from such >> behavoir which is for me more an equivalent of like issuing a ne >> wcommand/ starting a process from the shell. > > It is considered a feature that fork/exec'ed programs inherit file > descriptors -- that's how stdin and stdout get inherited all the time. > It doesn't occur often with network connections because shells rarely > have reason to open them. It would be hard to figure out how (x)inetd or TCP wrappers could work without the open connection being passed to the spawned server process. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- Asciimercial ------------------ Get on the web: Blog, lens and tag the Internet Many services currently offer free registration ----------- Thank You for Reading ------------- From cathy at nachofoto.com Mon Jul 2 14:49:44 2007 From: cathy at nachofoto.com (Cathy Murphy) Date: Mon, 2 Jul 2007 11:49:44 -0700 Subject: Python compilation ?? Message-ID: Is python a compiler language or interpreted language. If it is interpreter , then why do we have to compile it? Python newbie -- Cathy www.nachofoto.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE.THIS.cybersource.com.au Wed Jul 25 22:04:01 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 26 Jul 2007 12:04:01 +1000 Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> <87ps2ghtd7.fsf@benfinney.id.au> <1185412639.075218.186290@z24g2000prh.googlegroups.com> Message-ID: On Wed, 25 Jul 2007 18:17:19 -0700, mensanator at aol.com wrote: > On Jul 25, 8:00 pm, Ben Finney > wrote: >> "mensana... at aol.com" writes: >> > On Jul 24, 6:08 pm, Steven D'Aprano >> > wrote: >> > > Python already does: >> > > "hello-" "world" => "hello-world" >> >> > > Propose: >> > > 123 456 789 => 123456789 >> > > 123.456 789 => 123.456789 >> >> > So, spaces will no longer be delimiters? >> >> I don't see how you get that conclusion from Steven's proposal. > > IDLE 1.2c1 >>>> s = '123 456' >>>> s.split() > ['123', '456'] > > The only way to get '123 456' would be to treat a space as a > non-delimiter. But what if those actually WERE two different numbers? That makes no sense at all. Your example is about splitting a _string_. You can construct and split the string any way you like: >>> s = '123SURPRISE456' >>> s.split('SURPRISE') ['123', '456'] Notice that the results aren't ints, they are strings. To get an int literal, you currently type something like 123456. 123 456 is currently not valid in Python, it raises an SyntaxError. Try it for yourself: >>> 123 456 File "", line 1 123 456 ^ SyntaxError: invalid syntax If you want two numbers, you would do exactly the same thing you would now: >>> x, y = 123, 456 >>> print "x is %d and y is %d" % (x, y) x is 123 and y is 456 -- Steven. From harry.g.george at boeing.com Fri Jul 6 01:20:18 2007 From: harry.g.george at boeing.com (Harry George) Date: Fri, 6 Jul 2007 05:20:18 GMT Subject: VB frontend to Python COM backend References: <1183701494.979323.301500@d30g2000prg.googlegroups.com> Message-ID: nik writes: > I have a VB6 application that I would like to attach to a python > communications application. > > I have come across several discussions on using VB with a Python COM > back-end, but no starting point. I haven't had anymore luck with > google at finding out what this method is called and where to find > more information or examples on it. I would really appreciate it if > someone could point me in the right direction for using python objects > from VB. > > Thank you, > Nik > Search for "python win32 book". You want "Python Programming on Win32" By Mark J.. Hammond, Andy Robinson. It covers exactly this case. -- Harry George PLM Engineering Architecture From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jul 11 10:37:19 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 11 Jul 2007 16:37:19 +0200 Subject: bool behavior in Python 3000? In-Reply-To: References: Message-ID: <4694eb01$0$24460$426a74cc@news.free.fr> Steven Bethard a ?crit : (snip) > Remember that while Python 3 is allowed to break backwards > compatibility, it's only supposed to do it when there are concrete > benefits. Clearly there are existing use cases for treating bools like > ints, e.g. from Alexander Schmolck's email: > > (x < b) * f(x) > -1 ** (i == j) Both can be cleanly handled using int(): int(x < b) * f(x) -1 ** int(i == j) Not that I have any clear opinion on the topic FWIW. From gagsl-py2 at yahoo.com.ar Mon Jul 30 00:42:46 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 30 Jul 2007 01:42:46 -0300 Subject: Bug in cPickle with packages and 'object' inherited class References: <1185395566.665326.310600@d55g2000hsg.googlegroups.com> Message-ID: En Wed, 25 Jul 2007 17:32:46 -0300, Conrado PLG escribi?: > Say you have this structure: > > pna/ > __init__.py > model.py > > > __init__.py is empty. > > model.py is: > > > import cPickle as pickle > > class A(object): > pass > > def serialize(): > pickle.dump(A(), open('temp.dat', 'wb')) > > > Now open a python interpreter on the root directory of that structure > and type: > > > import pna.model > pna.model.serialize() > > > The following exception is thrown: > > > Traceback (most recent call last): > File "test.py", line 2, in > pna.model.serialize() > File "...\pna\model.py", line 7, in serialize > pickle.dump(A(), open('temp.dat', 'wb')) > cPickle.PicklingError: Can't pickle : import of > module pna.model failed It works for me. What are those "..." in the file name? -- Gabriel Genellina From eigenehps at web.de Mon Jul 23 19:23:58 2007 From: eigenehps at web.de (Nooby) Date: Mon, 23 Jul 2007 16:23:58 -0700 Subject: python a lonys Message-ID: <1185233038.242553.95340@n60g2000hse.googlegroups.com> http://www.directurl.de/39850293 thissi something new 4 u guys From thejaswi.puthraya at gmail.com Fri Jul 27 05:53:51 2007 From: thejaswi.puthraya at gmail.com (theju) Date: Fri, 27 Jul 2007 09:53:51 -0000 Subject: Submit form, open result in a browser In-Reply-To: References: Message-ID: <1185530031.986538.270490@m37g2000prh.googlegroups.com> > Is there a way to submit a form and then open the resulting page in the > default browser? (Writing the form submission code is not a problem by > the way) There is a library called "Client Form" that does this for you. wwwsearch.sourceforge.net/ClientForm/ > I guess what I'm asking is how I can get the resulting URL and feed it > to the webbrowser module. After the form is submitted through ClientForm open the resulting response using the webbrowser module. Cheers Thejaswi Puthraya From nospam at nospam.com Mon Jul 23 20:32:02 2007 From: nospam at nospam.com (Gilles Ganault) Date: Tue, 24 Jul 2007 02:32:02 +0200 Subject: [2.5] Regex doesn't support MULTILINE? References: Message-ID: <13iaa3hi7nkamcjnibd52mk00f7tinp8l7@4ax.com> On Sun, 22 Jul 2007 05:34:17 -0300, "Gabriel Genellina" wrote: >Try to avoid using ".*" and ".+" (even the non greedy forms); in this >case, I think you want the scan to stop when it reaches the ending >or any other tag, so use: [^<]* instead. > >BTW, better to use a raw string to represent the pattern: pattern = >r"...\d+..." Thanks everyone for the help. It did improve things significantly :-) From sjmachin at lexicon.net Tue Jul 24 08:15:42 2007 From: sjmachin at lexicon.net (John Machin) Date: Tue, 24 Jul 2007 05:15:42 -0700 Subject: how to get next month string? In-Reply-To: References: Message-ID: <1185279342.863711.246700@d30g2000prg.googlegroups.com> On Jul 24, 8:31 pm, "Yinghe Chen" wrote: > Hi, > Could someone help on how to use python to output the next month string like > this? > > "AUG07", suppose now is July 2007. > > I think also need to consider Dec 07 case, it is supposed to output as > below: > "JAN07". > > datetime module seems not supporting the arithmatic operations, any hints? > > Thanks in advance, > > Yinghe Chen >>> import datetime >>> def nextmo(d): ... mo = d.month ... yr = d.year ... mo += 1 ... if mo > 12: ... mo = 1 ... yr += 1 ... return datetime.date(yr, mo, 1).strftime('%b%y').upper() ... >>> nextmo(datetime.date(2007,7,15)) 'AUG07' >>> nextmo(datetime.date(2007,12,15)) 'JAN08' >>> From uymqlp502 at sneakemail.com Thu Jul 26 19:22:57 2007 From: uymqlp502 at sneakemail.com (Russ) Date: Thu, 26 Jul 2007 16:22:57 -0700 Subject: automatic type conversion for comparison operators Message-ID: <1185492177.836716.312390@q75g2000hsh.googlegroups.com> I posted a message on this several days ago, but it apparently got lost in googlespace, so I'll try it again. I recently discovered a bug in my code that apparently resulted from the automatic conversion of a function pointer to an integer. Say you have a class member function called getCount(), which returns an integer. Now suppose you write something like if obj.getCount < 3: ... This is an error because the parentheses were left off. But Python somehow compares the function pointer with an integer without complaining. Unless there is a darn good reason for allowing comparisons of this type (and I can't think of one), I think Python should flag this as an Exception. From Ira.Kovac at gmail.com Fri Jul 27 13:23:23 2007 From: Ira.Kovac at gmail.com (Ira.Kovac at gmail.com) Date: Fri, 27 Jul 2007 10:23:23 -0700 Subject: Filtering content of a text file In-Reply-To: <5guagnF3hehbbU1@mid.individual.net> References: <1185528507.750436.91140@j4g2000prf.googlegroups.com> <5guagnF3hehbbU1@mid.individual.net> Message-ID: <1185557003.253128.246830@w3g2000hsg.googlegroups.com> Thanks all for the input. This is going to be a great basis for starting. And, yeah - I wish it was a homework. Best, Ira From martin at see.sig.for.address Tue Jul 3 07:24:19 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Tue, 03 Jul 2007 12:24:19 +0100 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <138jml0ldeucf32@corp.supernews.com> Message-ID: <48opl4-uaj.ln1@zoogz.gregorie.org> Peter J. Holzer wrote: > On 2007-07-03 05:12, Scott David Daniels wrote: >> TOPS-20 did an interesting format which suggest an interesting variant: >> Tops-20: 36-bit (the machine word size) fixed-bit representation >> of days since a given moment (the first Photographic >> plates of the sky). The "binary point" was at the middle >> of the word; the low order 18 bits were the time of day >> (GMT), the high-order 18 bits were the days-since date. >> I think there's a definite practical advantage in storing dates as a day count from a base date and providing a standard set of procedures/methods to convert it to and from a human-readable format. It makes all sorts of date calculations much easier. For instance, if there's a requirement to produce statements dated for the last day of the current month the pseudo code is simply: - convert the date to ccyymmdd format - add 1 to the month, adjusting the year and century to fix year roll-over and set the day to 1 - convert back to day count and subtract 1 - the result, output in readable form is the last day of the month irrespective of month length, leap years, etc. I don';t think it matters what the base date is, though the Astronomical base date [12 noon on 1 JAN -4712 (4713 BC)] may be as good as any. Other bases I've seen (apart from UNIX date) are ICL 1900 mainframes, which set day zero as 31 Dec 1899 and held the time separately. ICL 2900 systems held the date and time as microseconds since 00:00:00 1900-01-01 in a 64 bit word, which is also easy to deal with and allows the same set of date arithmetic operations as a straight day number. BTW, be sure to distinguish Julian Day and Modified Julian Day (used by astronomers from the "Julian Date" that [used to] be used by IBM mainframes. The former is a day count but the latter is day within year (yyddd). JD and MJD are described in: http://tycho.usno.navy.mil/mjd.html -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From rcdailey at gmail.com Fri Jul 13 10:56:29 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 13 Jul 2007 14:56:29 -0000 Subject: How to create new files? In-Reply-To: <469731ea$0$18333$426a74cc@news.free.fr> References: <1184274877.612434.26870@k79g2000hse.googlegroups.com> <469731ea$0$18333$426a74cc@news.free.fr> Message-ID: <1184338589.129432.178560@w3g2000hsg.googlegroups.com> On Jul 13, 3:04 am, Bruno Desthuilliers wrote: > Robert Dailey a ?crit : > > > Hi, > > > I'm trying to create a Python equivalent of the C++ "ifstream" class, > > with slight behavior changes. > > > Basically, I want to have a "filestream" object that will allow you to > > overload the '<<' and '>>' operators to stream out and stream in data, > > respectively. So far this is what I have: > > > class filestream: > > class Filestream(object): > > > def __init__( self, filename ): > > self.m_file = open( filename, "rwb" ) > > You don't need this C++ 'm_' prefix here - since the use of self is > mandatory, it's already quite clear that it's an attribute. > > > > > # def __del__( self ): > > # self.m_file.close() > > > def __lshift__( self, data ): > > self.m_file.write( data ) > > > def __rshift__( self, data ): > > self.m_file.read( data ) > > > So far, I've found that unlike with the C++ version of fopen(), the > > Python 'open()' call does not create the file for you when opened > > using the mode 'w'. > > It does. But you're not using 'w', but 'rw'. > > > I get an exception saying that the file doesn't > > exist. > > Which is what happens when trying to open an inexistant file in read mode. > > > I expected it would create the file for me. Is there a way to > > make open() create the file if it doesn't exist > > yes : open it in write mode. > > def __init__( self, filename ): > try: > self._file = open( filename, "rwb" ) > except IOError: > # looks like filename doesn't exist > f = open(filename, 'w') > f.close() > self._file = open( filename, "rwb" ) > > Or you can first test with os.path.exists: > > def __init__( self, filename ): > if not os.path.exists(filename): > # looks like filename doesn't exist > f = open(filename, 'w') > f.close() > self._file = open( filename, "rwb" ) > > HTH Thanks for the variable naming tips. Is it normal for Python programmers to create class members with a _ prefixed? I also figured out why it wasn't creating the file after I had posted, I realized I was doing "rw" instead of just "w". Thank you for verifying. Thanks to everyone else for your replies as well. From cito at online.de Sun Jul 8 09:53:51 2007 From: cito at online.de (Christoph Zwerschke) Date: Sun, 08 Jul 2007 15:53:51 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: <1183844028.501781.266230@g4g2000hsf.googlegroups.com> References: <1183842825.057867.169710@q75g2000hsh.googlegroups.com> <1183844028.501781.266230@g4g2000hsf.googlegroups.com> Message-ID: samwyse wrote: > def test(code): > try: > code() > except Exception, e: > try: > raise e.__class__, str(e) + ", sorry!" > except TypeError: > raise SorryFactory(e)() Ok, you're suggestig the naive approach if it works and the factory approach I came up with last as a fallback. Maybe a suitable compromize. -- Chris From mccredie at gmail.com Fri Jul 20 13:00:55 2007 From: mccredie at gmail.com (Matt McCredie) Date: Fri, 20 Jul 2007 10:00:55 -0700 Subject: Images in Tkinter In-Reply-To: <1184949437.876063.78860@w3g2000hsg.googlegroups.com> References: <1184949437.876063.78860@w3g2000hsg.googlegroups.com> Message-ID: <9e95df10707201000i27ddb29eg478b33158dee0ac3@mail.gmail.com> That code doesn't tell me anything. You are going to have to post a more complete example to get help. Like, enough code so that I can run it and see the same problem. > Also, I tried creating the image object outside class but it > gives a runtime error saying it is too early to create an image > object. Please help! You need to call Tkinter.Tk() before you can create an instance of `PhotoImage' (I don't know why, but I know I got a similar error when I didn't). Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcsgbrevkonto at gmail.com Sat Jul 28 13:22:11 2007 From: marcsgbrevkonto at gmail.com (MarkyMarc) Date: Sat, 28 Jul 2007 17:22:11 -0000 Subject: How to write a warning to my log file? Message-ID: <1185643331.804498.251550@g4g2000hsf.googlegroups.com> Hi All, A small newbie Q. I have made a nice log function in me program. The program writes some data to me mysql database. When I write to the database I get som warnings back. Have do I write these to me log file? I know I have to use the the warnings api. But I can not figure out how to use it. Is there anyone take might give me a small example. THX all :-) From rschroev_nospam_ml at fastmail.fm Thu Jul 5 14:04:32 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 05 Jul 2007 18:04:32 GMT Subject: WXPYTHON push button call a frame In-Reply-To: <1183626149.036739.281070@w5g2000hsg.googlegroups.com> References: <1183626149.036739.281070@w5g2000hsg.googlegroups.com> Message-ID: Marcpp schreef: > Hi I need to call a widget from a button in WXPYTHON. I've tried to > this from a function like this, but when push the button, the program > opens a window and do error. > Any idea? > > ..... > def DialogRRHH(self,event): > prog = wx.PySimpleApp(0) > wx.InitAllImageHandlers() > DialogRRHH = MTRRHH(None, -1, "") > prog.SetTopWindow(DialogRRHH) > DialogRRHH.Show() > prog.MainLoop() > > class MTRRHH(wx.Frame): > ....... > if __name__ == "__main__": > app = wx.PySimpleApp(0) > wx.InitAllImageHandlers() > tasques = tasques(None, -1, "") > app.SetTopWindow(tasques) > tasques.Show() > app.MainLoop() In DialogRRHH() you create a new application object with a new event loop, while you already have one running. wxPython should have only one application object though; otherwise there conflicts between the different event loops. Also you don't need to call wx.InitAllImageHandlers() again. It seems to me that in DialogRRHH() you want to create a dialog and wait until the user closes it. In that case, it should look more or less like this (beware, I'm not a wxPython expert myself): def DialogRRHH(self, event): DialogRRHH = MTRRHH(None, -1, "") DialogRRHH.ShowModal() Also, in that case MTRRHH should be a wxDialog, not a wxFrame. In case you want to show MTRRHH without waiting for the user to close it, use DialogRRHH.Show() instead of .ShowModal(). I think MTRRHH can be either a wxDialog or a wxForm in that case. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From cito at online.de Sun Jul 8 09:50:12 2007 From: cito at online.de (Christoph Zwerschke) Date: Sun, 08 Jul 2007 15:50:12 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: <1183863713.876365.111820@57g2000hsv.googlegroups.com> References: <1183863713.876365.111820@57g2000hsv.googlegroups.com> Message-ID: Did you run this? With Py < 2.5 I get a syntax error, and with Py 2.5 I get: new.__class__ = old.__class__ TypeError: __class__ must be set to a class -- Chris From pink at odahoda.de Mon Jul 30 07:37:07 2007 From: pink at odahoda.de (Benjamin Niemann) Date: Mon, 30 Jul 2007 13:37:07 +0200 Subject: Cross platform Python app deployment References: <46adbbec$0$15210$fa0fcedb@news.zen.co.uk> Message-ID: Hi, Will McGugan wrote: > Is there some reference regarding how to package a Python application > for the various platforms? I'm familiar with Windows deployment - I use > Py2Exe & InnoSetup - but I would like more information on deploying on > Mac and Linux. The standard way to package portable Python apps is a tarball with a setup.py script. That should work on all systems where Python is already installed, including Windows. Read , if you have not already done so. If you want more 'native' packages (as you already have for Windows, where users are used to have a graphical installer), you'll have to create .deb, .rpm, .whatever packages. You usually won't have to bother about the Python interpreter, because it is either already present (it's a standard package on most systems) or it will be pulled in via a package dependency. distutils already allows you to create rpm packages. HTH -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From steven.robbins at gmail.com Mon Jul 2 23:46:59 2007 From: steven.robbins at gmail.com (Stevo) Date: Tue, 03 Jul 2007 03:46:59 -0000 Subject: ZSI Web Service Call Message-ID: <1183434419.222156.137670@i38g2000prf.googlegroups.com> Hi There, I'm looking for an example of a simple SOAP web service call using the Zolera SOAP Infrastructure library. The web service I am trying to call contains a method that is supposed to accept a string as a parameter and output it to a file. I have tried the following and I am able to create the file on the web server although the file is empty. Is there additional code required for this? from datetime import datetime from EventsDatabase_services import * from ZSI.client import * import sys def main(): SOAPAction = 'http://tempuri.org/ALU.EventsDatbase/ EventsDatabase/LogEventStringInputTest' teststring = 'This is a test' loc = EventsDatabaseLocator() port = loc.getEventsDatabaseSoap() req = LogEventStringInputTestSoapIn() req.input = 'test' resp = port.LogEventStringInputTest(req) print resp ################################################## # EventsDatabase_services.py # generated by ZSI.generate.wsdl2python ################################################## from EventsDatabase_services_types import * import urlparse, types from ZSI.TCcompound import ComplexType, Struct from ZSI import client import ZSI from ZSI.generate.pyclass import pyclass_type # Locator class EventsDatabaseLocator: EventsDatabaseSoap_address = "http://tipsy/ALU.EventsDatabase/ EventsDatabase.asmx" def getEventsDatabaseSoapAddress(self): return EventsDatabaseLocator.EventsDatabaseSoap_address def getEventsDatabaseSoap(self, url=None, **kw): return EventsDatabaseSoapSOAP(url or EventsDatabaseLocator.EventsDatabaseSoap_address, **kw) # Methods class EventsDatabaseSoapSOAP: def __init__(self, url, **kw): kw.setdefault("readerclass", None) kw.setdefault("writerclass", None) # no resource properties self.binding = client.Binding(url=url, **kw) # no ws-addressing # op: LogEventStringInputTest def LogEventStringInputTest(self, request): if isinstance(request, LogEventStringInputTestSoapIn) is False: raise TypeError, "%s incorrect request type" % (request.__class__) kw = {} # no input wsaction self.binding.Send(None, None, request, soapaction="http:// tempuri.org/ALU.EventsDatbase/EventsDatabase/LogEventStringInputTest", **kw) # no output wsaction response = self.binding.Receive(LogEventStringInputTestSoapOut.typecode) return response LogEventStringInputTestSoapIn = ns0.LogEventStringInputTest_Dec().pyclass LogEventStringInputTestSoapOut = ns0.LogEventStringInputTestResponse_Dec().pyclass ################################################## ################################################## import ZSI import ZSI.TCcompound from ZSI.schema import LocalElementDeclaration, ElementDeclaration, TypeDefinition, GTD, GED from ZSI.generate.pyclass import pyclass_type ############################## # targetNamespace # http://tempuri.org/ALU.EventsDatbase/EventsDatabase ############################## class ns0: targetNamespace = "http://tempuri.org/ALU.EventsDatbase/ EventsDatabase" class LogEventStringInputTest_Dec(ZSI.TCcompound.ComplexType, ElementDeclaration): literal = "LogEventStringInputTest" schema = "http://tempuri.org/ALU.EventsDatbase/EventsDatabase" def __init__(self, **kw): ns = ns0.LogEventStringInputTest_Dec.schema TClist = [ZSI.TC.String(pname=(ns,"input"), aname="_input", minOccurs=0, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))] kw["pname"] = ("http://tempuri.org/ALU.EventsDatbase/ EventsDatabase","LogEventStringInputTest") kw["aname"] = "_LogEventStringInputTest" self.attribute_typecode_dict = {} ZSI.TCcompound.ComplexType.__init__(self,None,TClist,inorder=0,**kw) class Holder: __metaclass__ = pyclass_type typecode = self def __init__(self): # pyclass self._input = None return Holder.__name__ = "LogEventStringInputTest_Holder" self.pyclass = Holder class LogEventStringInputTestResponse_Dec(ZSI.TCcompound.ComplexType, ElementDeclaration): literal = "LogEventStringInputTestResponse" schema = "http://tempuri.org/ALU.EventsDatbase/EventsDatabase" def __init__(self, **kw): ns = ns0.LogEventStringInputTestResponse_Dec.schema TClist = [ZSI.TC.String(pname=(ns,"LogEventStringInputTestResult"), aname="_LogEventStringInputTestResult", minOccurs=0, maxOccurs=1, nillable=False, typed=False, encoded=kw.get("encoded"))] kw["pname"] = ("http://tempuri.org/ALU.EventsDatbase/ EventsDatabase","LogEventStringInputTestResponse") kw["aname"] = "_LogEventStringInputTestResponse" self.attribute_typecode_dict = {} ZSI.TCcompound.ComplexType.__init__(self,None,TClist,inorder=0,**kw) class Holder: __metaclass__ = pyclass_type typecode = self def __init__(self): # pyclass self._LogEventStringInputTestResult = None return Holder.__name__ = "LogEventStringInputTestResponse_Holder" self.pyclass = Holder class string_Dec(ZSI.TC.String, ElementDeclaration): literal = "string" schema = "http://tempuri.org/ALU.EventsDatbase/EventsDatabase" def __init__(self, **kw): kw["pname"] = ("http://tempuri.org/ALU.EventsDatbase/ EventsDatabase","string") kw["aname"] = "_string" class IHolder(str): typecode=self kw["pyclass"] = IHolder IHolder.__name__ = "_string_immutable_holder" ZSI.TC.String.__init__(self, **kw) # end class ns0 (tns: http://tempuri.org/ALU.EventsDatbase/EventsDatabase) From hniksic at xemacs.org Fri Jul 20 08:47:52 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 20 Jul 2007 14:47:52 +0200 Subject: class C: vs class C(object): References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> <1184923127.990359.288920@d55g2000hsg.googlegroups.com> Message-ID: <87hcnzqm13.fsf@mulj.homelinux.net> "sjdevnull at yahoo.com" writes: > In particular, old-style classes are noticeably faster than > new-style classes for some things (I think it was attribute lookup > that surprised me recently, possibly related to the property > stuff...) Can you post an example that we can benchmark? I ask because the opposite is usually claimed, that (as of Python 2.4 or 2.5) new-style classes are measurably faster. From Minallewis at gmail.com Tue Jul 31 16:12:39 2007 From: Minallewis at gmail.com (Min w) Date: Tue, 31 Jul 2007 13:12:39 -0700 Subject: =?utf-8?B?4peYIExlZ2FsbHkgQWNjZXNzIEZSRUUgU2F0ZWxsaXRlIFRWIG9uIFBDIOKXmA==?= Message-ID: <1185912759.532443.173070@d30g2000prg.googlegroups.com> Turn your Computer into a Ultimate TV ? Watch all your favorite shows on your Computer & TV! ? Channels you can?t get any other place in the U.S.A! ? Watch from anywhere in the world! ? Save 1000's of $$$ over many years on cable and satellite bills ? INSTANT DOWNLOAD ? And much, much more! For More Details: http://tvonpc.7p.com/ From attn.steven.kuo at gmail.com Wed Jul 25 19:56:10 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Wed, 25 Jul 2007 16:56:10 -0700 Subject: Reading files, splitting on a delimiter and newlines. In-Reply-To: <1185378363.166434.172190@r34g2000hsd.googlegroups.com> References: <1185378363.166434.172190@r34g2000hsd.googlegroups.com> Message-ID: <1185407770.462158.57490@z24g2000prh.googlegroups.com> On Jul 25, 8:46 am, chris... at gmail.com wrote: > Hello, > > I have a situation where I have a file that contains text similar to: > > myValue1 = contents of value1 > myValue2 = contents of value2 but > with a new line here > myValue3 = contents of value3 > > My first approach was to open the file, use readlines to split the > lines on the "=" delimiter into a key/value pair (to be stored in a > dict). > > After processing a couple files I noticed its possible that a newline > can be present in the value as shown in myValue2. > > In this case its not an option to say remove the newlines if its a > "multi line" value as the value data needs to stay intact. > > I'm a bit confused as how to go about getting this to work. > > Any suggestions on an approach would be greatly appreciated! Check the length of the list returned from split; this allows your to append to the previously extracted value if need be. import StringIO import pprint buf = """\ myValue1 = contents of value1 myValue2 = contents of value2 but with a new line here myValue3 = contents of value3 """ mockfile = StringIO.StringIO(buf) record=dict() for line in mockfile: kvpair = line.split('=', 2) if len(kvpair) == 2: key, value = kvpair record[key] = value else: record[key] += line pprint.pprint(record) # lstrip() to remove newlines if needed ... -- Hope this helps, Steven From http Sat Jul 28 03:28:12 2007 From: http (Paul Rubin) Date: 28 Jul 2007 00:28:12 -0700 Subject: 128 or 96 bit integer types? References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com> <1185562901.206212.52570@j4g2000prf.googlegroups.com> <1185607142.096574.209200@e16g2000pri.googlegroups.com> Message-ID: <7xlkd1ugvn.fsf@ruckus.brouhaha.com> "mensanator at aol.com" writes: > has 146 digits. And that's just the begining. The above > actually represents a polynomial with 264 terms, the > exponents of which range from 0 to 492. One of those > polynomials can have over 50000 decimal digits when > solved. You should use gmpy rather than python longs if you're dealing with numbers of that size. Python multiplication uses a straightforward O(n**2) algorithm where n is the number of digits. This is the best way for up to a few hundred or maybe a few thousand digits. After that, it's better to use more complicated FFT-based algorithms which are O(n log n) despite their increased constant overhead. Gmpy does this. From kyosohma at gmail.com Wed Jul 11 16:19:57 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 11 Jul 2007 13:19:57 -0700 Subject: ImportError: MemoryLoadLibrary failed loading In-Reply-To: <1184003221.733125.38270@57g2000hsv.googlegroups.com> References: <1184003221.733125.38270@57g2000hsv.googlegroups.com> Message-ID: <1184185197.330464.109320@57g2000hsv.googlegroups.com> On Jul 9, 12:47 pm, kyoso... at gmail.com wrote: > Hi, > > Recently I began my journey into creating executables. I am using > Andrea > Gavana's cool GUI2EXE program which works very well and that is a GUI > for > py2ece. I am also using Inno Setup to create a script/executable. > Anyway, > today I am putting the program to the test with some volunteer testers > and > I've hit a wall. On the first tester's PC the program installed > beautifully and runs great. The next tester's PC, the program failed > to > run complaining that MSVCR71.dll didn't exist. I copied that file on > there and now I get the following traceback written to my exe's log > file: > > Traceback (most recent call last): > File "reminder.py", line 23, in ? > File "zipextimporter.pyo", line 78, in load_module > File "wx\__init__.pyo", line 45, in ? > File "zipextimporter.pyo", line 78, in load_module > File "wx\_core.pyo", line 4, in ? > File "zipextimporter.pyo", line 91, in load_module > ImportError: MemoryLoadLibrary failed loading wx\_core_.pyd > > I see other user's have this issue too sometimes and they talk a lot > about > a "gdiplus.dll" file. My user's PC has that file in 4 places on her > computer and my development PC has it in 6 places. Does either DLL > have to > be in a specific location for the executable to find it? Is this > something > else entirely? I tried sticking the gdiplus.dll file in the directory > my > executable runs from too, but that didn't work either. > > I have posted this to the wxPython's group and the py2exe group, but > the latter doesn't have much activity and the wxPython suggestions > didn't work. > > Thanks a lot! > > Mike I figured this out, not that anyone probably cares. It seems the program was looking for MSVCP71.dll, but I (alas) included the MSVCR71.dll instead. If I include the correct file, it works. For all the newbs out there, spelling makes a difference! Mike From nytrokiss at gmail.com Thu Jul 19 13:19:34 2007 From: nytrokiss at gmail.com (James Matthews) Date: Thu, 19 Jul 2007 10:19:34 -0700 Subject: wxPython, searching, and threads In-Reply-To: <1184860309.970982.148880@r34g2000hsd.googlegroups.com> References: <1184789708.351825.224110@x35g2000prf.googlegroups.com> <1184860309.970982.148880@r34g2000hsd.googlegroups.com> Message-ID: <8a6b8e350707191019n4844374aqef235396a64acf99@mail.gmail.com> I have seen this thread for a while and i do not see it on the wxpython list so i am posting it there now and will post a reply if i still see this later! James On 7/19/07, kyosohma at gmail.com wrote: > > On Jul 18, 3:15 pm, Benjamin wrote: > > Hello! I am writing a search engine with wxPython as the GUI. As the > > search thread returns items, it adds them to a Queue which is picked > > up by the main GUI thread calling itself recursively with > > wx.CallAfter. These are then added to a ListCtrl. This works fine for > > small searches, but with larger and longer searchs the GUI is clogged > > and won't respond. I suspect (I may be wrong) that there are so many > > results being sent to the ListCtrl that the event loop doesn't have > > time to respond to events. I've tried buffering the results before > > sending them to the GIU, but that doesn't help at all. Please advise. > > I think what you need to look at is > http://wiki.wxpython.org/LongRunningTasks > > That's what the people on the wxPython list usually recommend when > doing what you're doing. I've used the techniques there and they work > great! > > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/watches.asp?Brand=14 http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From the.mindstorm.mailinglist at gmail.com Sun Jul 15 07:49:54 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Sun, 15 Jul 2007 04:49:54 -0700 Subject: Circular import problem In-Reply-To: References: <1184294176.550267.119980@n60g2000hse.googlegroups.com> <1184343897.111992.107880@g4g2000hsf.googlegroups.com> Message-ID: <1184500194.909470.178430@w3g2000hsg.googlegroups.com> On Jul 14, 6:27 am, "Gabriel Genellina" wrote: > En Fri, 13 Jul 2007 13:24:57 -0300, bvdp escribi?: > > > > > > >> Seehttp://effbot.org/zone/import-confusion.htm > >> Try to move the circular references later in the code (maybe inside a > >> function, when it is required), or much better, refactor it so there is > >> no > >> circularity. > > >> -- > >> Gabriel Genellina > > > Yes, thanks. I'd read that page before posting. Helpful. > > > But, I still don't understand how python can access a function in a > > file I have NOT included. In this case, to get things to work, I DO > > NOT "import MMA.grooves" but later in the module I access a function > > with "xx=MMA.grooves.somefunc()" and it finds the function, and works > > just fine. It shouldn't work. > > That depends a bit on what is "MMA" and what is "grooves". > MMA.grooves means "look for an attribute named grooves inside MMA". If MMA > is a module, and MMA.grooves is a class/function defined inside the > module, you don't need to import it before using it. I am a bit confused: I think the above should be: if MMA.grooves in a class/function defined inside the module MMA, you don't need to import the class/function before using it, but only import the module MMA. Am I wrong? tia, ./alex -- .w( the_mindstorm )p. > But if MMA is a package, and MMA.grooves is a module inside that package, > you need to import it first (unless MMA/__init__.py does that already) > > > I have tried to delay the import, and that does work. But, from a > > stylistic view I really to like to have all my imports at the top of > > the module. Maybe some old assembler/C habits on my part. > > Sure, it's considered good style. > > -- > Gabriel Genellina From goldtech at worldpost.com Sun Jul 22 18:53:58 2007 From: goldtech at worldpost.com (leegold) Date: Sun, 22 Jul 2007 15:53:58 -0700 Subject: Sort lines in a text file In-Reply-To: <1185084296.913235.97490@x35g2000prf.googlegroups.com> References: <1185073397.821811.143260@k79g2000hse.googlegroups.com> <1185084296.913235.97490@x35g2000prf.googlegroups.com> Message-ID: <1185144838.514595.301360@n60g2000hse.googlegroups.com> ...snip... > To save anybody who's tempted to write the whole shebang for you, > please specify which part(s) of the exercise you are having problems > with: > (a) reading lines from a file > (b) extracting a sort key from a line [presuming "number" means > "positive integer"; what do you want to do if multiple lines have the > same number? what if no number at all"] > (c) creating a list of tuples, where each tuple is (key, > line_contents) > (d) sorting the list > (e) creating the output file from the sorted list. Thanks, you've done more than enough right here! (a) through (e) gives me a good start. Again, thank you for this. From kkvilekval at gmail.com Tue Jul 10 20:55:52 2007 From: kkvilekval at gmail.com (kgk) Date: Tue, 10 Jul 2007 17:55:52 -0700 Subject: concatenate file-like objects -> file-like object Message-ID: <1184115352.818085.250500@e16g2000pri.googlegroups.com> I would like to concatenate several file-like objects to create a single file-like object. I've looked at fileinput, however this returns a fileinput object that is not very file-like. something like # a has 50 bytes, and b has 100 bytes f = FileList (open('a'), open('b')) f.read (100) # read 50 bytes from a and 50 from b My interest is in passing several files to an incremental parser as if they came from a single file. I would rather not load them in memory using StringIO and the parser reads only from file-like objects. Any pointers appreciated Kris From OlafMeding at gmail.com Tue Jul 24 17:52:50 2007 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: Tue, 24 Jul 2007 14:52:50 -0700 Subject: pg8000 (PostgreSQL DB-API 2.0) under IronPython Message-ID: <1185313970.735080.58200@m3g2000hsh.googlegroups.com> Has anyone tried to run pg8000, a pure Python PostgreSQL DB-API 2.0 implementation, under IronPython? If so, I would be interested in how well it worked. Many thanks for you help. Olaf From hg at nospam.org Sun Jul 1 10:55:01 2007 From: hg at nospam.org (hg) Date: Sun, 01 Jul 2007 09:55:01 -0500 Subject: Python app as a Display Manager References: <46879e09$0$22529$9b622d9e@news.freenet.de> Message-ID: <9fPhi.3834$%K1.426@newsfe21.lga> "Martin v. L?wis" wrote: >> I feel at this stage that what I miss is: assuming I manage to get a >> python-based dialog box started automatically from init.rc (instead of >> xdm, gdm, ...): how do I start an X11 session with the user/pw >> information retrieved ... + set the correct *nix environment variables. > > First, the user will enter username and password into your dialog box. > You need to verify this, either by using the pwd module, or by using PAM > (through python-pam). > > Then you need start a session. Fork a subprocess, and use setuid/setgid > to take the identity of the subprocess. In the parent process, wait for > this child process to terminate, then display your dialog again (perhaps > restarting the X server in-between). > > What you do in your session is your own choice. It is custom to set a > few environment variables, and then run /etc/X11/Xsession (or whereever > the standard X11 session script lives); the latter is done through exec, > i.e. when Xsession returns, the user has chosen to logout. > > This is the basic working principle; different display managers deviate > in how precisely they setup the session, and what precisely they run in > what order. > > However, this entire discussion is off-topic for comp.lang.python; > please ask on comp.windows.x instead. > > HTH, > Martin Martin, Many many thanks, I did post here also so someone would tell me whether using Python was feasible or not for this project (ex, having tkinter or wxPython running prior t oan actual X11 session). Also I did not know about comp.windows.x. Regards, hg From carsten at uniqsys.com Sun Jul 22 17:15:45 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 22 Jul 2007 17:15:45 -0400 Subject: space / nonspace In-Reply-To: References: Message-ID: <1185138945.3153.7.camel@localhost.localdomain> On Sun, 2007-07-22 at 22:33 +0200, Peter Kleiweg wrote: > >>> import re > >>> s = u'a b\u00A0c d' > >>> s.split() > [u'a', u'b', u'c', u'd'] > >>> re.findall(r'\S+', s) > [u'a', u'b\xa0c', u'd'] And your question is...? > This isn't documented either: > > >>> s = ' b c ' > >>> s.split() > ['b', 'c'] > >>> s.split(' ') > ['', 'b', 'c', ''] See http://docs.python.org/lib/string-methods.html -- Carsten Haese http://informixdb.sourceforge.net From nospam.themindstorm at gmail.com Tue Jul 31 06:44:41 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Tue, 31 Jul 2007 10:44:41 +0000 (UTC) Subject: Simple question about logging module. References: Message-ID: "Gabor Urban" wrote in news:f7ac28aa0707310146s4f230347qaf42128931cfd831 at mail.gmail.com: > ------=_Part_36089_18686793.1185871599583 > Hullo, > > I have started to use Python's logging, and got a problem. I have > created some loggers and wrote some lines in the log. The problem is, > that most of the lines appear doubled in the log, and some lines do > not appear at all. > > Any ideas or comments are wellcome, > > Gabor > > Here is the code: > > import sys > import logging > > l = logging.getLogger('XmlTester') > la = logging.getLogger('XmlTester.XmlParser') > lb = logging.getLogger('XmlTester.TestExecutor') I other worlds, loggers are hierarchical, and so XmlTester.XmlParser may be a child of XmlTester and so inheriting some of the properties of its parent. bests, ./alex -- .w( the_mindstorm )p. From sjmachin at lexicon.net Fri Jul 6 20:39:57 2007 From: sjmachin at lexicon.net (John Machin) Date: Fri, 06 Jul 2007 17:39:57 -0700 Subject: C++ Modules for python: How to? In-Reply-To: <1183764388.576690.31740@n60g2000hse.googlegroups.com> References: <1183750094.154566.248170@m36g2000hse.googlegroups.com> <5f7llqF3bfvstU1@mid.uni-berlin.de> <1183764388.576690.31740@n60g2000hse.googlegroups.com> Message-ID: <1183768797.659079.17150@o11g2000prd.googlegroups.com> On Jul 7, 9:26 am, Robert Dailey wrote: > On Jul 6, 3:06 pm, "Diez B. Roggisch" wrote: > > > > > Robert Dailey schrieb: > > > > Hi, > > > > I'm interested in making a C++ library of mine usable through python. > > > Python does a similar thing with Expat (the non-validating XML > > > parser). I notice that with Expat, python is importing a C++ header > > > file into a PY file and the interface is available to python. I've > > > read through the python documentation as well as done a little bit of > > > google research and I've not been able to find a tutorial of some sort > > > on how to do this. Perhaps I just don't know the right words to search > > > for. > > > > If anyone could lead me in the right direction (possibly an article, > > > tutorial, etc) I would greatly appreciate it. > > > The best thing to do is to offer your C++-lib with a C-style interface. > > Then you can use python's ctypes (included since python2.5) to access > > the shared library. > > > If you insist on using C++, you can expose the lib using several > > available wrapper generators. I know of three: SIP, Swig & > > Boost::Python. The first I've got some very good first-hand experience. > > The second is somewhat primitive IHMO. The third I never used. > > > Use these to google in this group, you'll find plenty of stuff. > > > Diez > > How do I install SIP? I can't seem to do this. I've downloaded the > package and read the README file, but I don't see a way of installing > it on windows. I ran the configure.py file but then it generates > makefiles to run which can't be run on windows. I also attempted to > download QT but it doesn't appear to be free (it's an evaluation and I > don't feel like submitting my personal information to download it). > > Am I missing something? Probably. "makefiles ... which can't be run on windows"??? Have you acquired a make program [if necessary] and tried it? What happened? The free Borland compiler comes with a make.exe. If you plan to use GCC, you will probably need this: http://gnuwin32.sourceforge.net/packages/make.htm I understand that if you have a Microsoft compiler, you should have an nmake.exe. If all else fails, e-mail the package author, supplying some relevant information, like what compiler you are using, what options you used on the configure.py run, which "make" you are using, what happened when you ran that make, ... From horpner at yahoo.com Wed Jul 4 21:43:08 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 05 Jul 2007 01:43:08 GMT Subject: disappearing documentation of `coerce` References: Message-ID: On 2007-07-05, Alan Isaac wrote: > Once upon a time, `coerce` was documented > with the other built-ins. > http://pydoc.org/1.5.2/__builtin__.html > Now it is not. > http://docs.python.org/lib/built-in-funcs.html > Reason? It's now documented in Library Reference 2.2 Non-essential Built-in Functions. Apparently it is no longer needed or useful, but only kept for backward compatibility. -- Neil Cerutti From nogradi at gmail.com Thu Jul 26 08:23:35 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 26 Jul 2007 14:23:35 +0200 Subject: Tix.Tk() on Mac Intel In-Reply-To: References: Message-ID: <5f56302b0707260523p523e97e1pe72144105db3fb92@mail.gmail.com> On 7/26/07, Alan wrote: > Hi List! > > I have I Macbook Pro Intel running OSX 10.4.10. > > I downloaded Python 2.5 and tried > TclTkAquaBI-8.4.10.0.dmg, but I got: > > Traceback (most recent call last): > File "", line 1, in > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py", > line 210, in __init__ > self.tk.eval('package require Tix') > _tkinter.TclError: no suitable image found. Did find: > /Library/Tcl/Tix8.4/libTix8.4.dylib: mach-o, but wrong architecture > > Which make sense since tcltkaqua is released only for PPC. Googling a > bit, since tcltkaqua stopped development, I found they recommended > ActiveTcl, but Tix is not included in the package. > > So removing tcltkaqua and ActiveTcl, when trying Tix.Tk() I got: > >>> Tix.Tk() > Traceback (most recent call last): > File "", line 1, in > File > "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/lib-tk/Tix.py", > line 210, in __init__ > self.tk.eval('package require Tix') > _tkinter.TclError: can't find package Tix > > The only way I got Tix.Tk() working so far was using Fink but I want > the nice aqua visual for python. Is there any way of getting it > working? > > I would appreciate any help here. > Many thanks in advance. > Cheers, > Alan > -- > http://mail.python.org/mailman/listinfo/python-list > You might want to look into this thread on the same issue: http://groups.google.com/group/comp.lang.python/browse_thread/thread/878b8a1d9e6d92ce/6f257a1c60ab50f2 From nagle at animats.com Mon Jul 9 02:10:30 2007 From: nagle at animats.com (John Nagle) Date: Sun, 08 Jul 2007 23:10:30 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xir8us3hm.fsf@ruckus.brouhaha.com> References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <5engo8F38jdgaU1@mid.uni-berlin.de> <4686b9b0$0$27140$426a74cc@news.free.fr> <5epe7aF39ugprU1@mid.uni-berlin.de> <7xir8us3hm.fsf@ruckus.brouhaha.com> Message-ID: <1ckki.25936$C96.7063@newssvr23.news.prodigy.net> Paul Rubin wrote: > "Diez B. Roggisch" writes: > >>>Which implies that even in ADA, runtime type errors are in fact >>>expected - else there would be no handler for such a case. >> >>Well, yes, runtime errors occur - in statically typed languages as >>well. That's essentially the halting-problem. > > > Well, no, it's quite possible for a language to reject every program > that has any possibility of throwing a runtime type error. The > halting problem implies that no algorithm can tell EXACTLY which > programs throw errors and which do not. So the language cannot accept > all programs that are free of runtime type errors and reject all > programs that definitely have runtime type errors, with no uncertain > cases. But it's fine for a language to reject uncertain cases and > accept only those which it can rigorously demonstrate have no type > errors. Also, if you're really into this, read this DEC SRL report on Extended Static Checking for Java, a system from the 1990s. ftp://gatekeeper.research.compaq.com/pub/DEC/SRC/research-reports/SRC-159.pdf They were doing great work until Compaq bought DEC and killed off research. The follow up to that is Microsoft's Spec# effort, which is program verification for C#. See http://research.microsoft.com/specsharp/ They have some of the same people, and some of the same code, as the DEC effort. Back when I was working on this, we only had a 1 MIPS VAX, and theorem proving was slow. That's much less of a problem now. John Nagle From michael.b.newman at gmail.com Thu Jul 12 06:31:21 2007 From: michael.b.newman at gmail.com (Michael Newman) Date: Thu, 12 Jul 2007 06:31:21 -0400 Subject: Try a different type of debugger. In-Reply-To: <1184129696.072448.266240@z28g2000prd.googlegroups.com> References: <1184129696.072448.266240@z28g2000prd.googlegroups.com> Message-ID: <804b685e0707120331i253626c2t7d00d46a852beb82@mail.gmail.com> Thanks for making this terrific program. Can you add a setting for screen size? (perhaps desired Width and Height in pixels)? I have my screen set at 1024x768 (the web browser window is of course a little bit smaller) and I can't see all the program's rendering at the far right. -Mike On 7/11/07, mfriedeman at gmail.com wrote: > This one does not need you to set any breakpoints. It records the > entire run. Handy, if you don't know where to start. > > Run the program once and after that all the runtime data is available > to you. Which means you can jump to any point in the run and verify > the code against runtime data. > > The user interface is the python code itself viewed inside a Firefox > browser. > Scroll to a line you're interested in and click the variable. > > It requires Firefox and Python 2.5. > > http://codeinvestigator.googlepages.com/main > > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations.html > From cappy2112 at gmail.com Mon Jul 30 18:58:12 2007 From: cappy2112 at gmail.com (Cappy2112) Date: Mon, 30 Jul 2007 22:58:12 -0000 Subject: win32 question in Python In-Reply-To: References: Message-ID: <1185836292.076175.215860@j4g2000prf.googlegroups.com> Hello Brad, If you don't get a reply here, there is a win32 specific Python list on ActiveState.com wher ethey do talk about excel & other Win32 python issues. On Jul 30, 3:49 pm, Brad Johnson wrote: > Huang, Shun-Hsien ercot.com> writes: > > > > but how do I copy a excel file into > > > database table by using Python? > > I'm not sure if this helps, but you can access the Excel Automation model very > easily with: > > import win32com.client > > x1 = client.Dispatch("Excel.Application") > > Now you can use the x1 object to access any of the properties and methods in the > Excel Automation model. From martin at v.loewis.de Sat Jul 28 05:07:05 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 28 Jul 2007 11:07:05 +0200 Subject: Compiling python2.5.1 results in 3.5MB python lib? In-Reply-To: <1185556268.287077.258080@d55g2000hsg.googlegroups.com> References: <1185556268.287077.258080@d55g2000hsg.googlegroups.com> Message-ID: <46AB0739.9040107@v.loewis.de> > I'm compiling 2.5.1 and end up with a 3.5MB libpython2.5.so file. I > seem to remember it should be somewhere around the 1MB mark. What > could be causing this? Try stripping it. Regards, Martin From jzgoda at o2.usun.pl Mon Jul 16 05:16:12 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 16 Jul 2007 11:16:12 +0200 Subject: how good does PyGTK work on windows? In-Reply-To: References: Message-ID: krishnakant Mane napisa?(a): > I will be writing some code in PyGTK to run on linux. but I want to > know if there are any installers or distutils available for PyGTK on > windows? > I have heard that installing gimp or even pygtk is next to impossible > and is very tedious if at all one gets success. > can any one share their experiences with installing and running pygtk on > windos? > any links for downloading proper packages will be highly appreciated. There's no problem with installing PyGTK on Windows. While it doesn't look as pretty as on Linux and some people mention newer versions (2.8 and on) performing bit unstable, I did not realize any instabilities. Just use package from gladewin32 project, there are separate downloads with development tools and without. Then just install pycairo, pygobject and pygtk packages from PyGTK project. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From apetresc at uwaterloo.ca Thu Jul 12 23:05:35 2007 From: apetresc at uwaterloo.ca (Adrian Petrescu) Date: Thu, 12 Jul 2007 20:05:35 -0700 Subject: Client-side cookies on Python in Mac OSX In-Reply-To: <1184293712.607084.27310@g37g2000prf.googlegroups.com> References: <1184292844.383002.128420@n2g2000hse.googlegroups.com> <1184293712.607084.27310@g37g2000prf.googlegroups.com> Message-ID: <1184295935.344343.85290@r34g2000hsd.googlegroups.com> Oh, you're right! Silly me, I had always thought it was standard. Thanks for pointing this out! I went and downloaded ClientCookie and it works great on OS X. And since it is BSD-licensed, I can use it in my app without any fear. Perfect. Thank you, Graham! On Jul 12, 10:28 pm, Graham Dumpleton wrote: > On Jul 13, 12:14 pm, Adrian Petrescu wrote: > > > > > Hi, all. I'm writing an app for OS X; therefore I'd prefer to use only > > the default python install that comes with Tiger. For the moment, > > however, this means: > > > NaviOSX:~ adrianpetrescu$ python -V > > Python 2.3.5 > > > Therefore, I was not surprised to find out that cookielib did not > > exist here, since I knew that it was a 2.4+ feature. > > > However, I *was* shocked to find out that ClientCookie, which I'd > > thought was a Python 2.0+ feature, also cannot be found: > > > >>> import ClientCookie > > > Traceback (most recent call last): > > File "", line 1, in ? > > ImportError: No module named ClientCookie > > > Why would Apple go out of their way to remove this functionality from > > their shipped version of Python? More importantly, considering I need > > to programatically access a website that uses cookies for > > authentication, how can I do this in OSX's Python install? Do they > > provide some other library they'd prefer you to use? > > > I'm sure SOMEONE in the world has used cookies on Macs so I'm hoping > > there is a solution for this... > > They didn't remove it, it was never there in the first place. > > The ClientCookie site says 'Python 2.0 or above is required'. It > doesn't say it is included with Python distributions. The package > still has to be installed separately. See: > > http://wwwsearch.sourceforge.net/ClientCookie/ > > Graham From harelmalka at gmail.com Tue Jul 10 05:32:04 2007 From: harelmalka at gmail.com (Harel) Date: Tue, 10 Jul 2007 02:32:04 -0700 Subject: Can I Redirect debug output from HTTPConnection to a file? Message-ID: <1184059924.122878.241210@o61g2000hsh.googlegroups.com> I'm using httplib.HTTPConnection to perform http connections and during the beta period of the application I wanted to log its verbose output [set_debuglevel(5)]. However, raising the debuglevel just outputs it to stdout. can I redirect that to a file? My app uses the logging module for logging and I'd like to use that to log into the standard log it generates. Any ideas? Thanks, Harel From sebzzz at gmail.com Fri Jul 27 14:50:49 2007 From: sebzzz at gmail.com (sebzzz at gmail.com) Date: Fri, 27 Jul 2007 18:50:49 -0000 Subject: Removing certain tags from html files In-Reply-To: <5gusq9F3iotlrU2@mid.uni-berlin.de> References: <1185558023.501016.90050@d30g2000prg.googlegroups.com> <5gusq9F3iotlrU2@mid.uni-berlin.de> Message-ID: <1185562249.094802.128360@e16g2000pri.googlegroups.com> > > Than take a hold on the content and add it to the parent. Somthing like > this should work: > > from BeautifulSoup import BeautifulSoup > > 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) > > def main(): > source = 'This is a Test' > soup = BeautifulSoup(source) > print soup > remove(soup, 'b') > print soup > > > Is re the good module for that? Basically, if I make an iteration that > > scans the text and tries to match every occurrence of a given regular > > expression, would it be a good idea? > > No regular expressions are not a very good idea. They get very > complicated very quickly while often still miss some corner cases. > Thanks a lot for that. It's true that regular expressions could give me headaches (especially to find where the tag ends). From stesch at no-spoon.de Thu Jul 26 13:45:07 2007 From: stesch at no-spoon.de (Stefan Scholl) Date: Thu, 26 Jul 2007 19:45:07 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49d313I3ogNv8%stesch@parsec.no-spoon.de> <46A8C934.3010601@web.de> Message-ID: <0T49dalhI43nNv8%stesch@parsec.no-spoon.de> Stefan Behnel wrote: > Stefan Scholl wrote: >> Stefan Behnel wrote: >>> Stefan Scholl wrote: >>>> Stefan Behnel wrote: >>>>> Stefan Scholl wrote: >>>>>> Well, http://docs.python.org/lib/module-xml.sax.html is missing >>>>>> the fact, that I can't use Unicode with parseString(). >>>>>> >>>>>> This parseString() uses cStringIO. >>>>> Well, Python unicode is not a valid *byte* encoding for XML. >>>>> >>>>> lxml.etree can parse unicode, if you really want, but otherwise, you should >>>>> maybe stick to well-formed XML. >>>> The XML is well-formed. Works perfect in Python 2.4 with Python >>>> unicode and Python sax parser. >>> The XML is *not* well-formed if you pass Python unicode instead of a byte >>> encoded string. Read the XML spec. >>> >>> It would be well-formed if you added the proper XML declaration, but that is >>> system specific (UCS-4 or UTF-16, BE or LE). So don't even try. >> >> Who cares? I'm not calling any external tools. > > XML cares. If you want to work with something that is not XML, do not expect > XML tools to help you do it. XML tools work with XML, and there is a spec that > says what XML is. Your string is not XML. This isn't some sophisticated XML tool that tells me the string is wrong. It's a changed behavior of cStringIO that throws an exception. While I'm just using the method parseString() of xml.sax. We both repeat ourselves. I don't think this thread brings something new. I'm all for correct XML and hate XML bozos. But there are limits you have to learn after a few years. From ajsavige at yahoo.com.au Sun Jul 29 00:46:10 2007 From: ajsavige at yahoo.com.au (Andrew Savige) Date: Sun, 29 Jul 2007 14:46:10 +1000 (EST) Subject: Split a string based on change of character Message-ID: <961864.60438.qm@web56405.mail.re3.yahoo.com> Python beginner here. For a string 'ABBBCC', I want to produce a list ['A', 'BBB', 'CC']. That is, break the string into pieces based on change of character. What's the best way to do this in Python? Using Python 2.5.1, I tried: import re s = re.split(r'(?<=(.))(?!\1)', 'ABBBCC') for e in s: print e but was surprised when it printed: ABBBCC I expected something like: A A BBB B CC C (the extra fields because of the capturing parens). Thanks, /-\ ____________________________________________________________________________________ Yahoo!7 Mail has just got even bigger and better with unlimited storage on all webmail accounts. http://au.docs.yahoo.com/mail/unlimitedstorage.html From llansteffan at hotmail.com Fri Jul 13 08:39:47 2007 From: llansteffan at hotmail.com (justme) Date: Fri, 13 Jul 2007 12:39:47 -0000 Subject: scripts into wxPython Message-ID: <1184330387.066920.109250@n60g2000hse.googlegroups.com> Hello I've been happily scripting away for the last few years (Matlab, now Python) and all has been fine. Now I find myself scripting up code for clients, but they all want a nice GUI. I've had a tinker with wxPython and it all seems standard enough but I was wondering if anyone has any comments about how easy it is to shoehorn some fairly complex scripts into a GUI so that non-scripters can use the code. I assume I'll need to recode up all the input outputs? Any thoughts, or should I have started GUI programming right at the outset! Cheers From timr at probo.com Wed Jul 4 01:40:50 2007 From: timr at probo.com (Tim Roberts) Date: Wed, 04 Jul 2007 05:40:50 GMT Subject: How can i change an Object type ? References: <1183516235.774875.45710@q69g2000hsb.googlegroups.com> Message-ID: KuhlmannSascha wrote: > >i tried now for several hours to read through a win32com API to access >Itunes and read out myplaylists. > >First of all the Code: >... >The current Logic is to access first Itunes and then a Playlist >Collection. >This Playlist collection returns different kind of objects for >Playlists. >I am focussing on the Playlists of the object UserPlaylist. >(CodeLine: if curPlaylist.Kind == 2:) >After that i should be sure to have a UserPlaylist, but Python stops >with an exception that the requested Attribute "Smart" is not >available >Error MEssage: >AttributeError: 'instance at 0x30216960>' object has no attribute 'Smart' Smart is part of IITUserPlaylist, not IITPlaylist. You need to call curPlaylist.QueryInterface to get the IITUserPlaylist, but that means you'll need to know the GUID for IITUserPlaylist. Perhaps Google will help. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bj_666 at gmx.net Fri Jul 6 19:21:00 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 6 Jul 2007 23:21:00 GMT Subject: Repeating Thread Error References: <1183758016.776354.241620@g4g2000hsf.googlegroups.com> Message-ID: <5f812rF3b25tsU6@mid.uni-berlin.de> On Fri, 06 Jul 2007 14:40:16 -0700, Jonathan Shan wrote: > I am trying to call a function every 5 seconds. My understanding of > time.sleep() is during the sleep time everything "stops". Not "everything", just the thread in which `sleep()` is called. > However, in my application, there are background processes that must be > running continuously during the five second interval. Then start them as threads and they will run all the time. > Thus, threading.Timer seems like a good function. Here is the relevant > code: > > # background processes > t = threading.Timer(5.0, function_name, [arguments]) > while True: > # Do background processes run inside while loop? > t.start() > > The above code generates an error: > AssertionError: thread already started > > Any hints on how to fix the error? A thread can only be started once but you try to start the `Timer` over and over. And you don't wait, so even if this would "work" you would start many, many `Timer`\s as fast as the ``while`` loop runs. The `Timer`\s would all run the function after five seconds. It's like:: while True: function_name(*arguments) just with a five second delay. > Also, do background processes run inside while loops? This question doesn't make much sense to me. Do ``while`` loops block other threads? No of course not. Ciao, Marc 'BlackJack' Rintsch From orsenthil at users.sourceforge.net Mon Jul 16 15:03:19 2007 From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran) Date: Tue, 17 Jul 2007 00:33:19 +0530 Subject: urllib to cache 301 redirections? In-Reply-To: <87wsxds6sq.fsf@pobox.com> References: <87wsxds6sq.fsf@pobox.com> Message-ID: <20070716190319.GA7184@gmail.com> Thank you for the reply, Mr. John and I apologize for a very late response from my end. * John J. Lee [2007-07-06 18:53:09]: > "O.R.Senthil Kumaran" writes: > > > Hi, > > There is an Open Tracker item against urllib2 library python.org/sf/735515 > > > I am not completely getting what "cache - redirection" implies and what should > > be done with the urllib2 module. Any pointers? > > When a 301 redirect occurs after a request for URL U, via > urllib2.urlopen(U), urllib2 should remember the result of that > redirection, viz a second URL, V. Then, when another > urllib2.urlopen(U) takes place, urllib2 should send an HTTP request > for V, not U. urllib2 does not currently do this. (Obviously the > cache -- that is, the dictionary or whatever that stores the mapping > from URLs U to V -- should not be maintained by function urlopen > itself. Perhaps it should live on the redirect handler.) > I spent a little time thinking about a solution and figured out that the following changes to HTTPRedirectHandler, might be helpful in implementing this. Class HTTPRedirectHandler(BaseHandler): # ... omitted ... # Initialize a dictionary to hold cache. def __init__(self): self.cache = {} # Handles 301 errors separately in a different function which maintains a # maintains cache. def http_error_301(self, req, fp, code, msg, headers): if req in self.cache: # Look for loop, if a particular url appears in both key and value # then there is loop and return HTTPError if len(set(self.cache.keys()) & set(self.cache.values())) > 0: raise HTTPError(req.get_full_url(), code, self.inf_msg + msg + headers, fp) return self.cache[req] self.cache[req] = self.http_error_302(req,fp,code,msg, headers) return self.cache[req] John, let me know your comments on this approach. I have not tested this code in real scenario yet with a 301 redirect. If its okay, I shall test it and submit a patch for the tracker item. Thanks, Senthil -- O.R.Senthil Kumaran http://uthcode.sarovar.org From ladaan at iptel.org Thu Jul 12 15:01:00 2007 From: ladaan at iptel.org (Ladislav Andel) Date: Thu, 12 Jul 2007 21:01:00 +0200 Subject: lists and dictionaries In-Reply-To: <1184250011.187346.70470@r34g2000hsd.googlegroups.com> References: <1184184582.330491.326600@e9g2000prf.googlegroups.com> <1184208542.948772.50700@w3g2000hsg.googlegroups.com> <1184250011.187346.70470@r34g2000hsd.googlegroups.com> Message-ID: <46967A6C.3000002@iptel.org> Thank you to all of you guys. It's exactly I was looking for. > You provide scant information for this task. For example, is the > new list ordered or unordered? Can the list corresponding to the > 'transports' key contain duplicates? > unordered is fine.. I will be storing it in DB from that list. It should not happen to get 'transports' duplicates in my application. It's for testing domains where are running SIP servers. Lada Bart Ogryczak wrote: > On 12 jul, 04:49, anethema wrote: > >>> li = [ {'index': 0, 'transport': 'udp', 'service_domain': >>> 'dp0.example.com'}, >>> {'index': 1, 'transport': 'udp', 'service_domain': >>> 'dp1.example.com'}, >>> {'index': 0, 'transport': 'tcp', 'service_domain': >>> 'dp0.example.com'}, >>> {'index': 1, 'transport': 'tcp', 'service_domain': >>> 'dp1.example.com'}] >>> >> I like this solution: >> >> [{ 'transports' : [d['transport'] for d in li if >> d['service_domain'] == dom], >> 'service_domain': dom, >> } for dom in set(d2['service_domain'] for d2 in li)] >> >> merely because it takes one line. Humorously enough, it appears to be >> twice as efficient, >> > > Correct me if I?m wrong, that is a O(n**2) solution, to O(n) problem. > > From dlomsak at gmail.com Sun Jul 1 00:18:41 2007 From: dlomsak at gmail.com (dlomsak) Date: Sat, 30 Jun 2007 21:18:41 -0700 Subject: object references/memory access In-Reply-To: <7xps3c93b2.fsf@ruckus.brouhaha.com> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <7xps3c93b2.fsf@ruckus.brouhaha.com> Message-ID: <1183263521.729853.22430@q75g2000hsh.googlegroups.com> Paul Rubin wrote: > dlomsak writes: > > knowledge of the topic to help. If the above are not possible but you > > have a really good idea for zipping large amounts of data from one > > program to another, I'd like to hear it. > > One cheesy thing you might try is serializing with marshal rather than > pickle. It won't handle as many object types, and it's not guaranteed > interoperable from one Python version to another, but it's potentially > faster than pickle. Of course for pickling I presume you're already > using cPickle (written in C) instead of Pickle (written in Python). Well, I was using the regular pickle at first but then I switched to just using repr() / eval() because the resulting string doesn't have all the extra 's1=' and all that so it cuts down on the amount of data I have to send for large returns when you cut out all of that formatting. The speed of the above method is pretty high even for really large returns and it works fine for a list of dictionaries. To the previous poster: I'll be looking into C shared memory like you said. I have a feeling C will let me lay my hands on the things I want and that Python probably will not. That's fine though because Python is a wonderful language and I don't mind calling in tedious C to do the real dirty jobs if that is what it takes. From ptmcg at austin.rr.com Mon Jul 9 13:07:30 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 09 Jul 2007 10:07:30 -0700 Subject: compressing consecutive spaces In-Reply-To: <1183991894.508562.16430@g4g2000hsf.googlegroups.com> References: <1183991894.508562.16430@g4g2000hsf.googlegroups.com> Message-ID: <1184000850.349697.140740@k79g2000hse.googlegroups.com> On Jul 9, 9:38 am, Beliavsky wrote: > How can I replace multiple consecutive spaces in a file with a single > character (usually a space, but maybe a comma if converting to a CSV > file)? Ideally, the Python program would not compress consecutive > spaces inside single or double quotes. An inelegant method is to > repeatedly replace two consecutive spaces with one. Split with no arguments splits on whitespace, and multiple spaces count as but a single separator. So split+join = collapsed whitespace. >>> test = "a b c d efdd slkj sdfdsfl" >>> " ".join(test.split()) 'a b c d efdd slkj sdfdsfl' Or use something other than " " to join with, such as ",". >>> ",".join(test.split()) 'a,b,c,d,efdd,slkj,sdfdsfl' -- Paul From jeddrury at yahoo.com Thu Jul 26 14:18:10 2007 From: jeddrury at yahoo.com (jed drury) Date: Thu, 26 Jul 2007 11:18:10 -0700 (PDT) Subject: Fwd: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: <4b490f2f0707260810qe4a410co366291a6dccd4f01@mail.gmail.com> Message-ID: <611885.63070.qm@web36213.mail.mud.yahoo.com> Hey, Perl's new motto is "There is more than 1 way to be an ASSHOLE!" ____________________________________________________________________________________ Fussy? Opinionated? Impossible to please? Perfect. Join Yahoo!'s user panel and lay it on us. http://surveylink.yahoo.com/gmrs/yahoo_panel_invite.asp?a=7 From jurgenex at hotmail.com Wed Jul 25 18:20:34 2007 From: jurgenex at hotmail.com (Jürgen Exner) Date: Wed, 25 Jul 2007 22:20:34 GMT Subject: I am giving up perl because of assholes on clpm -- switching to Python References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> Message-ID: Martha_Jones at tx.net wrote: > 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!!! Considering that your total posting history according to DejaNews consists of exactly 3 posts (not including this last one) from 2001 to 2003 in NGs that are so closely related to programming as pregnancy, marriage, and cancer I believe the last sentiment is very mutual. After all, you didn't ever leave any trace in CLPM until today. jue From python27email at yahoo.com Sat Jul 14 02:12:17 2007 From: python27email at yahoo.com (python27email at yahoo.com) Date: Sat, 14 Jul 2007 06:12:17 -0000 Subject: installation problems on mac powerpc In-Reply-To: <1184390479.885895.179720@q75g2000hsh.googlegroups.com> References: <1184390479.885895.179720@q75g2000hsh.googlegroups.com> Message-ID: <1184393537.142616.249140@q75g2000hsh.googlegroups.com> On Jul 14, 1:21 am, python27em... at yahoo.com wrote: > interested in nltk installation on a mac osx 10.4.9 > > however when try to install latest python > > get error cannot access subprocesses and won't even open idle > got nltk to open through a terminal but entire process I fear is > fragmented > > is there a better walk through of installation than what I've found on > sourceforge? > > Any suggestions? rebooting has resolved the above for now how can I be sure numpy is installed correctly? same with matplotlib? what is python launcher and should I make it my default python scripts From kyosohma at gmail.com Mon Jul 2 15:18:08 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 02 Jul 2007 12:18:08 -0700 Subject: need help with win32com In-Reply-To: References: Message-ID: <1183403888.139075.127630@q69g2000hsb.googlegroups.com> On Jul 2, 11:38 am, Thomas wrote: > I want to be able to access an excel file and extract the code from > the macro that is in the file. How can I do this? > > -- > ~Thomas~ You should be able to use PythonWin and the makepy utility to get handles to the Excel object. See the following article: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html I also found an article on how to use Python as the scripting language in Excel: http://www.velocityreviews.com/forums/t319222-re-python-in-excel.html Mike From arkanes at gmail.com Thu Jul 12 14:33:39 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 12 Jul 2007 13:33:39 -0500 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <468565a0$0$3686$426a74cc@news.free.fr> <7xvecumrte.fsf@ruckus.brouhaha.com> <1i13w96.kyyobph71qxrN%aleax@mac.com> <7xwsx63we6.fsf@ruckus.brouhaha.com> <878x9llv5x.fsf@benfinney.id.au> Message-ID: <4866bea60707121133p536eb9afvb1d54514d776e5ec@mail.gmail.com> On 7/12/07, Donn Cave wrote: > In article <878x9llv5x.fsf at benfinney.id.au>, > Ben Finney wrote: > > > Paul Rubin writes: > > > > > The idea of designing languages with more and more support for > > > ensuring program correctness is to put the established, repetitive > > > processes into the computer where it belongs, freeing the programmer > > > to be innovative while still providing high assurance of that the > > > program will be right the first time. > > > > This seems to make the dangerous assumption that the programmer has > > the correct program in mind, and needs only to transfer it correctly > > to the computer. > > > > I would warrant that anyone who understands exactly how a program > > should work before writing it, and makes no design mistakes before > > coming up with a program that works, is not designing a program of any > > interest. > > I don't get it. Either you think that the above mentioned support > for program correctness locks program development into a frozen > stasis at its original conception, in which case you don't seem to > have read or believed the whole paragraph and haven't been reading > much else in this thread. Certainly up to you, but you wouldn't be > in a very good position to be drawing weird inferences as above. > > Or you see original conception of the program as so inherently > suspect, that random errors introduced during implementation can > reasonably be seen as helpful, which would be an interesting but > unusual point of view. > You can't prove a program to be correct, in the sense that it's proven to do what it's supposed to do and only what it's supposed to do. You can prove type-correctness, and the debate is really over the extent that a type-correct program is also behavior-correct. Personally, I remain unconvinced, but am open to evidence - I've only heard anecdotes which are readily discounted by other anecdotes. I absolutely do not believe that pure functional style programming, where we shun variables, is the best model for computing, either now or in the future. From jarausch at igpm.rwth-aachen.de Wed Jul 11 07:15:42 2007 From: jarausch at igpm.rwth-aachen.de (Helmut Jarausch) Date: Wed, 11 Jul 2007 13:15:42 +0200 Subject: Simple search and Display system, no need for db? In-Reply-To: <1184119048.302574.141810@w3g2000hsg.googlegroups.com> References: <1184119048.302574.141810@w3g2000hsg.googlegroups.com> Message-ID: <4694BBDE.9000603@igpm.rwth-aachen.de> flit wrote: > Hello All, > > I was discussing with a friend and we get in a hot debate. > > We have homepage that act like a name list. > > The user goes there: > > - Choose the building -- Department and the user receive an html table > with all names . > > So the user gives two inputs and receive the names. > > Currently we are using this in mysql, This is the reason of the > debate. > > If our list will never change and we are supposing that will be true > for a long time, is it not too much use an mysql? > > Which kind of structure can we use in python? in web? > What about using a simple dictionary in Python. You can use the module pickle (or cpickle) to dump it to disk and load it next time. Furthermore you can easily write the whole web server in Python, e.g. I like http://karrigell.sourceforge.net/ -- Helmut Jarausch Lehrstuhl fuer Numerische Mathematik RWTH - Aachen University D 52056 Aachen, Germany From ladynikon at gmail.com Sat Jul 21 01:57:52 2007 From: ladynikon at gmail.com (Danyelle Gragsone) Date: Sat, 21 Jul 2007 01:57:52 -0400 Subject: Spam filter? Message-ID: <59f9c5160707202257x221ffdddh345326c8861da4fe@mail.gmail.com> So, Can mailing lists have its mail filtered? I get more spam via mailing lists than I do in my own inbox. I am not just singling this mailing list. I see it a lot now. Danyelle From steve at holdenweb.com Mon Jul 30 11:31:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Jul 2007 11:31:42 -0400 Subject: Detecting __future__ features In-Reply-To: <1i22ic1.mkdgv718veezaN%raims@dot.com> References: <1i22ic1.mkdgv718veezaN%raims@dot.com> Message-ID: Lawrence Oluyede wrote: > Steven D'Aprano wrote: >> Is there any general mechanism? > > I'd just use the expected future feature and if the result is not what I > expect (or Python raises any kind of exception, like using a keyword not > present) I'd think I'm in the past :-) > Of course if the use of the feature creates a syntax error in the __main__ module (as it might currently for a use of the "with" keyword in 2.5, for example) then there is no way to catch the exception and you are therefore SOL, no? sholden at bigboy ~/Projects/Python $ cat test11.py with open("myfile.txt") as f: print l for l in f sholden at bigboy ~/Projects/Python $ python test11.py test11.py:1: Warning: 'with' will become a reserved keyword in Python 2.6 File "test11.py", line 1 with open("myfile.txt") as f: ^ SyntaxError: invalid syntax 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 Jul 25 06:04:21 2007 From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com) Date: Wed, 25 Jul 2007 03:04:21 -0700 Subject: code indentation In-Reply-To: <87lkd5jt83.fsf@benfinney.id.au> References: <1185297657.186852.136950@k79g2000hse.googlegroups.com> <87lkd5jt83.fsf@benfinney.id.au> Message-ID: <1185357861.989194.117000@r34g2000hsd.googlegroups.com> On 25 srp, 01:07, Ben Finney wrote: > Steve Holden writes: > > vedrandeko... at v-programs.com wrote: > > > On 24 srp, 05:20, "Gabriel Genellina" wrote: > > >> En Mon, 23 Jul 2007 16:53:01 -0300, ...:::JA:::... > > >> escribi?: > > >>> So......how can I do this????????????? > > >>> I will appreciate any help!!!!! > > >> Try with a simple example. Let's say you want to convert this: > > >> [...] > > > [...] Can you give me some example script of this? Please!!! > > > > PS: THANKS FOR YOUR TIME!!!!!!!!!! > > > It's unfortunate that you are having difficulty with two languages > > simultaneously: your command of English, though impressive, appears > > to be insufficient for you to explain the problem [...] > > And while we're on the topic of communication: The original poster > would do well to learn that increasing the number of consecutive > punctuation marks (!!!, ???) is a sure way to turn away many people > who would otherwise be helpful. Sentences need at most one '!' or '?', > adding more does not improve the chances of being taken seriously. > > -- > \ "We have to go forth and crush every world view that doesn't | > `\ believe in tolerance and free speech." -- David Brin | > _o__) | > Ben Finney Hi, I was only ask for help becose I don't understand this tokenize module so well. And if you can help me than please help me , but if you can't then please don't leave me some stupid messages Regards, Vedran From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Jul 21 05:59:41 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 21 Jul 2007 11:59:41 +0200 Subject: Permutations with generators References: <1184996537.069416.211730@g4g2000hsf.googlegroups.com> Message-ID: <5ge3odF3fk7i6U1@mid.individual.net> Pablo Torres wrote: > AttributeError: 'NoneType' object has no attribute 'insert' > > Could somebody please explain to me why my p variable has no type > at all? It does have a type, NoneType. As already explained, only None normally is of type NoneType. Regards, Bj?rn -- BOFH excuse #281: The co-locator cannot verify the frame-relay gateway to the ISDN server. From jjl at pobox.com Wed Jul 11 18:30:46 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 11 Jul 2007 22:30:46 GMT Subject: Passing a CookieJar instead of a cookieproc to urllib2.build_opener References: <1184028331.849197.263130@g4g2000hsf.googlegroups.com> <873azvg8il.fsf@pobox.com> <1184172043.009591.168890@w3g2000hsg.googlegroups.com> Message-ID: <87644qwp2h.fsf@pobox.com> "rrenaud at gmail.com" writes: [...] > Are the docs themselves in subversion? I suppose I should also update > the doc at http://docs.python.org/lib/module-urllib2.html Yep: http://svn.python.org/projects/python/trunk/Doc/lib/liburllib2.tex John From Larry.Martell at gmail.com Thu Jul 19 16:23:35 2007 From: Larry.Martell at gmail.com (Larry.Martell at gmail.com) Date: Thu, 19 Jul 2007 20:23:35 -0000 Subject: UDP broadcast over a specific interface In-Reply-To: References: <1184848322.796960.121950@q75g2000hsh.googlegroups.com> Message-ID: <1184876615.343876.178310@o61g2000hsh.googlegroups.com> On Jul 19, 7:09 am, Jean-Paul Calderone wrote: > On Thu, 19 Jul 2007 12:32:02 -0000, "Larry.Mart... at gmail.com" wrote: > >I am trying to send UDP broadcast packets over a specific interface > >and I > >am having trouble specifying the interface: > > >host='192.168.28.255' > >sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > >sock.bind(('',0)) > >sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) > >sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF, > >socket.inet_aton(host)) > > >socket.error: (49, "Can't assign requested address") > > >What am I doing wrong? How can I force my broadcast packets to go out > >a specific interface? > > IP_MULTICAST_IF is for multicast UDP, which doesn't have anything to do > with broadcast UDP. > > Try just doing this, instead: > > host='192.168.28.255' > sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) > sock.bind((host,0)) > sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) > > You shouldn't need to mess with anything beyond that. Thanks! This works perfectly. -larry From horpner at yahoo.com Wed Jul 25 15:42:53 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Wed, 25 Jul 2007 19:42:53 GMT Subject: is_iterable function. References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> <5gplj6F3gg2e0U3@mid.uni-berlin.de> Message-ID: <1JNpi.36823$G23.14657@newsreading01.news.tds.net> On 2007-07-25, Marc 'BlackJack' Rintsch wrote: > So there's no reliable way to test for "iterables" other than > actually iterate over the object. A TypeError exception is perhaps too generic for comfort in this use case: def deeply_mapped(func, iterable): for item in iterable: try: for it in flattened(item): yield func(it) except TypeError: yield func(item) I'd be more confortable excepting some sort of IterationError (or using an is_iterable function, of course). I guess there's always itertools. ;) -- Neil Cerutti From anadajames at gmail.com Fri Jul 27 10:31:56 2007 From: anadajames at gmail.com (Ana James) Date: Fri, 27 Jul 2007 07:31:56 -0700 Subject: =?utf-8?B?4peY4pa6TGVnYWxseSBBY2Nlc3MgRlJFRSBTYXRlbGxpdGUgVFYgb24geW91ciBQQ+KXhOKXmA==?= Message-ID: <1185546716.281154.131520@d30g2000prg.googlegroups.com> Access 1000's of Television Channels From All Over The World 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 Learn More About it at Link below: http://freetvonpc.50webs.com/ From steve at holdenweb.com Sun Jul 22 09:04:08 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 22 Jul 2007 09:04:08 -0400 Subject: Pickled objects over the network In-Reply-To: <00c601c7cc38$d826ba00$03000080@hendrik> References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com><011401c7caa0$3e3e5900$03000080@hendrik> <012901c7cb60$5ba530c0$03000080@hendrik> <00c601c7cc38$d826ba00$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "Steve Holden" wrote: > >> I think someone has already pointed out netstrings, which will allow you >> to send arbitrary strings over network connections deterministically. > > Yes I brought it up > >> I'm afraid for the rest it's just a matter of encoding your information >> in a way that you can decode without allowing a malicious sender to >> cause arbitrary code to be called. > > Yes - and in general you do this by having both the sender and the > transmitter conform to some pre agreed format - a netstring is one > of the simplest of such things - another way is to "frame" records > between some kind of delimeter and to "escape" the occurences of the > delimiter in the data. Another way is to use simple "self defining fields" > that work by giving fields a "tag" number from a list of pre defined > things, as well as a length, followed by the data - some financial > protocols work as a variant of this concept, where the presence or > absence of a bit signify the presence or absence of a field in the record. > > The problem with all of these schemes is that they are all a PITA to > implement, compared to the ease with which you can pickle and > unpickle something like a simple dict of parameters. > > And if that is all you want to pass over to some remote thing, then > having to download and import Pyro is an equal PITA and overkill. > - It adresses a far more sophisticated problem than just getting > some small things across the network. > > Now if Pyro were to make it into the standard library, it would be > my method of choice for even this silly level of functionality, > because I happen to think it rocks. > >> The issue with pickle is that it's way too general a mechanism to be >> secure in open network applications, so a suggestion to beef up its >> security was misguided. Trying to "beef up pickle's security" is like >> trying to make a shotgun that can't kill anything. >> > > Is it really that impossible to add something like a "noeval" flag, or to > force it to only give you a string or a dict if you ask for one or the other, > given that someone has already mentioned that the built in types are > decoded by separate routines? > > Or more generally - as it already has different protocols - to define a > protocol that won't pass executable stuff over, or one that will only > pass and accept the built in types? > Yes. 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 bsneddon at yahoo.com Sun Jul 8 13:46:44 2007 From: bsneddon at yahoo.com (bsneddon) Date: Sun, 08 Jul 2007 10:46:44 -0700 Subject: Validating XML in Windows In-Reply-To: <46910F44.8090506@web.de> References: <46910F44.8090506@web.de> Message-ID: <1183916804.165539.119980@22g2000hsm.googlegroups.com> On Jul 8, 12:22 pm, Stefan Behnel wrote: > Omari Norman wrote: > > My app needs to validate XML. That's easy enough in Unix. What is the > > best way to do it in Windows? > > > The most obvious choice would of course be PyXML. However, apparently it > > is no longer maintained: > > >http://sourceforge.net/project/showfiles.php?group_id=6473 > > > so there are no Windows binaries that work with Python 2.5. Getting > > other XML libraries like libxml2 also seems to be quite difficult on > > Windows. > > > Has anyone else dealt with this problem and found a solution? It would > > even be fine if I could find a free command-line validator that I could > > invoke with subprocess, but I haven't even had luck with that. > > lxml has statically built Windows binaries available for version 1.2.1, those > for 1.3.2 should become available soon. It supports RelaxNG, XMLSchema, DTDs > and (with a little patching) Schematron. > > http://codespeak.net/lxml/ > > Stefan You might try something like this. I am sure you can find help on MSDN. I know DOM may not be most efficient but could be a way to solve the problem on windows. >>> import win32com.client >>> >>> import win32com.client >>> objXML = win32com.client.Dispatch("MSXML2.DOMDocument.3.0") >>> objXML.load(r'C:\data\pyexamples\xml\acro.xml') True # not sure how to load schema but there must be away >>> objXML.validate() From mick at cs.wisc.edu Mon Jul 23 19:22:11 2007 From: mick at cs.wisc.edu (Mick Charles Beaver) Date: 23 Jul 2007 23:22:11 GMT Subject: pylint style convention Message-ID: <46a53823$0$3769$80265adb@spool.cs.wisc.edu> Hello, I've been looking into using PyLint on some of my programs, just as a best practices kind of thing. Here's a snippet: #====================================================================== if __name__ == '__main__': parser = optparse.OptionParser(usage='usage: %prog [OPTIONS]') parser.add_option('-c', '--config', action='store', type='string', dest='configFilename', help='config file containing defaults') (options, args) = parser.parse_args() #====================================================================== Now, PyLint reports the following convention warnings: C:158: Invalid name "parser" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) C:170: Invalid name "options" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) C:170: Invalid name "args" (should match (([A-Z_][A-Z1-9_]*)|(__.*__))$) Which style convention is it referring to? Should these really be all caps? Thank you, Mick From bdesth.quelquechose at free.quelquepart.fr Thu Jul 19 00:43:04 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 19 Jul 2007 06:43:04 +0200 Subject: Weird errors when trying to access a dictionary key In-Reply-To: <1184956573.702959.96400@d30g2000prg.googlegroups.com> References: <1184956573.702959.96400@d30g2000prg.googlegroups.com> Message-ID: <46a2121c$0$32485$426a74cc@news.free.fr> robinsiebler at gmail.com a ?crit : > I have a data structure that looks like this: > (snip) > > I get the following error: (snip) > AttributeError: 'list' object has no attribute 'keys' Already answered. > Here is where it gets weird: > > type(song) (snip) > TypeError: 'str' object is not callable You code snippet started with: if type == 'artist': which implies you bound the name 'type' to a string. Then you try to use the object bound to name 'type' as a callable. Python's bindings are just name=>object mappings, and nothing prevents you to rebind a builtin name. IOW, avoid using builtins types and functions as identifiers. HTH From josiah.carlson at sbcglobal.net Thu Jul 19 11:29:55 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Thu, 19 Jul 2007 15:29:55 GMT Subject: wxPython and threads In-Reply-To: References: <1184726489.112138.96350@z28g2000prd.googlegroups.com> Message-ID: Nick Craig-Wood wrote: > Josiah Carlson wrote: >> Sending results one at a time to the GUI is going to be slow for any >> reasonably fast search engine (I've got a pure Python engine that does >> 50k results/second without breaking a sweat). Don't do that. Instead, >> have your search thread create a list, which it fills with items for >> some amount of time, *then* sends it off to the GUI thread (creating a >> new list that it then fills, etc.). While you *could* use a Queue, it >> is overkill for what you want to do (queues are really only useful when >> there is actual contention for a resource and you want to block when a >> resource is not available). > > I'd dispute that. If you are communicating between threads use a > Queue and you will save yourself thread heartache. Queue has a non > blocking read interface Queue.get_nowait(). If you have one producer and one consumer, and the consumer will be notified when there is an item available, AND deques (in Python 2.4, 2.5, and presumably later) are threadsafe, then the *additional* locking, blocking, etc., that a Queue provides isn't necessary. Whether one wants to use a Queue for 'piece of mind', or for future expansion possibilities is another discussion entirely, but his application (as stated) will work with a deque for the worker thread -> GUI thread communication path. - Josiah From org.python.python-list at pooryorick.com Thu Jul 12 23:13:47 2007 From: org.python.python-list at pooryorick.com (Poor Yorick) Date: Thu, 12 Jul 2007 23:13:47 -0400 Subject: access to the namespace of a function from within its invocation Message-ID: <4696EDEB.1050406@pooryorick.com> In the example below, the attribute "data" is added to a function object. "me" can be used to get the function when it is invoked using an identifier that matches the "co_name" attribute of function's code object. Can anyone conjure an example of accessing fun2.data from without prior knowledge of the value of fun2.f_code.co_name? ###code begin### #!/bin/python import sys def me(): t = sys._getframe(0) return t.f_back.f_globals[t.f_back.f_code.co_name] def fun1(): m = me print me().data def makefun () : def tmpfunc(): print 'need something like me().data' return tmpfunc fun1.s = fun1 fun1.data=['one', 'two', 'three'] fun1() fun2 = makefun() fun2.data=['four', 'five','six'] fun2() ###code end### -- Poor Yorick From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jul 11 10:42:39 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 11 Jul 2007 16:42:39 +0200 Subject: bool behavior in Python 3000? In-Reply-To: References: Message-ID: <4694ec41$0$10948$426a74cc@news.free.fr> Steven D'Aprano a ?crit : (snip) > I mean, really, does anyone *expect* True+True to give 2, or that 2**True > even works, I may be biased since I learned C before Python and learned Python before it had a Boolean type, but I'd think that having False==0 and True==1 is not that surprising for most programmers. > without having learnt that Python bools are ints? I doubt it. > > And the old Python idiom for an if...then...else expression: > > ["something", "or other"][True] > > tends to come as a great surprise to most newbies. This idiom should slowly disappear now we have a clean syntax for such expressions. > So I would argue that > bools being ints is more surprising than the opposite would be. I suppose this mostly have to do with one's background. From zyzhu2000 at gmail.com Fri Jul 27 18:14:31 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 27 Jul 2007 22:14:31 -0000 Subject: Another C API Question In-Reply-To: References: <1185498383.333248.225360@19g2000hsx.googlegroups.com> <1185545488.751250.200270@z24g2000prh.googlegroups.com> <1185571136.628131.168260@z24g2000prh.googlegroups.com> Message-ID: <1185574471.541932.325700@z28g2000prd.googlegroups.com> On Jul 27, 4:50 pm, Farshid Lashkari wrote: > beginner wrote: > > I did and it did not seem to work. I ended up doing the following. > > Verbose, isn't it? > > If I do d=PyFloat_AsDouble(oDiscount); in the third "if", I get an > > error. Maybe I missed something obvious. > > That's strange. I just tried the following code: > > fprintf(stdout,"True = %lf\n",PyFloat_AsDouble(Py_True)); > fprintf(stdout,"False = %lf\n",PyFloat_AsDouble(Py_False)); > fprintf(stdout,"5 = %lf\n",PyFloat_AsDouble(PyInt_FromLong(5))); > > And it printed the following: > > True = 1.000000 > False = 0.000000 > 5 = 5.000000 > > What version of Python are you using? Interesting. Let me try it again. I definitely want to remove the intermediate step that creates a temporary Py object. Well, Python is probably doing it internally anyway, but at least I don't have to see it. :-) From willmaier at ml1.net Fri Jul 20 18:47:46 2007 From: willmaier at ml1.net (Will Maier) Date: Fri, 20 Jul 2007 17:47:46 -0500 Subject: Sorting dict keys In-Reply-To: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> Message-ID: <20070720224746.GY12728@lass.lfod.us> On Fri, Jul 20, 2007 at 03:27:51PM -0700, montyphyton at gmail.com wrote: > Consider the following: > >>> a = {1:2, 3:4, 2:5} > > Say that i want to get the keys of a, sorted. First thing I tried: > > >>> b = a.keys().sort() > >>> print b > None list's sort() method sorts the list _in_place_: >>> l = ['spam', 'eggs'] >>> help(l.sort) Help on built-in function sort: sort(...) L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*; cmp(x, y) -> -1, 0, 1 That means that doesn't return a sorted version of the list you're working with. Instead, it sorts the list itself. If you want to return a sorted list, use (duh) sorted: >>> sorted(l) ['eggs', 'spam', 'spam'] -- [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] From bdesth.quelquechose at free.quelquepart.fr Sun Jul 22 01:02:58 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 22 Jul 2007 07:02:58 +0200 Subject: class C: vs class C(object): In-Reply-To: References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> <469f1557$0$26759$426a74cc@news.free.fr> <46a082ed$0$431$426a74cc@news.free.fr> Message-ID: <46a7a7a5$0$10092$426a74cc@news.free.fr> Aahz a ?crit : (snip) > Enh. *All* of the standard Python documentation currently starts with > teaching classic classes, (snip) > There is almost no basic documentation > that starts with new-style classes; (snip) Just for the record: http://docs.python.org/ref/node33.html http://www.python.org/doc/newstyle/ From lew at lewscanon.nospam Sun Jul 8 08:50:43 2007 From: lew at lewscanon.nospam (Lew) Date: Sun, 08 Jul 2007 08:50:43 -0400 Subject: The Modernization of Emacs: terminology buffer and keybinding In-Reply-To: <1183856442.027967.272530@g4g2000hsf.googlegroups.com> References: <1182093200.598418.218620@e9g2000prf.googlegroups.com> <1182272495.990807.99110@a26g2000pre.googlegroups.com> <87tzt3ihev.fsf@kobe.laptop> <1182370216.961241.6960@n60g2000hse.googlegroups.com> <85zm2ufjpb.fsf@lola.goethe.zz> <1182372592.803332.288260@u2g2000hsc.googlegroups.com> <1182373919.262388.100740@c77g2000hse.googlegroups.com> <85r6o6fhkb.fsf@lola.goethe.zz> <1182375045.626510.188170@m36g2000hse.googlegroups.com> <85myyufgwj.fsf@lola.goethe.zz> <1182375528.985142.293900@q69g2000hsb.googlegroups.com> <1182545268.055596.228700@i38g2000prf.googlegroups.com> <1183841277.333384.188950@g4g2000hsf.googlegroups.com> <1183856442.027967.272530@g4g2000hsf.googlegroups.com> Message-ID: <1_adnQOkD9Y-QA3bnZ2dneKdnZydnZ2d@comcast.com> Twisted wrote: > On Jul 7, 6:12 pm, Lew wrote: >> Twisted wrote: >> Edward Dodge wrote: >>>> So -- what magical computer app illuminates the entire room and shows >>>> you how to use everything at the flip of a switch? This brilliant >>>> discovery would put Sam's, O'Reilly, the for-Dummies series, and >>>> virtually every other computer book publisher out of business in weeks. >>>> Naturally, this would include the publishers of books on "easy-to-use" >>>> Microsoft products. >>> I don't know, but it sure as hell isn't emacs. >> The reason you don't know, and Edward Dodge's point, is that there is no such >> app, whether emacs or not. > > Translation: since perfection is unattainable, we shouldn't even try, > and just foist upon our poor users whatever awkward and hard-to-learn > interface pops into our heads first? Nice rhetoric but completely twisted the point. Blaaaat! -- Lew From mail at microcorp.co.za Sat Jul 14 03:01:22 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 14 Jul 2007 09:01:22 +0200 Subject: Can a low-level programmer learn OOP? References: Message-ID: <01a301c7c5ee$69025f80$03000080@hendrik> "Chris Carlen" wrote: > Form 2: Use Python and PySerial and TkInter or wxWidgets. > > Pro: Cross-platform goal will likely be achieved fully. Have a > programmer nearby with extensive experience who can help. > Con: Must learn new language and library. Must possibly learn a > completely new way of thinking (OOP) not just a new language syntax. > This might be difficult. > This is the way to go. - Trust me on this. When you describe your history, it is almost an exact parallel to mine. In my case, I have been doing real low level stuff (mostly 8031 assembler) since 1982 or so. And then I found python in a GSM module (Telit), and I was intrigued. I really appreciate your comments on OO - it parallels a lot of what I feel as there is a lot of apparent BS that does not seem to "do anything" at first sight. However- for the GUI stuff, there is an easily understood relationship between the objects and what you see on the screen - so its a great way of getting into OO - as far as people like you and me will go with it, which is not very far, as we tend to think in machine instructions... And for what its worth - you can programme assembler-like python, and it also works. The best thing to do is just to spend a few days playing with say Tkinter. I use a reference from the web written by John W Shipman at New Mexico Tech - it is succinct and clear, and deserves more widespread publicity. Google for it - I have lost the link, although I still have the pdf file. You will also find the interactive prompt that you get when you type python at a command prompt invaluable - it lets you play with and debug small code snippets so that you can learn as you go along - it really speeds up the whole learning process, and makes it almost painless. All this talking is just wasting time - you could have had your first frame up on the screen already, with a blank canvas, ready for drawing. It really goes that quick, once you start. So the answer to the title question is: Yes - a low level programmer can learn OOP, and its in fact easier than it looks, as almost all the heavy lifting has been done for you by others. - Hendrik From bj_666 at gmx.net Tue Jul 24 03:58:21 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Jul 2007 07:58:21 GMT Subject: classmethod & staticmethod References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> Message-ID: <5glpotF3gs3gfU1@mid.uni-berlin.de> On Tue, 24 Jul 2007 03:19:05 +0000, james_027 wrote: > python's staticmethod is the equivalent of java staticmethod right? Correct. `staticmethod` is essentially just a function moved into a class and accessible at the class object and instances of that class. As Python opposed to Java has functions, `staticmethod` isn't that useful. > with classmethod, I can call the method without the need for creating > an instance right? since the difference between the two is that > classmethod receives the class itself as implicti first argument. From > my understanding classmethod are for dealing with class attributes? It's possible to access class attributes and, maybe more important, it's possible to call the class to return an instance. So if you call a `classmethod` on a subclass an instance of that subclass is returned. Silly example: class A(object): def __init__(self, x, y): print 'init A' self.x = x self.y = y @classmethod def from_str(cls, string): return cls(*map(float, string.split(','))) class B(A): def __init__(self, x, y): print 'init B' A.__init__(self, x, y) def main(): B.from_str('42,23') Ciao, Marc 'BlackJack' Rintsch From jjl at pobox.com Sun Jul 22 07:42:01 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 22 Jul 2007 11:42:01 GMT Subject: how to find available classes in a file ? References: <2e302$469bf38f$d443bb3a$30036@news.speedlinq.nl> <1184627599.597658.267380@g4g2000hsf.googlegroups.com> <1184681117.305570.311350@x35g2000prf.googlegroups.com> Message-ID: <878x98u0l2.fsf@pobox.com> Alex Popescu writes: [...] > I may be wrong but I think I've found a difference between my > dir(module) approach > and the inspect.getmembers(module, inspect.isclass): the first one > returns the > classes defined in the module, while the later also lists the imported > available > classes. FWIW, see doctest.DocTestFinder._from_module() for a way to tell if an object is from a module. This can be fooled if you've managed to get hold of two copies of a module, though, which unfortunately is possible. I hope the import system is much cleaner in Python 3 :-/ (seems there are efforts in that direction, though I'm not up-to-date with it). John From fabiofz at gmail.com Mon Jul 9 15:21:43 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 9 Jul 2007 16:21:43 -0300 Subject: Pydev 1.3.7 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.7 have been released Details on Pydev Extensions: http://www.fabioz.com/pydev Details on Pydev: http://pydev.sf.net Details on its development: http://pydev.blogspot.com Release Highlights: ---------------------------------------------- * Support for Eclipse 3.3 * Bug Fix: Interpreter modules not correctly set/persisted after specifying interpreter (so, the builtins and other system libraries would not be available in completions). * Mylyn integration. * Open With Pydev: does not appear for containers anymore. * Code-completion: The folowing cases are now considered in code-completion to discover the type of a variable: o Type/Interface checking: (note that 'assert' is required) assert isinstance(obj, Interface) -- default from python o assert Interface.implementedBy(obj) -- zope o assert IsImplementation(obj, Interface) -- custom request o assert IsInterfaceDeclared(obj, Interface) -- custom request o Factory methods a = adapt(obj, Interface) -- pyprotocols o a = obj.GetAdapter(Interface) -- custom request o a = obj.get_adapter(Interface) -- custom request o a = GetSingleton(Interface) -- custom request o a = GetImplementation(Interface) -- custom request What is PyDev? --------------------------- PyDev is a plugin that enables users to use Eclipse for Python and Jython development -- making Eclipse a first class Python IDE -- It comes with many goodies such as code completion, syntax highlighting, syntax analysis, refactor, debug and many others. Cheers, -- Fabio Zadrozny ------------------------------------------------------ Software Developer ESSS - Engineering Simulation and Scientific Software http://www.esss.com.br Pydev Extensions http://www.fabioz.com/pydev Pydev - Python Development Enviroment for Eclipse http://pydev.sf.net http://pydev.blogspot.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bjourne at gmail.com Mon Jul 9 10:57:33 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 9 Jul 2007 16:57:33 +0200 Subject: What is the preferred doc extraction tool? In-Reply-To: <32e43bb70707090743r6df891eeo3500e0893d05aa54@mail.gmail.com> References: <32e43bb70707090743r6df891eeo3500e0893d05aa54@mail.gmail.com> Message-ID: <740c3aec0707090757v715c40f5sb2ecc78fe849281b@mail.gmail.com> On 7/9/07, Emin.shopper Martinian.shopper wrote: > Dear Experts, > > What is the preferred doc extraction tool for python? It seems that there > are many very nice options (e.g., pydoc, epydoc, HappyDoc, and lots of > others), but what is the "standard" tool or at least what is the tool used > to generate the documentation for the python standard library? The tool is Latex plus a lot of utilities that help make the HTML output good looking. It doesn't even extract documentation from the source. The best tool is definitely epydoc. It produces very good looking javadoc-like html output by default, no annoying css setup needed. You can also produce pdfs with it which is very nice. -- mvh Bj?rn From cfbolz at gmx.de Sun Jul 29 07:45:25 2007 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sun, 29 Jul 2007 13:45:25 +0200 Subject: 128 or 96 bit integer types? In-Reply-To: <7xlkd1ugvn.fsf@ruckus.brouhaha.com> References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com> <1185562901.206212.52570@j4g2000prf.googlegroups.com> <1185607142.096574.209200@e16g2000pri.googlegroups.com> <7xlkd1ugvn.fsf@ruckus.brouhaha.com> Message-ID: <46AC7DD5.9020201@gmx.de> Paul Rubin wrote: > "mensanator at aol.com" writes: >> has 146 digits. And that's just the begining. The above >> actually represents a polynomial with 264 terms, the >> exponents of which range from 0 to 492. One of those >> polynomials can have over 50000 decimal digits when >> solved. > > You should use gmpy rather than python longs if you're dealing with > numbers of that size. > Python multiplication uses a straightforward > O(n**2) algorithm where n is the number of digits. That's untrue since quite a while. CPython now uses Karatsuba-multiplication if the number of digits is larger than a certain threshold. Karatsuba is O(n**(log(3) / log(2)). > This is the best > way for up to a few hundred or maybe a few thousand digits. After > that, it's better to use more complicated FFT-based algorithms which > are O(n log n) despite their increased constant overhead. Gmpy does this. Karatsuba is still slower than these algorithms, but only if you have quite a big number of digits. Of course the core of your argument remains valid: CPython is not up to providing extremely good big integer arithmetic, so if you have extreme needs, you shouldn't use the builtin longs. Cheers, Carl Friedrich Bolz From david at boddie.org.uk Wed Jul 18 19:42:20 2007 From: david at boddie.org.uk (David Boddie) Date: Thu, 19 Jul 2007 01:42:20 +0200 Subject: Python-URL! - weekly Python news and links (Jul 16) Message-ID: <200707190142.20910.david@boddie.org.uk> On Wed Jul 18 23:20:51 CEST 2007, Cameron Laird wrote: > Kay Schluehr wrote: > > >Not sure if it's important enough to be mentioned in weekly Python > >news but Europython 2007 actually happened and took place in Vilnius. > > *I* sure think it's important; is there a summary or narrative > from the event you recommend? I've started to collect reports, photos and videos from the conference on the relevant PythonInfo Wiki page: http://wiki.python.org/moin/EuroPython2007 There's no definitive report out there, as far as I can tell. I imagine that everyone is getting their strength back after a week of talks, hacking, sightseeing and socialising. :-) David From Succelus at gmail.com Mon Jul 16 16:46:16 2007 From: Succelus at gmail.com (Succelus at gmail.com) Date: Mon, 16 Jul 2007 13:46:16 -0700 Subject: How to organize control access to source code ? Message-ID: <1184618776.798929.98960@57g2000hsv.googlegroups.com> Hello, How can we organize development team with code source control policy, that limit access to some portion of code ? Sincerely, Ahmed Boukhari From hniksic at xemacs.org Fri Jul 13 02:52:21 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Fri, 13 Jul 2007 08:52:21 +0200 Subject: os.wait() losing child? References: <4694903B.8000105@cosc.canterbury.ac.nz> <87bqehg5v1.fsf@mulj.homelinux.net> Message-ID: <873azsn6ca.fsf@mulj.homelinux.net> Jason Zheng writes: > Hrvoje Niksic wrote: >>> greg wrote: >> Actually, it's not that bad. _cleanup only polls the instances that >> are no longer referenced by user code, but still running. If you hang >> on to Popen instances, they won't be added to _active, and __init__ >> won't reap them (_active is only populated from Popen.__del__). >> > > Perhaps that's the difference between Python 2.4 and 2.5. [...] > Nope it still doesn't work. I'm running python 2.4.4, tho. That explains it, then, and also why greg's code didn't work. You still have the option to try to run 2.5's subprocess.py under 2.4. From cornpicker at gmail.com Thu Jul 12 14:25:56 2007 From: cornpicker at gmail.com (cornpicker at gmail.com) Date: Thu, 12 Jul 2007 11:25:56 -0700 Subject: Problem with building extension in Python In-Reply-To: References: <1183622938.086813.18950@k79g2000hse.googlegroups.com> Message-ID: <1184264756.063561.259080@w3g2000hsg.googlegroups.com> On Jul 5, 4:33 am, "Gabriel Genellina" wrote: > En Thu, 05 Jul 2007 05:08:58 -0300, > escribi?: > > > I have already install Microsoft visual studio .NET 2003 and MinGw, > > when I try to build a extension: > > Is this for Python 2.4? I think you can't compile Python 2.5 with VS2003. > > > python my_extension_setup.py build ( or install ) , I get an error: > > > LINK : fatal error LNK1141: failure during build of exports file > > error: command '"C:\Program Files\Microsoft Visual Studio .NET > > 2003\Vc7\bin\link.exe"' failed with exit status 1141.What shoud I > > do??? > > Almost surely you got a previous error, making link to fail. Try to > correct *that* error. > > -- > Gabriel Genellina Microsoft Visual Studio .NET 2003 Version 7.1 is the correct version to build extensions for Python 2.5. There is also a Microsoft Visual Studio .NET 2003 Version 7.0 as well, which is not acceptable for building extensions. The first release (version 7.0) was purchased by many, and is relatively easy to find. The following release (version 7.1) was a minor revision and is very hard to find, but it is what's necessary for building Python extensions. I hope future Python releases are built using a more standard compiler. I'm posting in this thread because I am running into the same problem as the original poster, linker error 1141. Here's a summary of what I've gotten to work properly so far: Python 2.5, Pyrex, and Microsoft Visual Studio 2003 .NET (version 7.1) are successfully installed I have successfully built Pyrex extensions using Distutils I have successfully imported and ran Pyrex extensions in my Python code The problems occur when I try to include C libraries in my Pyrex code. Specifically, I need some trig functions found in C's math.h header files. My .pyx file is as follows: # # Use C math functions # def cFunctionTester(float theta): import sys # Import the native C functions we need cdef extern from "math.h": double cos(double theta) double sin(double theta) result[0] = cos(theta) result[1] = sin(theta) return 5 I try to build the extension by running my setup.py file from the command prompt. My setup.py file is presented below: from distutils.core import setup from distutils.extension import Extension from Pyrex.Distutils import build_ext setup( name = "PyrexGuide", ext_modules=[ Extension("cTest", ["cTest.pyx"], libraries = []) ], cmdclass = {'build_ext': build_ext} ) I run this code through the command prompt by entering "setup.py install" The following error appears: C:\Python25\Lib\site-packages\Pyrex\Distutils>setup.py install running install running build running build_ext building 'cTest' extension c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\cl.exe /c / nologo /Ox /MD /W3 /GX /DNDEBUG -IC:\Python25\include -IC:\Python25\PC / TccTest.c /Fobuild \temp.win32-2.5\Release\cTest.obj cTest.c c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\link.exe / DLL /nologo /INCREMENTAL:NO /LIBPATH:C:\Python25\libs /LIBPATH:C: \Python25\PCBuild /EXPORT: initcTest build\temp.win32-2.5\Release\cTest.obj /OUT:build \lib.win32-2.5\cTest. pyd /IMPLIB:build\temp.win32-2.5\Release\cTest.lib LINK : error LNK2001: unresolved external symbol initcTest build\temp.win32-2.5\Release\cTest.lib : fatal error LNK1120: 1 unresolved exter nals LINK : fatal error LNK1141: failure during build of exports file error: command '"c:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\bin\link .exe"' failed with exit status 1141 C:\Python25\Lib\site-packages\Pyrex\Distutils> I do not know what the problem is -- perhaps the linker cannot locate math.h? I've tried copying the math.h file to a whole bunch of other directories, but there's still no luck. Any help anyone can provide would be greatly appreciated. Joe Stoffa CornPicker at gmail.com From aahz at pythoncraft.com Mon Jul 23 08:47:15 2007 From: aahz at pythoncraft.com (Aahz) Date: 23 Jul 2007 05:47:15 -0700 Subject: ANN: Snobol 1.0 References: <7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com> Message-ID: In article , greg wrote: >Aahz wrote: >> >> So adding SNOBOL patterns to another library would be a wonderful >> gift to the Python community... > >I wrote a module for Snobol-style pattern matching a while back, but >didn't get around to releasing it. I've just put it on my web page: > >http://www.cosc.canterbury.ac.nz/greg.ewing/python/Snobol.tar.gz Nice! You have restored my faith in the time machine. ;-) -- 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 gwill at wirelesstcp.net Fri Jul 27 11:21:00 2007 From: gwill at wirelesstcp.net (george williams) Date: Fri, 27 Jul 2007 08:21:00 -0700 Subject: SQLObject 0.7.8 References: <20070726142305.GC30176@phd.pp.ru> Message-ID: <000201c7d061$bcfe3550$c9b6d5cf@george644090dd> ----- Original Message ----- From: "Oleg Broytmann" To: "Python Announce Mailing List" ; "Python Mailing List" Sent: Thursday, July 26, 2007 7:23 AM Subject: SQLObject 0.7.8 > Hello! > > I'm pleased to announce the 0.7.8 release of SQLObject. > > What is SQLObject > ================= > > SQLObject is an object-relational mapper. Your database tables are > described > as classes, and rows are instances of those classes. SQLObject is meant > to be > easy to use and quick to get started with. > > SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite, and > Firebird. It also has newly added support for Sybase, MSSQL and MaxDB > (also > known as SAPDB). > > > Where is SQLObject > ================== > > Site: > http://sqlobject.org > > Mailing list: > https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss > > Archives: > http://news.gmane.org/gmane.comp.python.sqlobject > > Download: > http://cheeseshop.python.org/pypi/SQLObject/0.7.8 > > News and changes: > http://sqlobject.org/docs/News.html > > > What's New > ========== > > News since 0.7.7 > ---------------- > > Bug Fixes > ~~~~~~~~~ > > * Replaced calls to style.dbColumnToPythonAttr() in joins.py by > name/dbName > lookup in case the user named columns differently using dbName. > > * Minor correction in the tests: we fully support EnumCol in Postgres. > > * MySQLConnection now recognizes Enum, Double and Time columns when > drawing the > database scheme from DB. > > * Minor fix in FirebirdConnection.fromDatabase. > > * Fixed a bug with default field values for columns for firebird > connection. > > * Prevent a deadlock in declarative.threadSafeMethod() by not reacquiring > the class lock. > > * Fixed a bug in col.createSQL(). > > * Fixed a bug in converting date/time for years < 1000 (time.strptime() > requires exactly 4 digits for %Y, hence a year < 1000 must be 0-padded). > > Other Changes > ~~~~~~~~~~~~~ > > * Changed string quoting style for PostgreSQL and MySQL from \' to ''. > > For a more complete list, please see the news: > http://sqlobject.org/docs/News.html > > Oleg. > -- > Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru > Programmers don't die, they just GOSUB without RETURN. > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations.html > From steve at REMOVE.THIS.cybersource.com.au Wed Jul 11 22:24:21 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 12 Jul 2007 12:24:21 +1000 Subject: bool behavior in Python 3000? References: <7xodijdd8r.fsf@ruckus.brouhaha.com> <1184139458.063988.63510@w3g2000hsg.googlegroups.com> Message-ID: On Wed, 11 Jul 2007 00:37:38 -0700, Rob Wolfe wrote: > > Steven D'Aprano wrote: > >> From a purely functional perspective, bools are unnecessary in Python. I >> think of True and False as syntactic sugar. But they shouldn't be >> syntactic sugar for 1 and 0 any more than they should be syntactic sugar >> for {"x": "foo"} and {}. > > But `bools` are usefull in some contexts. Agreed. Syntactic sugar is useful, even though it is unnecessary. I'm not against having bools. I just want them to be Booleans, not dicts, or lists, or sets, or even integers. -- Steven. From _wdx at 163.com Wed Jul 25 22:17:54 2007 From: _wdx at 163.com (_wdx at 163.com) Date: Wed, 25 Jul 2007 19:17:54 -0700 Subject: Unable to abort a FTP command? In-Reply-To: <1185366722.171461.228100@w3g2000hsg.googlegroups.com> References: <1185349701.504484.14370@m37g2000prh.googlegroups.com> <1185366722.171461.228100@w3g2000hsg.googlegroups.com> Message-ID: <1185416274.738858.266800@z24g2000prh.googlegroups.com> Thank you. You are right, retrbinary did not notice I want to abort, so it won't break the recv loop and close data connection. I changed getpart and callback like this, now it works: def getpart_callback(self, received): print "received a packet" if self.cnt <= 0: return True else: print 'received packet, [0] = %x' % ord(received[0]) self.outf.write(received) self.cnt -= len(received) def getpart(self, ftp_filename, rest, cnt, out_filename): self.outf = open(out_filename, 'wb') self.cnt = cnt self.handle.voidcmd('TYPE I') conn = self.handle.transfercmd('RETR ' + ftp_filename, rest) while 1: data = conn.recv(8192) if not data: break if self.getpart_callback(data): try: self.handle.abort() break except: pass self.outf.close() self.handle.voidresp() conn.close() From steve at holdenweb.com Mon Jul 30 06:32:55 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Jul 2007 06:32:55 -0400 Subject: How to write GUI and event separately in wxPython?? In-Reply-To: <5h5kmiF3hmufcU3@mid.uni-berlin.de> References: <1185777254.925902.204500@z28g2000prd.googlegroups.com> <5h5kmiF3hmufcU3@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Sun, 29 Jul 2007 23:34:14 -0700, Jia Lu wrote: > >> I am making an application with wxpython. >> But I got a problem when I want to change the display string >> according to process status. >> >> I passed the frame to the processing function and use the >> frame.txtobj to change displaying strings. >> >> I found it is a bad method to do that. >> Can any one tell me how to do that usually? >> ( How to separate GUI and Control code? ) > > One possibility here is to give a callback function into the worker > function that gets called while the function does it's work. Simple > example: > > def do_work(arguments, callback=lambda msg: None): > callback('Start processing.') > for percent in xrange(0, 101): > callback('finished %d%%...' % percent) > callback('Done.') > >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)] True >>> 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 jscrerar at compuserve.com Sun Jul 15 10:25:41 2007 From: jscrerar at compuserve.com (Jim) Date: Sun, 15 Jul 2007 07:25:41 -0700 Subject: zipfile 2GB problems? In-Reply-To: <1184474112.081258.111490@n60g2000hse.googlegroups.com> References: <1184474112.081258.111490@n60g2000hse.googlegroups.com> Message-ID: <1184509541.717169.89920@d55g2000hsg.googlegroups.com> On Jul 14, 10:35 pm, xamdam wrote: > Hi fellas, > I am experiencing problems reading a 2GB zipfile consisting of > multiple zipped files. I found a threadhttp://mail.python.org/pipermail/python-dev/2005-April/053027.html > that mentions a problem on the writing side, does such a problem exist > on a reading side? I am using 2.4.1, perhaps there is a fix in a later > version? Hi, I use PKZIP V9.00 and maintain a 2.5GB zipfile that consists of over 6,600 zipped files. There is no problem with reading or writing. Thanks, Jim From aleax at mac.com Thu Jul 5 23:19:22 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 5 Jul 2007 20:19:22 -0700 Subject: MethodType/FunctionType and decorators References: <1183589529.198694.109440@m36g2000hse.googlegroups.com> <1183591053.434640.119550@o61g2000hsh.googlegroups.com> <1i0qoq9.u1fu2g63fkmxN%aleax@mac.com> <1183623479.913816.301230@g4g2000hsf.googlegroups.com> <1183626989.983470.94950@o61g2000hsh.googlegroups.com> <1183641471.753457.269030@m36g2000hse.googlegroups.com> <1183644112.049339.159460@c77g2000hse.googlegroups.com> <1183673911.790367.73090@n2g2000hse.googlegroups.com> Message-ID: <1i0snfy.9sv6evjonlj6N%aleax@mac.com> Alex Popescu wrote: ... > frameworks (TestNG is not a unit testing framework, > but a full flavored testing framework that fits perfectly functional > testing, integration testing, and with some of the > very advanced features even performance and load testing). Nice! Does it have any integration/interoperability with FIT/Fitnesse, btw? For certain kinds of "functional testing" (where the specs are to be mostly written by people with no programming skills but strong business, accounting, &c, i.e., people _used_ to thinking in terms of tables and spreadsheets) I find that approach very interesting... Alex From manasd at gmail.com Sun Jul 15 22:39:44 2007 From: manasd at gmail.com (MD) Date: Sun, 15 Jul 2007 19:39:44 -0700 Subject: Accessing Python variables in an extension module Message-ID: <1184553584.757696.92630@g4g2000hsf.googlegroups.com> Hi, I would like to access "variables" defined in my Python program in a C module extension for Python. Is this possible? I looked at the Python C API reference but didn't find anything there that could help me. Thanks in advance for any help/tips. Regards, -MD From michele.simionato at gmail.com Fri Jul 13 11:06:08 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Fri, 13 Jul 2007 15:06:08 -0000 Subject: Function parameter type safety? In-Reply-To: <1184338421.695360.227030@g4g2000hsf.googlegroups.com> References: <1184277163.803229.318660@g4g2000hsf.googlegroups.com> <1184338421.695360.227030@g4g2000hsf.googlegroups.com> Message-ID: <1184339168.207823.202670@w3g2000hsg.googlegroups.com> On Jul 13, 4:53 pm, Robert Dailey wrote: > Good replies. > > I'm in the process of learning Python. I'm a native C++ programmer, so > you can see how the question relates. There's a lot of cool things C++ > allowed you to do with type-checking, such as function overloading. This is an area of hot debate in Python and things are changing. You may want to have a look at http://www.python.org/dev/peps/pep-3119 about interfaces, and to http://www.python.org/dev/peps/pep-3124 about overloading and generic functions. Both PEPs are for Python 3000, but their existence should be an indication that people are not happy with the current situation in Python. You can something better than overloading already, with P.J. Eby modules simplegeneric and/or RuleDispatch, but I would say that they are not commonly used. So the right thing to do for now is to follow the good advices you received, but keep in mind that there will be alternatives in the near future (such as interface checking/function overload). Michele Simionato From http Sun Jul 1 13:01:13 2007 From: http (Paul Rubin) Date: 01 Jul 2007 10:01:13 -0700 Subject: object references/memory access References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> Message-ID: <7xfy48f486.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > > If this is a Linux server, it might be possible to use the SCM_RIGHTS > > message to pass the socket between processes. > > I very much doubt that the OP's problem is what he thinks it is, > i.e. that copying over a local TCP connection is what makes his > application slow. Right, the copying should be very fast, but serializing and deserializing the stuff being copied can be slow. This is an issue with something I'm currently working on, for example. > [Apache] Instead, it is the operating system itself which > distributes the requests: the parent process opens the server socket, ... Ah, thanks. From bj_666 at gmx.net Sun Jul 8 16:55:42 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 8 Jul 2007 20:55:42 GMT Subject: "Empty" text References: <469147b8$1@griseus.its.uu.se> Message-ID: <5fd1aeF3berb8U1@mid.uni-berlin.de> On Sun, 08 Jul 2007 22:23:20 +0200, Jan Danielsson wrote: > The problem is that this generates the following code: > > > Description > > > > I understand the opitmization ElementTree is performing; but it seems > there are cases when it is not the proper thing to do. Is it possible to > force ElementTree to output the XHTML code I need it to? > Then either Firefox is broken or you don't declare your XHTML properly and Firefox thinks it's HTML. Ciao, Marc 'BlackJack' Rintsch From brotherjenos at gmail.com Fri Jul 20 12:05:22 2007 From: brotherjenos at gmail.com (Walker Lindley) Date: Fri, 20 Jul 2007 09:05:22 -0700 Subject: Pickled objects over the network In-Reply-To: <9c8d48280707200904w59e2ac44yf2f60f38b2ffa0e4@mail.gmail.com> References: <9c8d48280707200827h66d32ffcxe68978590efd3e97@mail.gmail.com> <20070720155536.4947.302498406.divmod.quotient.13831@ohm> <9c8d48280707200904w59e2ac44yf2f60f38b2ffa0e4@mail.gmail.com> Message-ID: <9c8d48280707200905m1febc9aamb024f4321cab753@mail.gmail.com> Right, it's just a big problem with pickle because if you do a recv at the wrong time and try to load it with pickle, you'll start getting weird errors down in the pickle module as opposed to just not getting the full string you expected if you were using plaintext strings. This is probably me being spoiled from Java, but they built a stream class that can be used for files, networks, and many other things while hiding nasty details like this. It seems like Python could really benefit from this kind of architecture. Of course, there's probably already something out there that I just don't know about. -Walker On 7/20/07, Jean-Paul Calderone wrote: > > On Fri, 20 Jul 2007 08:27:13 -0700, Walker Lindley > wrote: > >It doesn't interface well because the string you end up with often > doesn't > >fit into a single packet. Therefore you have to add a layer of protocol > on > >top of it that allows you to check to make sure you have the whole string > >received before trying to unpickle it. This the case even if you use > >socket's makefile() method to make a file descriptor. > > This is somewhat misleading. TCP doesn't guarantee any minimum packet size > larger than a single byte. Any messaging system which uses strings longer > > than one byte must have a framing protocol to be reliable. So, this isn't > really specific to pickle. Basically, all protocols have to address this. > > Jean-Paul > -- > http://mail.python.org/mailman/listinfo/python-list > -- 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. -- 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: From nagle at animats.com Tue Jul 3 01:09:16 2007 From: nagle at animats.com (John Nagle) Date: Tue, 03 Jul 2007 05:09:16 GMT Subject: Rappresenting infinite In-Reply-To: References: <1182940919.351011.267020@n2g2000hse.googlegroups.com> <1183403549.523918.262500@m36g2000hse.googlegroups.com> Message-ID: <0Skii.1281$eY.3@newssvr13.news.prodigy.net> Robert Kern wrote: > avassalotti at gmail.com wrote: > > >>float('inf') works well, no? > It is not cross-platform. The parsing of strings into floats and the string > representation of floats is dependent on your system's C library. For these > special values, this differs across platforms. Your code won't work on Windows, > for example. Yes. This is CPython bug #1255395, status "open". Also CPython bug #44585 (Pickle fails on "inf" values) PEP 42 contains excuses for not calling it a bug. John Nagle From Xin.Zheng at jpl.nasa.gov Thu Jul 12 12:27:18 2007 From: Xin.Zheng at jpl.nasa.gov (Jason Zheng) Date: Thu, 12 Jul 2007 09:27:18 -0700 Subject: os.wait() losing child? In-Reply-To: <87bqehg5v1.fsf@mulj.homelinux.net> References: <4694903B.8000105@cosc.canterbury.ac.nz> <87bqehg5v1.fsf@mulj.homelinux.net> Message-ID: Hrvoje Niksic wrote: >> greg wrote: > > Actually, it's not that bad. _cleanup only polls the instances that > are no longer referenced by user code, but still running. If you hang > on to Popen instances, they won't be added to _active, and __init__ > won't reap them (_active is only populated from Popen.__del__). > Perhaps that's the difference between Python 2.4 and 2.5. In 2.4, Popen's __init__ always appends self to _active: def __init__(...): _cleanup() ... self._execute_child(...) ... _active.append(self) > This version is a trivial modification of your code to that effect. > Does it work for you? > Nope it still doesn't work. I'm running python 2.4.4, tho. $ python test.py Starting child process 0 (26497) Starting child process 1 (26498) Starting child process 2 (26499) Child Process 2 terminated, restarting Child Process 2 terminated, restarting Child Process 2 terminated, restarting Child Process 2 terminated, restarting Child Process 2 terminated, restarting Child Process 2 terminated, restarting Child Process 2 terminated, restarting Child Process 2 terminated, restarting Child Process 2 terminated, restarting Child Process 2 terminated. Traceback (most recent call last): File "test.py", line 15, in ? pid, ignored = os.wait() OSError: [Errno 10] No child processes From jeffober at gmail.com Wed Jul 25 10:45:00 2007 From: jeffober at gmail.com (Jeff) Date: Wed, 25 Jul 2007 14:45:00 -0000 Subject: Closures / Blocks in Python In-Reply-To: <7tvjn4-qas.ln1@lairds.us> References: <1185289112.771239.200260@n60g2000hse.googlegroups.com> <1185291146.753573.280420@n60g2000hse.googlegroups.com> <7tvjn4-qas.ln1@lairds.us> Message-ID: <1185374700.256479.228560@b79g2000hse.googlegroups.com> You can create a lexical closure using a Python generator function, which allows iteration using a block of code while maintaining internal state. A generator is a regular function which uses yield (like Ruby) to define the point at which the function should return an expression to the calling code. For example: # Generic counter def counter(min=None, max): if not min: min = 0 for i in xrange(min, max): yield i i = i + 1 When called, this function will yield the value of i and remember its state. The next time it's called, it will increment i, then continue on another iteration of the loop, yielding the new value of i. For example: my_counter = counter(0, 10) my_counter() # <-- 0 my_counter() # <-- 1 for i in my_counter(): print i # Prints 2-10 (the remaining numbers in xrange(min, max)) From danmcleran at yahoo.com Wed Jul 25 14:58:40 2007 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: Wed, 25 Jul 2007 11:58:40 -0700 Subject: is_iterable function. In-Reply-To: References: Message-ID: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> You can use the built-in dir() function to determine whether or not the __iter__ method exists: class Iterable(object): def __iter__(self): pass class NotIterable(object): pass def is_iterable(thing): return '__iter__' in dir(thing) print 'list is iterable = ', is_iterable(list()) print 'int is iterable = ', is_iterable(10) print 'float is iterable = ', is_iterable(1.2) print 'dict is iterable = ', is_iterable(dict()) print 'Iterable is iterable = ', is_iterable(Iterable()) print 'NotIterable is iterable = ', is_iterable(NotIterable()) Results: list is iterable = True int is iterable = False float is iterable = False dict is iterable = True Iterable is iterable = True NotIterable is iterable = False On Jul 25, 12:24 pm, Neil Cerutti wrote: > def is_iterable(obj): > try: > iter(obj) > return True > except TypeError: > return False > > Is there a better way? > > -- > Neil Cerutti From bignose+hates-spam at benfinney.id.au Wed Jul 25 20:54:45 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 26 Jul 2007 10:54:45 +1000 Subject: code indentation References: <1185297657.186852.136950@k79g2000hse.googlegroups.com> <87lkd5jt83.fsf@benfinney.id.au> <1185357861.989194.117000@r34g2000hsd.googlegroups.com> <1185387723.155661.311510@b79g2000hse.googlegroups.com> Message-ID: <87tzrshtm2.fsf@benfinney.id.au> vedrandekovic at v-programs.com writes: > On this group I ask for serious help and now we talk about > communication. Yes. You're asking for volunteer help from a group of people who have their own priorities separate from yours. The way to garner help from these people is to respect their time. One excellent way to do that is to communicate clearly and maturely, so that your messages are easier (and therefore faster) to read. Please, before going further, read this document on how to ask questions the smart way: > Then I you don't know how to help me then please DON'T SAY ANYTHING This is a volunteer group, run for the benefit of the community. We want to help not only you, but *anyone* who might come here asking for help, and especially those who are inclined to help them. Advice on improving communication is one good way to do that: it actively works toward better communication in future, which helps questions get answered quicker and consumes less of the helpers' time. -- \ "I put contact lenses in my dog's eyes. They had little | `\ pictures of cats on them. Then I took one out and he ran around | _o__) in circles." -- Steven Wright | Ben Finney From dave at boost-consulting.com Wed Jul 4 23:53:15 2007 From: dave at boost-consulting.com (David Abrahams) Date: Wed, 04 Jul 2007 23:53:15 -0400 Subject: Proposal: s1.intersects(s2) References: <5f1pldF3a62csU5@mid.uni-berlin.de> Message-ID: <87tzsjjyl0.fsf@grogan.peloton> on Wed Jul 04 2007, "Steven D'Aprano" wrote: > On Wed, 04 Jul 2007 14:37:34 +0000, Marc 'BlackJack' Rintsch wrote: > >> On Wed, 04 Jul 2007 09:59:24 -0400, David Abrahams wrote: >> >>> Here's an implementation of the functionality I propose, as a >>> free-standing function: >>> >>> def intersects(s1,s2): >>> if len(s1) < len(s2): >>> for x in s1: >>> if x in s2: return True >>> else: >>> for x in s2: >>> if x in s1 return True >>> return False >> >> In Python 2.5 this can be written a bit more concise: >> >> def intersects(set_a, set_b): >> if len(set_a) < len(set_b): >> set_a, set_b = set_b, set_a >> return any(item in set_a for item in set_b) > > > I'd rather see sets gain an method "isintersect()" And why is that a good name? It's not even grammatical. > with the functionality than the language to gain a built-in > function. How is a method on sets not a built-in function? Anyway, such a method is what I'm proposing. > However, there's a very subtle flaw in the idea. While "the intersection" > of two sets is well-defined, "these two sets intersect" is (surprisingly!) > _not_ well-defined. Depends how you define it. I define it as "has a non-empty intersection," which is pretty obviously solid. The semantics should be identical to len(s1&s2) > 0 Those are exactly the semantics I want, and if mathematical purists are going to argue that "intersects" is the wrong name, I ask that they come up with a better one. -- Dave Abrahams Boost Consulting http://www.boost-consulting.com The Astoria Seminar ==> http://www.astoriaseminar.com From tedpottel at gmail.com Mon Jul 9 17:37:45 2007 From: tedpottel at gmail.com (tedpottel at gmail.com) Date: Mon, 09 Jul 2007 21:37:45 -0000 Subject: having problems in changing directories doing ftp in python In-Reply-To: References: <1183812119.335649.292470@w3g2000hsg.googlegroups.com> Message-ID: <1184017065.872866.209340@q75g2000hsh.googlegroups.com> Hi, Thank you for your cfomment, also I forgot about the case issue, yes my web server is unix, not windows On Jul 9, 4:12 am, "Gabriel Genellina" wrote: > En Sat, 07 Jul 2007 09:41:59 -0300, tedpot... at gmail.com > escribi?: > > > I'm trying to write aftpin python to send files to my webserverr. > > Curtly I will change the directory to the folder name, down load the > > file, then do a chnag dir ..\ to go back to the root diretory, chnag > > the directory, save the file, do a ../. > > > Instad of going back one directory by doing ..\, could I just go to > > the root directory? Currtly I get a error saying file does not exist. > > Use the pwd command to see exactly which is your current directory. > > > When I log onto my server using myftpprogram, > > The current path reads /home/admin/ > > I change the directory to mainwebsite_html. > > The line that tells you the current directory now reads VAR/WWW/HTML. > > > When I use python, I > > 1. change the directory to mainwebsite_html > > 2. change the directory to ted > > 3. try to go back by changing the directory to "var/www/html" in which > > I get an error saying it does not exist. > > If your server file system is case sensitive (likely if it's a linux/unix > server), VAR/WWW/HTML is not the same thing as var/www/html > > -- > Gabriel Genellina From http Thu Jul 12 20:28:16 2007 From: http (Paul Rubin) Date: 12 Jul 2007 17:28:16 -0700 Subject: Fastest way to convert a byte of integer into a list References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> <1184284461.506663.75500@g12g2000prg.googlegroups.com> <1184284861.695430.99300@e9g2000prf.googlegroups.com> Message-ID: <7xr6ndtae7.fsf@ruckus.brouhaha.com> Godzilla writes: > > num = 255 > > numlist = [num >> i & 1 for i in range(8)] > > Thanks matimus! I will look into it... numlist = lookup_table[num] where lookup_table is a precomputed list of lists. From carsten at uniqsys.com Sun Jul 8 20:37:56 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 08 Jul 2007 20:37:56 -0400 Subject: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc) In-Reply-To: <1183939608.088756.178320@m37g2000prh.googlegroups.com> References: <1183939608.088756.178320@m37g2000prh.googlegroups.com> Message-ID: <1183941476.3165.19.camel@localhost.localdomain> On Sun, 2007-07-08 at 17:06 -0700, socialanxiety at gmail.com wrote: > i hope someone here can help me. > > basically, me and my friend have a summer project. > > in this project, we need something that would basically function as a > blender. we know we'll need to buy a motor that spins, but what we're > having trouble with is figuring out how to program it. we want to be > able to control the speed of the motor. how would we accomplish this? > > i'm new to all of this, so i'm having a hard time wrapping my mind > around how it'd be possible to program one of those things :\ > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then > turn the other direction. > > would you program it the same way you would on a personal computer > (via c, python, etc)? The answers to your questions depend very much on what you're working with and how the motor is controlled. Is this supposed to be a self-contained machine, or is it supposed to be connected to a personal computer as a peripheral device? The easier way is the peripheral device. In that case, you need some way of sending signals e.g. from your computer's parallel or serial port to a relay switch or voltage controller that controls your motor. In that case, apart from the nitty gritty hardware to make the physical connections, it's a matter of controlling the parallel or serial port that the "robot" is attached to, which can definitely be done in Python. I won't go into details because you're not saying enough about your project constraints, and as fascinating as your question is, it is somewhat off-topic on this list (as if that's a deterrent to discussing something on this list ;-). As John said, you're more likely to receive useful advice on comp.robotics.misc. Good luck, -- Carsten Haese http://informixdb.sourceforge.net From cito at online.de Thu Jul 5 14:15:16 2007 From: cito at online.de (Christoph Zwerschke) Date: Thu, 05 Jul 2007 20:15:16 +0200 Subject: Re-raising exceptions with modified message In-Reply-To: References: Message-ID: Neil Cerutti wrote: > The documentation for BaseException contains something that might > be relevant: > > [...] If more data needs to be attached to the exception, > attach it through arbitrary attributes on the instance. All > > Users could get at the extra info you attached, but it wouldn't > be automatically displayed by the interpreter. Yes, that's the problem here. It wouldn't be displayed automatically and the users must be aware of this attribute. I'd like to have a more transparent solution. -- Chris From nospam.themindstorm at gmail.com Tue Jul 31 20:10:31 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Wed, 1 Aug 2007 00:10:31 +0000 (UTC) Subject: Wing IDE for Python v. 3.0 beta1 released References: <46AF8ED7.2070206@wingware.com> Message-ID: Wingware wrote in news:46AF8ED7.2070206 at wingware.com: > Hi, > > I'm happy to announce the first beta release of Wing IDE 3.0. It is > available from http://wingware.com/wingide/beta > > > [snip...] > > There is one feature that I would like to suggest: open module in project. Currently you need to Navigate inside the project and double-click the module (or right block open), but having a shortcut that would bring a popup to enter the name of the module would be more proficient. bests, ./alex -- .w( the_mindstorm )p. From nospam.themindstorm at gmail.com Fri Jul 20 18:50:36 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Fri, 20 Jul 2007 22:50:36 +0000 (UTC) Subject: Sorting dict keys References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> Message-ID: montyphyton at gmail.com wrote in news:1184970471.146819.86280 @r34g2000hsd.googlegroups.com: I am not sure about your scenario, but as you discovered the sort() method is modifying the in place list (and doesn't return a new one). If you just want to iterate over your dict in an ordered manner than all you have to do is: for k in my_dict.keys().sort(): # rest of the code If you just want to keep a list of ordered keys you can probably do something like: key_list = list(my_dict.keys()) key_list.sort() bests, ./alex -- .w( the_mindstorm )p. From kyosohma at gmail.com Mon Jul 9 16:03:49 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Mon, 09 Jul 2007 13:03:49 -0700 Subject: Distributing python apps In-Reply-To: <1184011164.346200.9330@q75g2000hsh.googlegroups.com> References: <1184011164.346200.9330@q75g2000hsh.googlegroups.com> Message-ID: <1184011429.403297.270560@n2g2000hse.googlegroups.com> On Jul 9, 2:59 pm, Robert Dailey wrote: > Hi, > > I'm creating a set of command-line tools using Python. These tools > manage resources for a game I'm working on. However, many people that > will be using these tools will not want to install Python on their > machines. This would be a very tedious process (for first time users > of my tools). > > Ideally, I would like for someone to be able to use my tools without > having to install Python. For example, if I could put python.exe in a > hidden folder somewhere in my tools directory, and make a batch file > that they run to start the tool, python could be executed from a > relative path in my tools directory. Is this possible? What is an > ideal way of distributing python apps? I would prefer a transparent > and user-friendly approach. > > Thanks for any tips. The typical approach is using py2exe: http://www.py2exe.org/ I use it in conjunction with Inno Setup. http://www.jrsoftware.org/isinfo.php GUI2Exe is a GUI interface to py2exe: http://xoomer.alice.it/infinity77/eng/GUI2Exe.html Mike From stefan.behnel-n05pAM at web.de Thu Jul 26 13:56:44 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 26 Jul 2007 19:56:44 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? In-Reply-To: <0T49dalhI43nNv8%stesch@parsec.no-spoon.de> References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49d313I3ogNv8%stesch@parsec.no-spoon.de> <46A8C934.3010601@web.de> <0T49dalhI43nNv8%stesch@parsec.no-spoon.de> Message-ID: <46A8E05C.5060603@web.de> Stefan Scholl wrote: > Stefan Behnel wrote: >> Stefan Scholl wrote: >>> Stefan Behnel wrote: >>>> Stefan Scholl wrote: >>>>> Stefan Behnel wrote: >>>>>> Stefan Scholl wrote: >>>>>>> Well, http://docs.python.org/lib/module-xml.sax.html is missing >>>>>>> the fact, that I can't use Unicode with parseString(). >>>>>>> >>>>>>> This parseString() uses cStringIO. >>>>>> Well, Python unicode is not a valid *byte* encoding for XML. >>>>>> >>>>>> lxml.etree can parse unicode, if you really want, but otherwise, you should >>>>>> maybe stick to well-formed XML. >>>>> The XML is well-formed. Works perfect in Python 2.4 with Python >>>>> unicode and Python sax parser. >>>> The XML is *not* well-formed if you pass Python unicode instead of a byte >>>> encoded string. Read the XML spec. >>>> >>>> It would be well-formed if you added the proper XML declaration, but that is >>>> system specific (UCS-4 or UTF-16, BE or LE). So don't even try. >>> Who cares? I'm not calling any external tools. >> XML cares. If you want to work with something that is not XML, do not expect >> XML tools to help you do it. XML tools work with XML, and there is a spec that >> says what XML is. Your string is not XML. > > This isn't some sophisticated XML tool that tells me the string > is wrong. It's a changed behavior of cStringIO that throws an > exception. While I'm just using the method parseString() of > xml.sax. All I'm saying is that parseString() is perfectly right in using cStringIO, as cStringIO supports every possible incarnation of serialised XML. It was documented that cStringIO does not support Unicode and it doesn't: $ python2.4 Python 2.4.4 (#2, Apr 12 2007, 21:03:11) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from cStringIO import StringIO >>> s = StringIO() >>> s.write(u"\uf852") Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\uf852' in position 0: ordinal not in range(128) What a surprise. Stefan From paul at boddie.org.uk Thu Jul 26 12:38:34 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Thu, 26 Jul 2007 09:38:34 -0700 Subject: I am giving up perl because of assholes on clpm -- switching to Python In-Reply-To: References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com> Message-ID: <1185467914.814174.94600@22g2000hsm.googlegroups.com> zentara wrote: > > This is where the big boys play, you have to be able to be able to > scuffle and take punishment if you are wrong or unduly ignorant. > You also need to squash somehow who attacks you, when you > know you are right. Where is this again? High school? I can understand people getting impatient with repeated incoherent one-line messages of the form "can u give me teh codes thanx", but you'd show off your community a bit better by entertaining even the most naive questions - people have to start somewhere, you know. > I was watching a CNBC yesterday, and they interviewed a leading > solar panel company's CEO. One guy just blasted him for no reason > other than he gets a government subsidy, and even the moderator felt > bad for the way the executive was blasted. BUT...... they are the big > boys, playing for real money, and if you play there, you have to expect > to have your toughness tested..... it means real profit and loss. In comp.lang.perl.misc? It seems to me that the "big boys" in this case have an inflated sense of their own bigness. Paul P.S. Although it's nice to point to beginner resources, too, 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. From stesch at no-spoon.de Thu Jul 26 11:21:03 2007 From: stesch at no-spoon.de (Stefan Scholl) Date: Thu, 26 Jul 2007 17:21:03 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> Message-ID: <0T49d313I3ogNv8%stesch@parsec.no-spoon.de> Stefan Behnel wrote: > Stefan Scholl wrote: >> Stefan Behnel wrote: >>> Stefan Scholl wrote: >>>> Well, http://docs.python.org/lib/module-xml.sax.html is missing >>>> the fact, that I can't use Unicode with parseString(). >>>> >>>> This parseString() uses cStringIO. >>> Well, Python unicode is not a valid *byte* encoding for XML. >>> >>> lxml.etree can parse unicode, if you really want, but otherwise, you should >>> maybe stick to well-formed XML. >> >> The XML is well-formed. Works perfect in Python 2.4 with Python >> unicode and Python sax parser. > > The XML is *not* well-formed if you pass Python unicode instead of a byte > encoded string. Read the XML spec. > > It would be well-formed if you added the proper XML declaration, but that is > system specific (UCS-4 or UTF-16, BE or LE). So don't even try. Who cares? I'm not calling any external tools. Python should know its own strings. From dave at boost-consulting.com Tue Jul 3 18:47:24 2007 From: dave at boost-consulting.com (David Abrahams) Date: Tue, 03 Jul 2007 18:47:24 -0400 Subject: import mysteries References: Message-ID: <87bqetnlz7.fsf@grogan.peloton> on Fri Jun 22 2007, "Steven D'Aprano" wrote: > There are ways to bypass the import system. The most obvious would be to > write directly to globals. > >>>> spanish_inquisition > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'spanish_inquisition' is not defined >>>> globals()['spanish_inquisition'] = "NOBODY expects the Spanish > Inquisition!!!" >>>> spanish_inquisition > 'NOBODY expects the Spanish Inquisition!!!' Yeah, of course. I just don't think anything that perverse is happening in these cases. Take, for another example, http://trac.edgewall.org/ticket/5646#comment:3 -- Dave Abrahams Boost Consulting http://www.boost-consulting.com The Astoria Seminar ==> http://www.astoriaseminar.com From nis at superlativ.dk Wed Jul 4 08:09:14 2007 From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=) Date: Wed, 04 Jul 2007 14:09:14 +0200 Subject: Generator for k-permutations without repetition In-Reply-To: <1183548133.495759.191390@d30g2000prg.googlegroups.com> References: <1183548133.495759.191390@d30g2000prg.googlegroups.com> Message-ID: <468b8df8$0$90275$14726298@news.sunsite.dk> bullockbefriending bard skrev: > I was able to google a recipe for a k_permutations generator, such > that i can write: > > x = range(1, 4) # (say) > [combi for combi in k_permutations(x, 3)] => > > [[1, 1, 1], [1, 1, 2], [1, 1, 3], [1, 2, 1], [1, 2, 2], [1, 2, 3], [1, > 3, 1], [1, 3, 2], [1, 3, 3], [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2, > 1], [2, 2, 2], [2, 2, 3], [2, 3, 1], [2, 3, 2], [2, 3, 3], [3, 1, 1], > [3, 1, 2], [3, 1, 3], [3, 2, 1], [3, 2, 2], [3, 2, 3], [3, 3, 1], [3, > 3, 2], [3, 3, 3]] > > but what i really want is the above without repetition, i.e.: > > [combi for combi in k_permutations_without_repetitions(x, 3)] => > > [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] > > For smallish lists, it's no problem to generate the list as follows: > > no_reps_combis = [combi for combi in k_permutations(x, 3) if \ > > len(set(combi)) == 3] > > but i'm sure there must be a way to do this as a pure generator, just > that i wouldn't have a clue how to go about it. > > Help please, Python Gods! :) I was initially confused by your example, since the size of the underlying set is the same as of the individual permutations. In this case, you are just asking for all permutations of the set. As far as I can tell from a quick googling, the relevant definition of k-permutation is "an ordered list of k elements from the set". Thus your first example does not really generate k_permutations. A quick solution, not extensively tested # base needs to be an of the python builtin set def k_perm(base,k): for e in base: if k == 1: yield [e] else: for perm in k_perm(base-set([e]),k-1): yield [e] + perm >>> list(k_perm(set([1,2,3,4]),3)) [[1, 2, 3], [1, 2, 4], [1, 3, 2], [1, 3, 4], [1, 4, 2], [1, 4, 3], [2, 1, 3], [2, 1, 4], [2, 3, 1], [2, 3, 4], [2, 4, 1], [2, 4, 3], [3, 1, 2], [3, 1, 4], [3, 2, 1], [3, 2, 4], [3, 4, 1], [3, 4, 2], [4, 1, 2], [4, 1, 3], [4, 2, 1], [4, 2, 3], [4, 3, 1], [4, 3, 2]] Much to my initial surprise, it "works" for k<1 as well: >>> list(k_perm(set([1,2,3,4]),-1)) [] Hope this helps Nis From matt.rasmus at gmail.com Tue Jul 10 20:21:12 2007 From: matt.rasmus at gmail.com (rasmus) Date: Wed, 11 Jul 2007 00:21:12 -0000 Subject: profiling a C++ python extension Message-ID: <1184113272.962640.41240@22g2000hsm.googlegroups.com> I have used gprof to profile stand alone C++ programs. I am also aware of pure python profilers. However, is there a way to get profile information on my C++ functions when they are compiled in a shared library (python extension module) and called from python. From what I can tell, gmon.out will not be generated unless the entire executable (python interpreter) was compiled with -pg. Is my only solution to recompile the python interpreter with -pg so that my extension module (also compiled with -pg) produces a gmon.out? Any suggestions or tips would be helpful. Matt From afriere at yahoo.co.uk Tue Jul 17 02:22:34 2007 From: afriere at yahoo.co.uk (Asun Friere) Date: Mon, 16 Jul 2007 23:22:34 -0700 Subject: In a dynamic language, why % operator asks user for type info? In-Reply-To: <1184631007.920803.147790@j4g2000prf.googlegroups.com> References: <1184631007.920803.147790@j4g2000prf.googlegroups.com> Message-ID: <1184653354.651689.247770@i13g2000prf.googlegroups.com> In practice the different placeholders give you a handle to achieve different formatting effects. Compare for example: for x in range(15) : print '%02d' % x against: for x in range(15) : print '%02s' % x #the '0' in this case being redundant Or again: from math import pi print '%.4f' % pi print '%.4s' % pi #if that last seems silly consider print '%.4s % 'hello world' Given that there already exists an established (and documented) printf convention, one could argue that overloading (or even augmenting) the established placeholders is not the best option in this case. >If the above is the case, we could've avoided all those exceptions >that happen when a %d is specified but say a string is passed. Generally I prefer handling exceptions to avoiding them. From bbxx789_05ss at yahoo.com Mon Jul 2 16:06:12 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Mon, 02 Jul 2007 13:06:12 -0700 Subject: subprocess -- broken pipe error In-Reply-To: <5et3n6F399q8uU1@mid.individual.net> References: <1183396350.429008.185200@n2g2000hse.googlegroups.com> <1183397577.959518.264230@g4g2000hsf.googlegroups.com> <1183400345.202323.133750@k29g2000hsd.googlegroups.com> <5et3n6F399q8uU1@mid.individual.net> Message-ID: <1183406772.091375.89830@c77g2000hse.googlegroups.com> On Jul 2, 1:58 pm, Bjoern Schliessmann wrote: > 7stud wrote: > > Thanks for the response. So are you saying that the only way you > > can get data out of a pipe is when the subprocess has terminated? > > No, not only because Pipes aren't related to processes in any > special way. > > He said that you can't write to a pipe whose reader has already > terminated. > What he said was: >...once the subprocess terminates (which it must have done for >p.stdout.read() to return a result) And based on the results of the examples I posted in my last post, it seems to confirm that no data travels through a pipe until a program on one side of the pipe has terminated. From bdesth.quelquechose at free.quelquepart.fr Tue Jul 10 23:12:55 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 11 Jul 2007 05:12:55 +0200 Subject: xml yml and dependency hell In-Reply-To: References: <4693D100.1000209@web.de> Message-ID: <4693d9fd$0$27791$426a74cc@news.free.fr> Rustom Mody a ?crit : > On 7/11/07, Stefan Behnel wrote: > >> Rustom Mody wrote: > > >> > So is it likely that yaml will make it to the standard python library >> > at some point?? >> >> That's up to the maintainers of PyYAML. If they want to get it in, >> there will >> be ways to get there. If they do not want to - unlikely, unless >> someone else >> takes up the work. But it's definitely easier if the authors decide to >> put it in. > > > Is this a general comment or specific to yaml? I mean can anyone add > anything they please to the python standard library? No, definitively. But the process is supposed to be initiated by the maintainers. Have a look at pep 0002 for more informations. From gopi420 at gmail.com Thu Jul 19 02:26:39 2007 From: gopi420 at gmail.com (Anmolads) Date: Thu, 19 Jul 2007 06:26:39 -0000 Subject: A new Classifieds Website has been Launched. Message-ID: <1184826399.485058.45750@z24g2000prh.googlegroups.com> A new Classifieds Website has been Launched. Place Full page Ad for free at Anmolads.com http://www.Anmolads.com Get your desired Job from our Job Portal... www.Anmoljobs.com/forum Logon to www.anmolads.com for further details. Place Full Page For Free at www.Anmolads.com , www.earnyourcash.com , www.eternaldating.com , www.voiptechnocrats.com/forum , www.anmoljobs.com/forum From http Fri Jul 20 12:28:04 2007 From: http (Paul Rubin) Date: 20 Jul 2007 09:28:04 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <7x8x9lwka9.fsf@ruckus.brouhaha.com> Message-ID: <7xbqe7ox9n.fsf@ruckus.brouhaha.com> Steve Holden writes: > The issue I have with correctness proofs (at least as they were > presented in the 1980s - for all I know the claims may have become > more realistic now) is that the proof of correctness can only relate > to some highly-formal specification so complex that it's only > comprehensible to computer scientists. Just like software as it is now, is only comprehensible to programmers. A long while back there was a language called COBOL designed to be comprehensible to non-programmers, and it actually did catch on, but it was cumbersome and limited even in its time and in its application era, not so readable to non-programmers after all, and is not used much in new projects nowadays. > In other words, we can never "prove" that a program does what the > customer wants, because the semantics are communicated in different > ways, involving a translation which, since it is necessarily performed > by humans using natural language, will always be incomplete at best > and inaccurate at worst. The types of things one tries to prove are similar to what is less formally expressed as localized test cases in traditional software. E.g. for a sorting routine you'd want to prove that output[n+1] >= output[n] for all n and for all inputs. As the Intel FDIV bug incident reminds us, even billions of test inputs are not enough to show that the routine does the right thing for EVERY input. From jjl at pobox.com Sat Jul 21 10:40:07 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 21 Jul 2007 14:40:07 GMT Subject: code packaging References: <7xfy3jpem8.fsf_-_@ruckus.brouhaha.com> Message-ID: <87y7h9n7lk.fsf@pobox.com> Paul Rubin writes: [...] > I'm now wondering where this type of thing is best addressed in more > general terms. What I usually see happening, in projects I've worked > on and in others, is that developers get the code working on their own > computers, using source control tools and (if we're lucky) tests > developed in parallel with the code, but without much attention to > final packaging until the very end when the code is about to be > shipped. > > Is this appropriate? Inappropriate? Do your projects start using > serious packaging and distribution tools very early in development, > before the code is anywhere near usable? Should they? > > I'm involved in something that I wish was that way, mainly because I > really don't have any way to put a complete installation on my own > computers; I have to develop my subsystem more or less independently > of the overall app, then toss stuff over the wall to the more central > application guys for integration, which gets slow sometimes because > we're distributed all over. This is a fairly complex server app that > depends on a lot of external packages and programs running across > multiple machines, so I could see the packaging problem being messy. > It would cause a significant interruption in development to try to > package things so that the non-central developers could install and > hack it without a lot of assistance. But I think it would be > worthwhile given how much easier it would become to test changes. We > do plan to bundle up and release the code sometime (maybe as a Debian > package) but for now that's deferred until the code is more complete > and stable. > > I'm wondering how other projects go about this. You can go further: in addition to developing a Debian package (or a few of them) for your own project, build your OS image using debootstrap (you'll probably want your own local repository(ies), for reproducibility). Then you do your development in a virtual machine or chroot environment. That way you develop in the same (or very similar) environment to the one in which your code will eventually be deployed (one difference being the use of an version control checkout rather a .deb install for the code you're actually working on, unless troubleshooting problems that are somehow tied up with that particular aspect of deployment). I've seen this working in a real-world project. Of course, you can set up a server that does a complete build-and-test every night, and a separate continuous integration server that just does an "svn up" (rather than a full rebuild) every time somebody checks in, so that test failures can be detected quickly and the guilty party suitably humiliated :-) John From goldtech at worldpost.com Sat Jul 21 23:03:17 2007 From: goldtech at worldpost.com (leegold) Date: Sat, 21 Jul 2007 20:03:17 -0700 Subject: Sort lines in a text file Message-ID: <1185073397.821811.143260@k79g2000hse.googlegroups.com> say I have a text file: zz3 uaa4a ss 7 uu zz 3 zzzz66 ppazz9 aaaaaaaaa00000zz0 I want to sort the text file. I want the key to be the number after the two "zz". Or I guess a string of two zz then a number....So that's 3, 9, 0 I'm trying to say that I want to sort lines in a file based on a regular expression. How could I do that in Python? I'm limited to Python 2.1, I can't add any 2nd party newer tools. Thanks Lee G. From nagle at animats.com Mon Jul 16 20:47:49 2007 From: nagle at animats.com (John Nagle) Date: Tue, 17 Jul 2007 00:47:49 GMT Subject: Fetching a clean copy of a changing web page In-Reply-To: <1184566190.197725.296610@n60g2000hse.googlegroups.com> References: <1184566190.197725.296610@n60g2000hse.googlegroups.com> Message-ID: Miles wrote: > On Jul 16, 1:00 am, John Nagle wrote: > >> I'm reading the PhishTank XML file of active phishing sites, >>at "http://data.phishtank.com/data/online-valid/" This changes >>frequently, and it's big (about 10MB right now) and on a busy server. >>So once in a while I get a bogus copy of the file because the file >>was rewritten while being sent by the server. >> >> Any good way to deal with this, short of reading it twice >>and comparing? >> >> John Nagle > > > Sounds like that's the host's problem--they should be using atomic > writes, which is usally done be renaming the new file on top of the > old one. How "bogus" are the bad files? If it's just incomplete, > then since it's XML, it'll be missing the "" and you should > get a parse error if you're using a suitable strict parser. If it's > mixed old data and new data, but still manages to be well-formed XML, > then yes, you'll probably have to read it twice. The files don't change much from update to update; typically they contain about 10,000 entries, and about 5-10 change every hour. So the odds of getting a seemingly valid XML file with incorrect data are reasonably good. John Nagle From jstroud at mbi.ucla.edu Mon Jul 30 16:37:20 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 30 Jul 2007 13:37:20 -0700 Subject: OOP in Python book? In-Reply-To: References: <1185550866.950455.61240@g12g2000prg.googlegroups.com> Message-ID: Dick Moores wrote: > At 01:27 PM 7/28/2007, Dennis Lee Bieber wrote: > >> On Fri, 27 Jul 2007 16:27:57 -0700, Dick Moores >> declaimed the following in comp.lang.python: >> >> >> > Well, the publisher is Prentice Hall, "The world's leading >> > educational publisher". Textbooks are typically expensive. >> > >> >> Yeah... But at that price it should have hard-covers! > > > Should have, but look at this popular Cultural Anthropology text > (paperback): . List price is $120.95 USD. > (BTW I just bought the 6th edition online for about $10.) > > Then there's Calculus: Single Variable (Paperback) > List price $123.95 USD. > > And so it goes. > > Dick > > Balme your professors. They are not paying for the books. Of course most will be give a lot of lip-service to educational access for disadvantaged groups but thier choice of books usually suggests otherwise. The high price of textbooks and the tendency for professors to overlook alternatives is helping to keep the rich educated and the poor, well, poor. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From mccredie at gmail.com Mon Jul 23 20:39:34 2007 From: mccredie at gmail.com (Matt McCredie) Date: Mon, 23 Jul 2007 17:39:34 -0700 Subject: pylint style convention In-Reply-To: <46a53823$0$3769$80265adb@spool.cs.wisc.edu> References: <46a53823$0$3769$80265adb@spool.cs.wisc.edu> Message-ID: <9e95df10707231739g3d8b916cu98cbd62530625954@mail.gmail.com> > > Which style convention is it referring to? Should these really be all > caps? > I think pylint is expecting that any variables declared outside of a function should be constants with special meanings (similar to #define or enum values in c). So, I guess to get rid of that message you should do something like this: def main(args=None): if args is None: args = sys.argv parser = optparse.OptionParser(usage='usage: %prog [OPTIONS]') parser.add_option('-c', '--config', action='store', type='string', dest='configFilename', help='config file containing defaults') (options, args) = parser.parse_args(args) if "__main__" == __name__: sys.exit(main()) Here is an article by GvR that goes over main functions in python: http://www.artima.com/weblogs/viewpost.jsp?thread=4829. You didn't really ask for it, but I think it is good reading. His examples all use getopt though, instead of optparse. I have come up with my own (probably overkill for 99% of python scripts) template that uses optparse. If you really want to see it let me know and I will send it to you. Matt -------------- next part -------------- An HTML attachment was scrubbed... URL: From HDoran at air.org Wed Jul 25 15:19:35 2007 From: HDoran at air.org (Doran, Harold) Date: Wed, 25 Jul 2007 15:19:35 -0400 Subject: Output to csv Message-ID: <2323A6D37908A847A7C32F1E3662C80EE58016@dc1ex01.air.org> I've hacked together a small utility program that I assume can be written much better. The program reads in output from a statistical program and spits out the relevant data needed. The purpose of the program is to reach into the original data file (which is a text file), pull out the relevant informaiton, and spit out a file that can be opened in Excel in order to create tables for some reports we need. To accomplish this, I enter in commas by brute force so that the output is a csv file that excel can open. This program works fine, but, as I am still learning python, I am interested in ways to write better code. If anyone has any suggestions, they are most appreciated. Below is the program in its current form. Harold filename = raw_input("Please enter the WinSteps ISF file: ") new_file = raw_input("Enter the name of the csv file to output: ") # create a new file defined by the user f = open(new_file, 'w') f.write("Num, Measure, SE, Measure, SE, Measure, SE, Measure, SE \n") params = open(filename, 'r') for line in params: x = line if x[15] == '1': print >> f, x[4:6], ',' ,x[39:47], ',' ,x[49:55], ',,,' elif x[15] == '2': print >> f, x[4:6], ',' ,x[39:47], ',' ,x[49:55], ',' ,x[90:97], ',' ,x[99:105], ',,' elif x[15] == '3': print >> f, x[4:6], ',' ,x[39:47], ',' ,x[49:55], ',' ,x[90:97], ',' ,x[99:105], ',' ,x[140:147], ',' ,x[149:155], ',' elif x[15] == '4': print >> f, x[4:6], ',' ,x[39:47], ',' ,x[49:55], ',' ,x[90:97], ',' ,x[99:105], ',' ,x[140:147], ',' ,x[149:155], ',',x[190:197], ',' ,x[199:205] f.close() -------------- next part -------------- An HTML attachment was scrubbed... URL: From itkong247 at gmail.com Sat Jul 28 16:49:01 2007 From: itkong247 at gmail.com (itkong) Date: Sat, 28 Jul 2007 20:49:01 -0000 Subject: great new site for IT GURUS - www.itkong.com Message-ID: <1185655741.466554.108860@z24g2000prh.googlegroups.com> Check out this site - WWW.ITKONG.COM. Focused solely on the community of IT specialists, web developers, technological experts, companies and individuals alike. Currently we are up and running in our beta phase, taking care of final minor bugs tightening loose screws and slowly getting the word out about our existence. I hope it is of some help and we welcome your feedback. Team ITkong From steve at REMOVE.THIS.cybersource.com.au Thu Jul 5 18:50:36 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 06 Jul 2007 08:50:36 +1000 Subject: Embedded For Loop With No Data References: Message-ID: On Thu, 05 Jul 2007 22:03:59 +0000, rshepard wrote: > Haven't found an answer to my question in the books and other docs I have > available, so I am asking here. > > I have three lists of data retrieved from database tables. I want to cycle > through all three lists using nested FOR loops. What is the behavior if > there are no data in the list used in the middle loop? Why don't you try it and see for yourself? types = ["Type A", "Type B", "Type C"] subtypes = [] details = [1, 2, 3] > Example: > > for a in types: > for b in subtypes: > for c in details: > do some processing > > Not every item in the 'types' list will have an associated 'subtype'. Does > the index ignore that loop and drop to the one nested beneath it? Be sure to write back and let us know what you discover. -- Steven. From nagle at animats.com Fri Jul 20 14:29:21 2007 From: nagle at animats.com (John Nagle) Date: Fri, 20 Jul 2007 11:29:21 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7x4pjzjzfm.fsf@ruckus.brouhaha.com> References: <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <7x8x9lwka9.fsf@ruckus.brouhaha.com> <1184914601.872554.19720@n2g2000hse.googlegroups.com> <7x4pjzjzfm.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Kay Schluehr writes: > >>Sure. But knowing that memory is limited doesn't buy you much because >>you achieve an existential proof at best: you can show that the >>program must run out of memory but you have to run the program to know >>where this happens for arbitrary input values. Moreover you get always >>different values for different memory limits. So in the general case >>you can't improve over just letting the program run and notice what >>happens. > > > Program verification is nothing like the halting problem. It's not > done by dropping the program into some tool and getting back a proof > of correctness or incorrectness. The proof is developed, by the > programmer, at the same time the program is developed. Verifiability > means that the programmer-supplied proof is precise enough to be > checked by the computer. > > Think of when you first learned to program. Most non-programmers have > an idea of what it means to follow a set of steps precisely. For > example they could tell you an algorithm for sorting a shelf full of > books alphabetically by author. Programming means expressing such > steps in much finer detail than humans usually require, to the point > where a machine can execute it; it takes a lot of patience and > knowledge of special techniques, more than non-programmers know how to > do, but we programmers are used to it and even enjoy it. > > Now think of something like a code review. There is a line of code in > your program (maybe even an assert statement), that depends on some > variable "x" being greater than 3. You must have had a reason for > thinking x>3 there, so if the reviewer asks why you thought that, you > can explain your argument until the reviewer is convinced. > > Do you see where this is going? Code verification means expressing > such an argument in much finer detail than humans usually require, to > the point where a machine can be convinced by it; it takes a lot of > patience and knowledge of special techniques, more than most of us > regular "practical" programmers currently know how to do, but the > methods are getting more accessible and are regularly used in > high-assurance software. In any case there is nothing magic about > it--just like programming, it's a means of expressing precisely to a > machine what you already know informally how to express to a human. Ah. At last, an intelligent comment about program proving. One of the biggest problems with proof of correctness is that, as a first step, you need a language where you don't have to "lie to the language". That is, the language must have sufficient power to express even the ugly stuff. Python isn't bad in that regard. A good example is the "struct" module, where you can explicitly convert a string of bytes into a Python tuple. That's an inherently risky operation, but Python has a safe and unambiguous way to express it that doesn't depend on the machine representation of Python types. In C and C++, this is often done using casts, and what's going on is neither explicit nor checked. Note that it's quite possible to implement something like the "struct" module for C, and it could even be compiled into hard code. (GCC, for example, knows about "printf" strings at compile time, so that's not an unacceptable idea.) The big problem with C and C++ in this area is the "array=pointer" convention. Again, that's lying to the compiler. Programmers have to write "char* p" which is a pointer to a char, when they mean an array of characters. That's inherently wrong. It was a good idea in the 1970s when it was developed, but we know better now. If you were doing proofs of correctness for Python, the biggest headache would be checking for all the places where some object like a module or function might be dynamically modified and making sure nobody was patching the code. Enough on this issue, though. John Nagle From james.harris.1 at googlemail.com Wed Jul 4 14:46:00 2007 From: james.harris.1 at googlemail.com (James Harris) Date: Wed, 04 Jul 2007 11:46:00 -0700 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: <1183574760.225389.266470@o61g2000hsh.googlegroups.com> On 1 Jul, 15:11, "Peter J. Holzer" wrote: ... > Stick to unix timestamps but store them as a double precision floating > point number. The 53 bit mantissa gives you currently a resolution of > about 200 ns, slowly deteriorating (you will hit ms resolution in about > 280,000 years, if I haven't miscalculated). Any language and database > should be able to handle double-precision FP numbers, so that's as > portable as it gets and conversion from/to system time should be > trivial. > > If you need to represent milliseconds exactly, you can just multiply the > timestamp with 1000 (and get java timestamps). Interesting option. I think my choice is between separate day and sub- day 32-bit unsigned integers, text, and this 64-bit float option. I'm not clear, though. Did you mean to store double precision numbers where the seconds are the units (I assume this) or where the days are the units? And what do you think of the other option? From carsten at uniqsys.com Fri Jul 13 09:34:41 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 13 Jul 2007 09:34:41 -0400 Subject: Fast powerset function In-Reply-To: <20070713120150.M89148@uniqsys.com> References: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> <7xodigr6xk.fsf@ruckus.brouhaha.com> <20070713120150.M89148@uniqsys.com> Message-ID: <1184333681.3372.6.camel@dot.uniqsys.com> On Fri, 2007-07-13 at 08:15 -0400, I wrote: > [...] > def recursive_powerset(s): > if not s: yield set() > for x in s: > s2 = s - set([x]) > for subset in recursive_powerset(s2): > yield subset > for subset in recursive_powerset(s2): > yield subset.union(set([x])) > [...] Pardon the soliloquy, but now that I'm a bit more awake, I realize that this is unnecessarily slow due to the duplicate invocation of the recursive call. Changing it thusly cuts the run time roughly in half: def recursive_powerset(s): if not s: yield set() for x in s: s2 = s - set([x]) for subset in recursive_powerset(s2): yield subset yield subset.union(set([x])) However, this doesn't change the fact that the iterative method blows the recursive method out of the water. -- Carsten Haese http://informixdb.sourceforge.net From stargaming at gmail.com Thu Jul 26 01:46:23 2007 From: stargaming at gmail.com (Stargaming) Date: 26 Jul 2007 05:46:23 GMT Subject: cls & self References: <1185419276.645373.83570@d30g2000prg.googlegroups.com> Message-ID: <46a8352e$0$24910$9b622d9e@news.freenet.de> On Thu, 26 Jul 2007 03:07:56 +0000, james_027 wrote: > hi, > > is cls & self the same thing? > > I have seen something like > > class A: > def dosomething(cls): > #doing something > > How is cls & self differ? How is it use? > > Thanks > james First, you have to understand that the choice of this name is *completely arbitrary*. You could call it self, cls, this, bogus, helloworld or whatsoever. The important thing is just: The first argument is (by default) the instance. Amongst python developers, many things aren't enforced by the language (eg. implicit `this` referencing the instance, as in other languages) but by conventions. It's just way more convenient to call it `self` always. We call it `cls` when speaking about classmethods. Your method there might have been headed by a line containing ``@classmethod``. See http://docs.python.org/lib/built-in-funcs.html#l2h-16 for classmethod and http://docs.python.org/tut/node11.html#SECTION0011400000000000000000 for this conventional stuff (paragraph "Often, the first argument ..."). HTH, Stargaming From andre.roberge at gmail.com Sun Jul 29 22:49:43 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Mon, 30 Jul 2007 02:49:43 -0000 Subject: Important new release (was: Crunchy security advisory) In-Reply-To: <1185664385.106256.59250@o61g2000hsh.googlegroups.com> References: <1185664385.106256.59250@o61g2000hsh.googlegroups.com> Message-ID: <1185763783.883122.131220@w3g2000hsg.googlegroups.com> A new release (0.9.2) containing a very important security fix is available for Crunchy, at http://code.google.com/p/crunchy Anyone using Crunchy *should* download this release. Fairly detailed information about the security issue can be found on the FAQ page included in Crunchy's release (viewable from Crunchy's left menu). Andr? Crunchy is an application that transforms an otherwise static html page into an interactive Python session. On Jul 28, 8:13 pm, Andr? wrote: > A security hole has been uncovered in Crunchy (version 0.9.1.1 and > earlier). > > Anyone using Crunchy to browse web tutorials should only visit sites > that are trustworthy. > > We are working hard at fixing the hole; a new release addressing the > problems that have > been found should be forthcoming shortly. > > Andr? > From ninja.krmenadl at nes.com Sat Jul 7 18:39:50 2007 From: ninja.krmenadl at nes.com (Boris Ozegovic) Date: Sun, 8 Jul 2007 00:39:50 +0200 Subject: httplib module Message-ID: Why do I get double new lines when geting data from server? Example: I have a following file: ------start------------- Ovo je testni primjerak ------end--------------- And the code is: conn = httplib.HTTPConnection("localhost:8000") conn.request("GET", "/folder/index.html") response = conn.getresponse() reply = response.read() print reply \n\n\n\nOvo je testni primjerak\n\n\n\n\n\n -- Ne dajte da nas la?ljivac Bandi? truje: http://cnn.blog.hr/arhiva-2007-06.html#1622776372 From martin.laloux at gmail.com Tue Jul 10 07:28:16 2007 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: Tue, 10 Jul 2007 04:28:16 -0700 Subject: Choosing Tkinter over wxPython... In-Reply-To: References: <3e384$4692a3c4$4275d90a$11745@FUSE.NET> Message-ID: <1184066896.830365.135140@o61g2000hsh.googlegroups.com> me to because of the problem of the new versions of wxpython not compatible with the old ones (try to run a script done with wxpython 3, 4, 5 even 6 with wxpython 2.8.x). Each time, I must re-examine all my old scripts. Tkinter, although less beautiful, is more stable From Brad.Johnson at ballardtech.com Thu Jul 26 13:31:52 2007 From: Brad.Johnson at ballardtech.com (Brad Johnson) Date: Thu, 26 Jul 2007 10:31:52 -0700 Subject: Problem Embedding Python in small Win32 App Message-ID: I am just entering the world of Python embedding and I am running into a bug I am having a hard time fixing. Please be gentle. I am creating a small test application in Windows to test the embedding of the interpreter in order to execute arbitrary Python statements and print their results, all via a dialog application. Strings are sent to the interpreter via: PyRun_String(CString(*pbstrInput), Py_file_input, _d, _d); Where _d is my global dictionary. I would like to capture the output, so I created a small class to extend Python PyRun_String("class OutputCatcher:\n" "\tdef __init__(self):\n" "\t\tself.data=''\n" "\tdef write(self, stuff):\n" "\t\tself.data = stuff\n\n" "import sys\n" "_outcatcher = OutputCatcher()\n" "sys.stdout = _outcatcher\n", Py_file_input, _d, _d); Using this class, I thought I could access "_outcatcher.data" to get the last thing written to sys.stdout, and this does seem to work using the following code: PyObject* o = PyDict_GetItemString(_d, "_outcatcher"); PyObject* a = PyObject_GetAttrString(o, "data"); ::MessageBox(NULL, PyString_AsString(a), _T(""), NULL); However, it only works twice. On the third try, I get an access violation trying to access the stdout object (for a print statement). The pointer appears to be valid, but all of the data has overwritten with 0xDBDBDBDB, with obvious consequences. Thanks for any help. ~Brad Johnson -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Mon Jul 30 04:09:54 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 30 Jul 2007 08:09:54 GMT Subject: How to write GUI and event separately in wxPython?? References: <1185777254.925902.204500@z28g2000prd.googlegroups.com> Message-ID: <5h5kmiF3hmufcU3@mid.uni-berlin.de> On Sun, 29 Jul 2007 23:34:14 -0700, Jia Lu wrote: > I am making an application with wxpython. > But I got a problem when I want to change the display string > according to process status. > > I passed the frame to the processing function and use the > frame.txtobj to change displaying strings. > > I found it is a bad method to do that. > Can any one tell me how to do that usually? > ( How to separate GUI and Control code? ) One possibility here is to give a callback function into the worker function that gets called while the function does it's work. Simple example: def do_work(arguments, callback=lambda msg: None): callback('Start processing.') for percent in xrange(0, 101): callback('finished %d%%...' % percent) callback('Done.') Ciao, Marc 'BlackJack' Rintsch From carsten at uniqsys.com Tue Jul 24 13:39:03 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 24 Jul 2007 13:39:03 -0400 Subject: exec and func_code In-Reply-To: References: Message-ID: <1185298743.3370.25.camel@dot.uniqsys.com> On Tue, 2007-07-24 at 13:24 -0400, Prepscius, Colin (IT) wrote: > Does anybody know how to pass parameters to 'exec > somefunction.func_code'? > > def f1(): > print 'this is f1' > > def f2(p): > print 'this is f2, p =', str(p) > > exec f1.func_code > THIS RESULTS IN: "this is nf1" WHICH IS NICE > > exec f2.func_code > THIS RESULTS IN: TypeError: f2() takes exactly 1 argument (0 given) > WHICH IS EXPECTED > > exec f2.func_code in {'p':34} > THIS RESULTS IN: TypeError: f2() takes exactly 1 argument (0 > given) ????? Why not just "f2(34)"? What problem are you trying to solve here? -- Carsten Haese http://informixdb.sourceforge.net From nagle at animats.com Mon Jul 16 01:00:36 2007 From: nagle at animats.com (John Nagle) Date: Mon, 16 Jul 2007 05:00:36 GMT Subject: Fetching a clean copy of a changing web page Message-ID: I'm reading the PhishTank XML file of active phishing sites, at "http://data.phishtank.com/data/online-valid/" This changes frequently, and it's big (about 10MB right now) and on a busy server. So once in a while I get a bogus copy of the file because the file was rewritten while being sent by the server. Any good way to deal with this, short of reading it twice and comparing? John Nagle From robert.rawlins at thinkbluemedia.co.uk Tue Jul 3 05:01:02 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Tue, 3 Jul 2007 10:01:02 +0100 Subject: DatePart From String Message-ID: <00e401c7bd50$aecb4960$0c61dc20$@rawlins@thinkbluemedia.co.uk> Hello Guys, I have a date/time as a string which looks like this: 2007-02-01 00:00:00 I'm trying to get my hands on the different date parts of that string in the following formats: Time Only: 00:00:00 Day As Number: 01 Month As Number: 02 Day As Word: Monday I've tried using the time.strptime() function without much success so thought I'd come and ask your advice. Thanks guys for any advice, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From evan at yelp.com Tue Jul 17 22:07:32 2007 From: evan at yelp.com (Evan Klitzke) Date: Tue, 17 Jul 2007 19:07:32 -0700 Subject: Semantics of file.close() In-Reply-To: <87veciem6f.fsf@mulj.homelinux.net> References: <1184628945.314844.53300@k79g2000hse.googlegroups.com> <87veciem6f.fsf@mulj.homelinux.net> Message-ID: On 7/17/07, Hrvoje Niksic wrote: > "Evan Klitzke" writes: > > > You should take a look at the man pages for close(2) and write(2) (not > > fclose). Generally you will only get an error in C if you try to close > > a file that isn't open. In Python you don't even have to worry about > > that -- if you close a regular file object more than once no exception > > will be thrown, _unless_ you are using os.close(), which mimics the C > > behavior. If you are out of space, in C you will get an error returned > > by the call to write (even if the data isn't actually flushed to disk > > yet by the kernel). I'm pretty sure Python mimics this behavior, so an > > exception would be called on the write, not on the close operation. > > But the writes are buffered, and close causes the buffer to be > flushed. file.close can throw an exception just like fclose, but it > will still ensure that the file is closed. Is this buffering being done by Python or the kernel? AFAIK, the kernel will return a ENOSPC on a write if there is no space left on a device, even if the device isn't _really_ full but will be full after the kernel writes in memory buffers to disk. So a close statement (in C) should never fail due to a lack of space -- that should be seen on the write syscall, even if the kernel is doing buffering. -- Evan Klitzke From carsten at uniqsys.com Fri Jul 13 13:56:51 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 13 Jul 2007 13:56:51 -0400 Subject: Fast powerset function In-Reply-To: <1184348304.043233.241780@22g2000hsm.googlegroups.com> References: <266557d0707122133j2453e0em1474059547fda3e9@mail.gmail.com> <7xodigr6xk.fsf@ruckus.brouhaha.com> <20070713120150.M89148@uniqsys.com> <1184348304.043233.241780@22g2000hsm.googlegroups.com> Message-ID: <1184349411.3372.12.camel@dot.uniqsys.com> On Fri, 2007-07-13 at 17:38 +0000, Jyotirmoy Bhattacharya wrote: > On Jul 13, 6:34 pm, Carsten Haese wrote: > > def recursive_powerset(s): > > if not s: yield set() > > for x in s: > > s2 = s - set([x]) > > for subset in recursive_powerset(s2): > > yield subset > > yield subset.union(set([x])) > > > Your recursive_powerset is buggy--it generates too many sets. The loop > over the elements of s is unnecessary. Here is one alternative: > > def recursive_powerset(s): > def do_recursive(S): > if not S: > yield set([]) > return > x=set(S.pop()) > for t in do_recursive(S): > yield t > yield t|x > return do_recursive(s.copy()) Right you are. Note however that x=set(S.pop()) should be x=set([S.pop()]) for this to run. Forget everything I've said about timing comparisons, the correct recursive implementation is actually faster than the iterative implementation I was testing. -Carsten From nagle at animats.com Tue Jul 3 01:03:21 2007 From: nagle at animats.com (John Nagle) Date: Mon, 02 Jul 2007 22:03:21 -0700 Subject: Python compilation ?? In-Reply-To: References: Message-ID: Evan Klitzke wrote: > On 7/2/07, Cathy Murphy wrote: > >> Is python a compiler language or interpreted language. If it is >> interpreter >> , then why do we have to compile it? > > > It's an interpreted language. It is compiled into bytecode (not > machine code) the first time a script is run to speed up subsequent > executions of a script. CPython compiles to an intermediate form, rather than all the way to machine code, and executes the intermediate form, which is basically a tree, with an interpreter written in C. ShedSkin Python compiles to C++, then all the way to machine code. Some CPython features have to be disallowed, but there's a huge performance gain. Jython compiles to Java byte code, which is then compiled to machine code by a just-in-time compiler. Iron Python compiles to Microsoft's byte code as used by their ".NET" common language runtime. This is then compiled to machine code by a just-in-time compiler. John Nagle From apatheticagnostic at gmail.com Wed Jul 11 04:24:55 2007 From: apatheticagnostic at gmail.com (kaens) Date: Wed, 11 Jul 2007 04:24:55 -0400 Subject: Visualizing a wav file? In-Reply-To: <46948baa$0$79693$dbd41001@news.wanadoo.nl> References: <46948baa$0$79693$dbd41001@news.wanadoo.nl> Message-ID: <163f0ce20707110124y3a3be5ddvfa60d097f0641115@mail.gmail.com> On 7/11/07, Wim Vogelaar wrote: > Perhaps you can use parts/routines of Audacity. > See: http://en.wikipedia.org/wiki/Audacity > > Wim Vogelaar, http://home.wanadoo.nl/w.h.vogelaar/ > > > -- > http://mail.python.org/mailman/listinfo/python-list > I'm aware of audacity. Correct me if I'm wrong, but I don't think Audacity is written in Python, although I think someone wrote a way to script it a bit using python. While looking at their code might prove useful to me, I'm looking for a way to implement this in python. To provide a clearer (and audacity related) example, I'd like to be able to show the waveform as it's playing - like if you zoomed in decently far on a sample in audacity while playing it back. If I can accomplish that, I think I can figure out most of the other stuff I'd like to do on my own. Just looking for some points in the right direction. From gagsl-py2 at yahoo.com.ar Thu Jul 5 21:28:18 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Jul 2007 22:28:18 -0300 Subject: Htmllib help References: <070520072323.4867.468D7D5C000207F00000130322058861720D010C0E06A10407020E@comcast.net> Message-ID: En Thu, 05 Jul 2007 20:23:08 -0300, escribi?: > I am using html and formater as shown below. They are used as part of a > larger program. > > Even though I don't use any print statements, the htmllib seems to be > throwing parts of the html page on to the standard out(my screen in this > case). Is there a way to disable the output? > > import htmllib > w = formatter.DumbWriter() Change the above line. From http://docs.python.org/lib/writer-impls.html: "class DumbWriter([file[, maxcol = 72]]) Simple writer class which writes output on the file object passed in as file or, if file is omitted, on standard output." (From your code fragment it appears that you are not interested in any output - in that case you don't need the writer at all. And maybe you can use another parser, like HTMLParser.HTMLParser, so I'd ask why do you use a writer in the first place?) -- Gabriel Genellina From hniksic at xemacs.org Thu Jul 19 04:27:43 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Thu, 19 Jul 2007 10:27:43 +0200 Subject: Interpreting os.lstat() References: <1184806559.224636.266500@e9g2000prf.googlegroups.com> Message-ID: <87vecger28.fsf@mulj.homelinux.net> Adrian Petrescu writes: > I checked the online Python documentation at http://python.org/doc/1.5.2/lib/module-stat.html > but it just says to "consult the documentation for your system.". The page you're looking for is at http://www.python.org/doc/current/lib/os-file-dir.html . For lstat it says "Like stat(), but do not follow symbolic links." For stat it says: 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) [...] 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.) From m.elston at advantest-ard.com Wed Jul 18 19:37:03 2007 From: m.elston at advantest-ard.com (Mark Elston) Date: Wed, 18 Jul 2007 16:37:03 -0700 Subject: Exiting from python shell In-Reply-To: References: <469e8068$0$8912$88260bb3@free.teranews.com> Message-ID: <139t910dmac5i37@corp.supernews.com> * James Stroud wrote (on 7/18/2007 4:27 PM): > Tobiah wrote: >> For years now, I've been exiting the shell by typing 'exit\n', >> being chid by the shell, and then typing ^D. I can't >> remember a time that I typed the ^D the first time. Call >> me an idiot if you must, but since someone took the trouble >> to catch the command 'exit' in a special way, would it have >> been so awful to just let it be a way to exit when the shell? >> >> Thanks, >> >> Toby >> > > Yes, this would have required a ground-up approach to redesigning the > python language, transmuting it to something like a cross between lisp > and COBOL and would have rendered it impossible to author with C because > of the way C implements pointers--hardcoding in assembly would likely be > required. Beyond that, exiting an interpreter is not known in computer > science and has been shown impossible by Goedel himself in a series of > monographs on the topic. Thus, to exit python via a keyword would > require also reformulating mathematics as we know it. Furthermore, such > a change would propagate itself, via the observer effect, to the > behavior of sub atomic particles via ill-defined quantum-mechanical > affects and would likely result in the reversal of the Second Law of > Thermodynamics, wherein your refrigerator would end up heating its > contents and milk would spontaneously spoil, among other anomalies. > > For these reasons, you might propose a "quit" keyword. > > James > You know, some answers simply *must* be saved for posterity.... Mark From evan at yelp.com Thu Jul 12 18:58:10 2007 From: evan at yelp.com (Evan Klitzke) Date: Thu, 12 Jul 2007 15:58:10 -0700 Subject: How to create new files? In-Reply-To: <-dGdnQZsf9R5OwvbnZ2dnUVZ_jydnZ2d@comcast.com> References: <1184274877.612434.26870@k79g2000hse.googlegroups.com> <-dGdnQZsf9R5OwvbnZ2dnUVZ_jydnZ2d@comcast.com> Message-ID: On 7/12/07, Larry Bates wrote: > sizeof() in Python is len() No, sizeof in C/C++ is not like len (len is more like strlen). For example, on my computer compiling #include #include int main(int argc, char ** argv) { char * hello = "Hello World"; printf("sizeof: %d\n", sizeof(hello)); printf("strlen: %d\n", strlen(hello)); return 0; } prints out 11 for strlen but only 4 for sizeof because that is the size of a char *. AFAIK there isn't a true equivalent to sizeof in python (I hear there is an implementation in mxtools, however). -- Evan Klitzke From bj_666 at gmx.net Tue Jul 3 06:25:53 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Jul 2007 10:25:53 GMT Subject: 15 Exercises to Know A Programming Language References: <1183456696.168214.114900@o61g2000hsh.googlegroups.com> Message-ID: <5eumhhF39v66mU2@mid.uni-berlin.de> On Tue, 03 Jul 2007 09:58:16 +0000, Martin wrote: > "Write a program that takes as its first argument one of the words > 'sum,' 'product,' 'mean,' or 'sqrt' and for further arguments a > series of numbers. The program applies the appropriate function to > the series." > > My solution so far is this: > > http://dpaste.com/13469/ > > I would really like some feedback. Is this a good solution? is it > efficient? robust? what could be improved? any not looking for a > revised solution, hints on what to improve are also very welcome. Don't use `eval()` if it is not absolutely necessary. Especially if the input comes from a user it's a security hole. `float()` is the function to use here. `mean()` does not work as you try to divide a list by a number. Ciao, Marc 'BlackJack' Rintsch From kyosohma at gmail.com Wed Jul 11 13:05:23 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 11 Jul 2007 10:05:23 -0700 Subject: Embedding Matplotlib in wxpython wx.Panel problem In-Reply-To: References: <1177534801.938139.39220@r35g2000prh.googlegroups.com> Message-ID: <1184173523.808452.291500@r34g2000hsd.googlegroups.com> On Jul 10, 2:09 pm, abakshi11 wrote: > I was wondering if you ever got to create a small GUI program that did plots > using Matplotlib > I am gettin an error where its saying "WXagg's accelerator requires the > wxPython headers-the wxpython header files can not be located in any of the > standard include directories reported by 'wx-config --cppflags' > Do you think you can help? > > > > Soren-3 wrote: > > > Hi, > > > I'm trying to create a small GUI program where I can do plots using > > Matplotlib. I've been trying to borrow code from the examples at the > > matplotlib website, but I can't get it to work. > > > I want to be able to create a wx.Panel that contains an axis for > > plotting. Around it i want other panels containing various settings, > > buttons etc. to control the plot. So far I can't even get the program > > to actually show a plot in a panel. > > > Does anyone here have experience in making a wxpython GUI with > > matplotlib? > > > Any help would be appreciated! > > > Thanks, > > Soren > > > My code shows a frame, and I'm trying to set up two panels.. one with > > a plot and one with a button.. The plotpanel is just a little square > > in the corner when I run it.. ??? > > > My code is as follows: > > > import wx > > import pylab > > from matplotlib.numerix import arange, sin, cos, pi > > import matplotlib > > > matplotlib.use('WXAgg') > > from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg > > from matplotlib.backends.backend_wx import NavigationToolbar2Wx > > from matplotlib.figure import Figure > > matplotlib.interactive(False) > > > class App(wx.App): > > > def OnInit(self): > > self.frame = MainFrame("Autoplotter", (50,60), (700,700)) > > self.frame.Show() > > > return True > > > class MainFrame(wx.Frame): > > > def __init__(self, title, pos, size): > > wx.Frame.__init__(self, None, -1, title, pos, size) > > > pPanel = PlotPanel(self, -1) # Plot panel > > > bPanel = ButtonPanel(self, 100,500, (200,100)) # button > > panel > > > sizer = wx.BoxSizer(wx.VERTICAL) > > > sizer.Add(pPanel,0) > > sizer.Add(bPanel,0) > > > self.SetSizer(sizer) > > > class ButtonPanel(wx.Panel): > > > def __init__(self, Parent, xPos, yPos, insize): > > > pos = (xPos, yPos) > > wx.Panel.__init__(self, Parent, -1, pos, style = > > wx.RAISED_BORDER, size = insize) > > > button = wx.Button(self, -1, 'HELLO!!', (10,10), (150,50)) > > > class NoRepaintCanvas(FigureCanvasWxAgg): > > """We subclass FigureCanvasWxAgg, overriding the _onPaint method, > > so that > > the draw method is only called for the first two paint events. > > After that, > > the canvas will only be redrawn when it is resized. > > """ > > def __init__(self, *args, **kwargs): > > FigureCanvasWxAgg.__init__(self, *args, **kwargs) > > self._drawn = 0 > > > def _onPaint(self, evt): > > """ > > Called when wxPaintEvt is generated > > """ > > if not self._isRealized: > > self.realize() > > > if self._drawn < 2: > > self.draw(repaint = False) > > self._drawn += 1 > > > self.gui_repaint(drawDC=wx.PaintDC(self)) > > > class PlotPanel(wx.Panel): > > > def __init__(self, parent, id = -1, color = None,\ > > dpi = None, style = wx.NO_FULL_REPAINT_ON_RESIZE, > > **kwargs): > > > wx.Panel.__init__(self, parent, id = id, style = style, > > **kwargs) > > > self.figure = Figure(None, dpi) > > self.canvas = NoRepaintCanvas(self, -1, self.figure) > > self._resizeflag = True > > > self.Bind(wx.EVT_IDLE, self._onIdle) > > self.Bind(wx.EVT_SIZE, self._onSize) > > > self._SetSize() > > > def draw(self): # just draw something! > > if not hasattr(self, 'subplot'): > > self.subplot = self.figure.add_subplot(111) > > theta = arange(0, 45*2*pi, 0.02) > > rad = (0.8*theta/(2*pi)+1) > > r = rad*(8 + sin(theta*7+rad/1.8)) > > x = r*cos(theta) > > y = r*sin(theta) > > #Now draw it > > self.subplot.plot(x,y, '-r') > > > def _onSize(self, event): > > self._resizeflag = True > > > def _onIdle(self, evt): > > if self._resizeflag: > > self._resizeflag = False > > self._SetSize() > > self.draw() > > > def _SetSize(self, pixels = None): > > """ > > This method can be called to force the Plot to be a desired > > size, which defaults to > > the ClientSize of the panel > > """ > > if not pixels: > > pixels = self.GetClientSize() > > self.canvas.SetSize(pixels) > > self.figure.set_figsize_inches(pixels[0]/ > > self.figure.get_dpi(), > > pixels[1]/self.figure.get_dpi()) > > > if __name__ == "__main__": > > > app = App(0) > > app.MainLoop() > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > -- > View this message in context:http://www.nabble.com/Embedding-Matplotlib-in-wxpython-wx.Panel-probl... > Sent from the Python - python-list mailing list archive at Nabble.com. You guys should post your wxPython problems to the wxPython user's list: http://www.wxpython.org/maillist.php They talk about plotting with matplot (and other modules) on there on a fairly regular basis. Mike From kar1107 at gmail.com Mon Jul 2 22:13:15 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: Mon, 02 Jul 2007 19:13:15 -0700 Subject: object references/memory access In-Reply-To: References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <1183407411.397142.304790@e16g2000pri.googlegroups.com> <1183417108.245203.158830@x35g2000prf.googlegroups.com> Message-ID: <1183428795.334268.36630@e9g2000prf.googlegroups.com> On Jul 2, 6:32 pm, Steve Holden wrote: > Karthik Gurusamy wrote: > > On Jul 2, 3:01 pm, Steve Holden wrote: > >> Karthik Gurusamy wrote: > >>> On Jul 1, 12:38 pm, dlomsak wrote: > >> [...] > > >>> I have found the stop-and-go between two processes on the same machine > >>> leads to very poor throughput. By stop-and-go, I mean the producer and > >>> consumer are constantly getting on and off of the CPU since the pipe > >>> gets full (or empty for consumer). Note that a producer can't run at > >>> its top speed as the scheduler will pull it out since it's output pipe > >>> got filled up. > >> But when both processes are in the memory of the same machine and they > >> communicate through an in-memory buffer, what's to stop them from > >> keeping the CPU fully-loaded (assuming they are themselves compute-bound)? > > > If you are a producer and if your output goes thru' a pipe, when the > > pipe gets full, you can no longer run. Someone must start draining the > > pipe. > > On a single core CPU when only one process can be running, the > > producer must get off the CPU so that the consumer may start the > > draining process. > > Wrong. The process doesn't "get off" the CPU, it remains loaded, and > will become runnable again once the buffer has been depleted by the > other process (which is also already loaded into memory and will become > runnable as soon as a filled buffer becomes available). > huh? "get off" when talking about scheduling and CPU implies you are not running. It is a common term to imply that you are not running -- doesn't mean it goes away from main memory. Sorry where did you learn your CS concepts? > > > >>> When you increased the underlying buffer, you mitigated a bit this > >>> shuffling. And hence saw a slight increase in performance. > >>> My guess that you can transfer across machines at real high speed, is > >>> because there are no process swapping as producer and consumer run on > >>> different CPUs (machines, actually). > >> As a concept that's attractive, but it's easy to demonstrate that (for > >> example) two machines will get much better throughput using the > >> TCP-based FTP to transfer a large file than they do with the UDP-based > >> TFTP. This is because the latter protocol requires the sending unit to > >> stop and wait for an acknowledgment for each block transferred. With > >> FTP, if you use a large enough TCP sliding window and have enough > >> content, you can saturate a link as ling as its bandwidth isn't greater > >> than your output rate. > > >> This isn't a guess ... > > > What you say about a stop-n-wait protocol versus TCP's sliding window > > is correct. > > But I think it's totally orthogonal to the discussion here. The issue > > I'm talking about is how to keep the end nodes chugging along, if they > > are able to run simultaneously. They can't if they aren't on a multi- > > core CPU or one different machines. > > If you only have one CPU then sure, you can only run one process at a > time. But your understanding of how multiple processes on the same CPU > interact is lacking. > huh? > > > > > >>> Since the two processes are on the same machine, try using a temporary > >>> file for IPC. This is not as efficient as real shared memory -- but it > >>> does avoid the IPC stop-n-go. The producer can generate the multi-mega > >>> byte file at one go and inform the consumer. The file-systems have > >>> gone thru' decades of performance tuning that this job is done really > >>> efficiently. > >> I'm afraid this comes across a bit like superstition. Do you have any > >> evidence this would give superior performance? > > > I did some testing before when I worked on boosting a shell pipeline > > performance and found using file-based IPC was very good. > > (some details athttp://kar1107.blogspot.com/2006/09/unix-shell-pipeline-part-2-using.... > > ) > > > Thanks, > > Karthik > > >>>> Thanks for the replies so far, I really appreciate you guys > >>>> considering my situation and helping out. > > If you get better performance by writing files and reading them instead > of using pipes to communicate then something is wrong. > Why don't you provide a better explanation for the observed behavior than to just claim that a given explanation is wrong? I did mention using real shared memory is better. I do know the cost of using a file ("physical disk movements") - but with the amount of buffering that goes on today's file-system implementations, for this problem, we will see big improvement. Karthik > 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 jayloden.com Tue Jul 17 17:44:51 2007 From: python at jayloden.com (Jay Loden) Date: Tue, 17 Jul 2007 17:44:51 -0400 Subject: Can a low-level programmer learn OOP? In-Reply-To: References: <7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com> Message-ID: <469D3853.5010308@jayloden.com> Steve Holden wrote: > It took a little bit more careful planning to get Icon pattern-matching > structures right, but there was much more explicit control of > backtracking. I only wish they'd grafted more OO concepts into it, then > I might never have bothered with Python! Someone did do an OO system > layered on top of it, but IIRC it was clumsy and rebarbative. OT, but I just wanted to say, "rebarbative" is my word of the day for today thanks to this post. I consider myself to have a reasonably comprehensive vocabulary but that's a new one for me, so I had to look it up after your post ;) -Jay From carsten at uniqsys.com Fri Jul 6 12:05:42 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 06 Jul 2007 12:05:42 -0400 Subject: Expandable 2D Dictionaries? In-Reply-To: <1183736635.415927.208450@57g2000hsv.googlegroups.com> References: <1183736635.415927.208450@57g2000hsv.googlegroups.com> Message-ID: <1183737942.3339.14.camel@dot.uniqsys.com> On Fri, 2007-07-06 at 15:43 +0000, Robert Dailey wrote: > Hi, > > I am interested in creating an expandable (dynamic) 2D dictionary. For > example: > > myvar["cat"]["paw"] = "Some String" > > The above example assumes "myvar" is declared. In order for this to > work, I have to know ahead of time the contents of the dictionary. For > the above to work, my declaration must look like: > > myvar = {"cat": {"paw":""} } > > I would like to not have to declare my dictionary like this, as it > does not allow it to be expandable. I'm very new to Python (I'm a > professional C++ programmer. Any comparisons to C++ would help me > understand concepts). > > Is there a way that when I index into my dictionary using an "unknown" > index (string), that python will dynamically add that key/value pair? Sounds like a job for Python2.5's defaultdict: from collections import defaultdict class magicdict(defaultdict): def __init__(self): self.default_factory = magicdict myvar = magicdict() myvar["cat"]["paw"] = "Some String" -- Carsten Haese http://informixdb.sourceforge.net From tchur at optushome.com.au Wed Jul 18 21:32:13 2007 From: tchur at optushome.com.au (Tim Churches) Date: Thu, 19 Jul 2007 11:32:13 +1000 Subject: how to implementation latent semantic indexing in python.. In-Reply-To: <1184803885.142218.152490@g12g2000prg.googlegroups.com> References: <1184803885.142218.152490@g12g2000prg.googlegroups.com> Message-ID: <469EBF1D.3080604@optushome.com.au> malkarouri wrote: > On 13 Jul, 17:18, 78ncp wrote: >> hi... >> how to implementation algorithm latent semantic indexing in python >> programming...?? > > Of course you are aware that LSA is patented.. There is a US patent on it, sealed in 1989, but is it patented in any other countries? There is no such thing as a "global patent" - patents only cover the country which issues them. There is a global patent application process (the Patent Co-operation Treaty), but that just establishes a priority date for the invention in each country, but the inventor still needs to file patent applications and have them approved (sealed) is each and every country. Did Bellcore do that back in the 1980s? Tim C From kelvie at ieee.org Sat Jul 7 18:11:11 2007 From: kelvie at ieee.org (Kelvie Wong) Date: Sat, 7 Jul 2007 15:11:11 -0700 Subject: Restarting a Python Application In-Reply-To: <1183498045.092504.229250@m36g2000hse.googlegroups.com> References: <1183498045.092504.229250@m36g2000hse.googlegroups.com> Message-ID: <94ccbe710707071511o3beee718wc12f15082b3c6e18@mail.gmail.com> Ugh.. this would be a repost for the OP, but I forgot to hit "reply to all" again. This should do it: os.execv(sys.argv[0], sys.argv) Not sure how portable that statement is, though. On 7/3/07, kyosohma at gmail.com wrote: > Hi, > > I packaged up an application I am developing into an executable. In > the application, it has user configurable options. I would like a way > to restart the application so that the new options the user chooses > can be applied. Firefox can restart itself. Does anyone know how to > accomplish this in Python? > > Here is what I tried: > > > > exePath = os.path.join(os.getcwd(), 'myprogram.exe') > subprocess.Popen(exePath) > sys.exit() > > > > This didn't work. It closed the program, but another instance did not > appear. > > Tips would be appreciated. > > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Kelvie From evan at yelp.com Tue Jul 24 02:55:12 2007 From: evan at yelp.com (Evan Klitzke) Date: Mon, 23 Jul 2007 23:55:12 -0700 Subject: Code objects Message-ID: I was playing around with the inspect module tonight, and I have a question about "code components". Can an object have more than one code component? For example, will the following code ever create a list whose length is greater than one? import inspect # Some code here defining an object/function foo components = [cc[1] for cc in inspect.getmembers(foo,\ inspect.iscode)] -- Evan Klitzke From thomas at jollans.com Sun Jul 1 11:49:51 2007 From: thomas at jollans.com (Thomas Jollans) Date: Sun, 1 Jul 2007 17:49:51 +0200 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> Message-ID: <200707011749.51488.thomas@jollans.com> On Sunday 01 July 2007, Roedy Green wrote: > On 25 Jun 2007 18:46:25 -0700, Paul Rubin > wrote, quoted or indirectly quoted > > someone who said : > >You cannot accurately compute > >the number of seconds between Nixon's resignation and 1800 UTC today, > >unless you take into account the leap seconds have been occurred > >between then and now. > > There are two valid answers to those questions. In a court of law, > say did some document arrive before deadline, you must use civil > time. Arguing leap seconds would not fly. > > On the other hand, if you used civil seconds to computer satellite > orbits, tiny errors mount up quickly in the calculation. "civil" time/seconds ? I dare say that if they exist, they are variably defined. I know for a fact that here in Germany, official time is based on UTC, NOT UT (was GMT) or some other approximation of local time. Ergo, you *can* argue leap seconds in a court of law as they *are* "civil time". In fact Wikipedia [1] makes it sound like UTC is used in the US, and as leap seconds are part of UTC, you could probably argue with them in a US court as well Also, UTC and UT/GMT are always less than a second apart, so who cares... [1] http://en.wikipedia.org/wiki/Eastern_Time_Zone etc. From torriem at chem.byu.edu Sat Jul 28 19:34:06 2007 From: torriem at chem.byu.edu (Michael L Torrie) Date: Sat, 28 Jul 2007 17:34:06 -0600 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? In-Reply-To: <0T49ish0ItfaNv8%stesch@parsec.no-spoon.de> References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> <0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de> <0T49iehiIt1hNv8%stesch@parsec.no-spoon.de> <46AB8194.2060906@web.de> <0T49il77ItapNv8%stesch@parsec.no-spoon.de> <0T49ish0ItfaNv8%stesch@parsec.no-spoon.de> Message-ID: <46ABD26E.1070305@chem.byu.edu> Stefan Scholl wrote: > Don't let the subject line fool you. I'm OK with cStringIO. The > thread is now about xml.sax's parseString(). Giving you the benefit of the doubt here, despite the fact that Stefan Behnel has state this over and over again and you just haven't listened. xml.sax's use of parseString() is exactly correct. xml.sax should *never* parse python unicode strings as by definition XML must be encoded as a *byte stream*, which is what a python string is. A python /unicode/ string could be held internally in any number of ways, 2, 3, 4, or even 8 bytes per character if the implementation demanded it (a bit contrived, I admit). Since the xml parser is only ever intended to parse *XML*, why should it ever know what to do with python unicode strings, which could be stored any number of ways, making byte-parsing impossible. So your code is faulty in its assumptions, not xml.sax. > > From bblais at bryant.edu Tue Jul 24 05:50:14 2007 From: bblais at bryant.edu (Brian Blais) Date: Tue, 24 Jul 2007 05:50:14 -0400 Subject: Tix not properly installed on OS X? Message-ID: <48B39FEC-D3B9-4FAF-AD45-0DD744D8D289@bryant.edu> Hello, I am running OS X 10.4, on an Intel Mac, Python 2.5 not installed by source (I used the binary install from the website). When I do the following, I get an error: 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 Tix >>> root=Tix.Tk() Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.5/lib/ python2.5/lib-tk/Tix.py", line 210, in __init__ self.tk.eval('package require Tix') _tkinter.TclError: can't find package Tix I read somewhere that that I need to install the Tcl Tix package, but I can't seem to find it. I looked at the source, at Sourceforge, and the directions seems a bit daunting, and I don't want to mess up something that is already there. Can someone help me? thanks, Brian Blais -- Brian Blais bblais at bryant.edu http://web.bryant.edu/~bblais -------------- next part -------------- An HTML attachment was scrubbed... URL: From martin at v.loewis.de Sun Jul 1 03:24:51 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 01 Jul 2007 09:24:51 +0200 Subject: How to uninstall packages In-Reply-To: References: Message-ID: <468756c4$0$24862$9b622d9e@news.freenet.de> > So now my question: How does one uninstall *cleanly* > > 1> a package installed using setup.py install > 2> a package installed with easy_install Run "setup.py install" with the --record option; then remove all files that have been recorded as installed. This is clean depending on the package being installed; a package may perform additional actions which don't get recorded in the --record option; in such a case, you need to study setup.py and find out what these additional actions are and how to revert them. Regards, Martin From duncan.booth at invalid.invalid Mon Jul 9 04:01:15 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Jul 2007 08:01:15 GMT Subject: Decorating instance methods References: Message-ID: Alexander Draeger wrote: > Hello everybody, > > I'm very interesting in using the decorator concept, but I can't > convert it in useful things. I have read many about decorators and > have seen a lot of examples, but I search a possibility, to decorate > methods of classes with reference to the instances. For example: > > I have a class A: > > class A(object): > def __init__(self, name): > self.name=name > > @logging > def hello(self, name): > print 'Hello World.' > > > > >>>a=A('Ernie') > >>>b=A('Bert') > >>>a.hello() > Entering a method. [Ernie] > Hello World. > > >>>b.hello() > Entering a method. [Bert] > Hello World. > > > How should I implement the function logging, when I want to use the > variable self.name for the logging message? > (Did you intend that other parameter to the hello method? If so you had better pass it in when you call the method.) Try this: >>> def logging(f): def deco(self, *args, **kw): print "Entering a method [%s]" % self.name return f(self, *args, **kw) return deco >>> class A(object): def __init__(self, name): self.name=name @logging def hello(self, name): print 'Hello World.' >>> a=A('Ernie') >>> a.hello('world') Entering a method [Ernie] Hello World. From abhins4 at gmail.com Sat Jul 7 10:04:59 2007 From: abhins4 at gmail.com (Abhishek Jain) Date: Sat, 7 Jul 2007 19:34:59 +0530 Subject: How would I write this C code in Python? In-Reply-To: References: <1183743110.399675.180570@n60g2000hse.googlegroups.com> Message-ID: how would MAXBUFFERSIZE be taken care in python; --abhi On 7/7/07, Steven D'Aprano wrote: > > On Fri, 06 Jul 2007 17:31:50 +0000, DeveloperX wrote: > > > Python Attempt: Please note that since I can't type TABs online > > easily, I am using the @ character to represent TABs in the following > > Python code. > > Why not indent with spaces, just like you did for the example C code? > > > -- > Steven. > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From jmoy.matecon at gmail.com Thu Jul 5 17:21:36 2007 From: jmoy.matecon at gmail.com (Jyotirmoy Bhattacharya) Date: Thu, 05 Jul 2007 21:21:36 -0000 Subject: Extracting arbitrary amounts of data from a dictionary. In-Reply-To: <1183663916.635440.185720@e9g2000prf.googlegroups.com> References: <1183663916.635440.185720@e9g2000prf.googlegroups.com> Message-ID: <1183670496.169639.287310@n2g2000hse.googlegroups.com> On Jul 6, 12:31 am, robinsieb... at gmail.com wrote: > I had nothing better to do, so I thought I would make a database that > contained the songs played on the internet radio station I listen to > (hardradio.com) so I could see how many differents songs/artists they > played. > So I end up with a the number of times any given song by a given > artist is played in a day. Want I want to do is to be able to print > out a report for X number of weeks and I am trying to determine the > best way to interate through the 'week' key of the dictionary. > > For example, this is week 27, the dictonary has 6 'week' keys and I > want the data from the last 3 weeks. Is this the best way to iterate > through the dictionary? > > for date in dates[year][week].keys()[-3]: > > Or is there a better way with all the new features that have been > added to Python? Here is an implementation using as many 'new' features of Python as I could think of. http://phpfi.com/247634 From dr.death.tm at gmail.com Wed Jul 4 04:42:47 2007 From: dr.death.tm at gmail.com (ddtm) Date: Wed, 04 Jul 2007 01:42:47 -0700 Subject: Python IRC bot using Twisted In-Reply-To: References: <1183477890.690319.182400@m36g2000hse.googlegroups.com> Message-ID: <1183538567.128025.224430@q75g2000hsh.googlegroups.com> On 3 , 20:08, Jean-Paul Calderone wrote: > On Tue, 03 Jul 2007 15:51:30 -0000, ddtm wrote: > >On 3 , 17:55, Jean-Paul Calderone wrote: > >> On Tue, 03 Jul 2007 13:44:34 -0000, ddtm wrote: > >> >On 3 , 16:01, Jean-Paul Calderone wrote: > >> > [snip] > > >> >Thank you very much! It's a very useful information. One more > >> >question: can I cancel the DelayedCall using its ID (it is returned > >> >from callLater(...)) from another function? In example bot there are > >> >two functions: > >> >def joined(self, channel): > >> > ... > >> >def privmsg(self, user, channel, msg): > >> > ... > >> >For example, I add callLater(...) to joined(...) function and I'd like > >> >to cancel this in privmsg(...) function. What should I do? > > >> Yep. The object callLater returns has a `cancel' method (some others, too) > >> which will prevent the function from being called at the scheduled time. > > >> Jean-Paul > > >I know what you are talking about, but the question is: How can I > >cancel scheduled task in function that differs from > >function where I scheduled the task? Demo bot on Twisted website has a > >class with a bunch of predefined functions joined(...), privmsg(...) > >and so on. I can't see any method of communicating these functions. > >I'm new to Python and to Twisted framework. > >The task is: > >to call callLater(...) in joined(...) > >to cancel the task in privmsg(...) on special condition > > You need to preserve a reference to the object. For example: > > class IRCBot(Whatever): > def joined(...): > self.announceJoinedCall = reactor.callLater(...) > > def privmsg(...): > self.announceJoinedCall.cancel() > self.announceJoinedCall = None > > This skips over a bunch of details (what happens on multiple calls to > joined, what happens if privmsg is called after announceJoinedCall has > run, etc) but I hope it demonstrates the basic idea. > > Jean-Paul Thank you! Everything works great! From stesch at no-spoon.de Fri Jul 27 00:47:48 2007 From: stesch at no-spoon.de (Stefan Scholl) Date: Fri, 27 Jul 2007 06:47:48 +0200 Subject: Any reason why cStringIO in 2.5 behaves different from 2.4? References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de> <46A86C70.8040707@web.de> <0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de> <0T49cr71I3edNv8%stesch@parsec.no-spoon.de> <46A8AA57.4010802@web.de> <0T49dll7I4ilNv8%stesch@parsec.no-spoon.de> Message-ID: <0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de> Chris Mellon wrote: > XML is not a string. It's a specific type of bytestream. If you want > to work with XML, then generate well-formed XML in the correct > encoding. There's no reason you should have an XML document (as > opposed to values extracted from that document) in unicode objects at > all. The affected method in xml.sax is called parseString() From cbarton at metavr.com Mon Jul 2 00:11:12 2007 From: cbarton at metavr.com (Campbell Barton) Date: Mon, 02 Jul 2007 14:11:12 +1000 Subject: Tiny/small/minimalist Python? In-Reply-To: References: <1183332951.122782.212720@o11g2000prd.googlegroups.com> Message-ID: <46887AE0.6020509@metavr.com> Cameron Laird wrote: > In article <1183332951.122782.212720 at o11g2000prd.googlegroups.com>, > rtk wrote: >> I'm looking for information on building a tiny/small/minimalist/ >> vanilla python interpreter. One that implements the core language and >> a few of the key modules but isn't tied to any specific operating >> system. >> >> I guess I'm asking for the smallest subset of the standard Python >> source code files that is necessary to get a working interpreter using >> a plain C compiler. >> >> Is this even possible? If so, has someone done it already? I've >> looked on Google and in comp.lang.python but nothing comes up. > . > . > . > Tiny Python, PyMite, EmbeddedPython, Diet Python, deeply embedded > python, ...--I need to write up a page that explains these. Python binary/exe its self dosnt include much. if you get the full build and just remove modules, you can strip a lot out.. scripts that try import those files just wont work. From ptmcg at austin.rr.com Tue Jul 10 00:42:39 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Mon, 09 Jul 2007 21:42:39 -0700 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: References: Message-ID: <1184042559.120947.124560@k79g2000hse.googlegroups.com> On Jul 9, 11:21 pm, "Jim Langston" wrote: > In Python 2.5 on intel, the statement > 2**2**2**2**2 > evaluates to>>> 2**2**2**2**2 > > 200352993040684646497907235156025575044782547556975141926501697371089405955?63114 > 530895061308809333481010382343429072631818229493821188126688695063647615470?29165 > 041871916351587966347219442930927982084309104855990570159318959639524863372?36720 Exponentiation is right associative, so this is the same as: 2**(2**(2**(2**2))) 2**2**2**4 2**2**16 2**65536 2=10**0.3010, so 2**65536 is approx 10**19726 There are 19730 digits in your answer, so this seems to be at least in the ball park. -- Paul From mail at microcorp.co.za Fri Jul 27 03:26:03 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 27 Jul 2007 09:26:03 +0200 Subject: Pickled objects over the network References: <9c8d48280707192229y62ba2b38occ6614b966c75f66@mail.gmail.com><011401c7caa0$3e3e5900$03000080@hendrik><012901c7cb60$5ba530c0$03000080@hendrik><00c601c7cc38$d826ba00$03000080@hendrik><00bd01c7ccf6$8fa62540$03000080@hendrik> <7x4pjrbr32.fsf@ruckus.brouhaha.com> Message-ID: <01b201c7d024$d3f81740$03000080@hendrik> "Paul Rubin" wrote: > "Hendrik van Rooyen" writes: > > But more seriously - is there any need for a simple serialiser that will > > be able to be used to transfer a subset of the built in types over an > > open network in a safe manner, for the transfer of things like lists of > > parameters? > > > > Or am I the only person in the squad that hears this particular drum? > > This has been open for 5+ years: > > http://sourceforge.net/tracker/index.php?func=detail&aid=467384&group_id=5470&at id=355470 > > Related: > > http://sourceforge.net/tracker/index.php?func=detail&aid=471893&group_id=5470&at id=105470 Thanks for the links Paul - they are related, although not identical in requirements to the sort of thing I normally do - but it looks as if all the talking has not actually led to any action. : - ( - Hendrik From Solon.Lee at spirent.com Tue Jul 17 12:07:51 2007 From: Solon.Lee at spirent.com (Lee, Solon) Date: Tue, 17 Jul 2007 12:07:51 -0400 Subject: Python with TestDirector Message-ID: <3027F8ACF1DDC8429BBC0C305358DDD87BF609@spcrokexcbe01.AD.SPIRENTCOM.COM> Hello Mr. Golawala, I am glad to spot this on the web search - "python and Test Director", However can you or anyone tell me more specifically how this COM objects works in between Python and "Test Director" or to where should I refer?? Thanks. Solon Lee

    E-mail confidentiality. -------------------------------- This e-mail contains confidential and / or privileged information belonging to Spirent Communications plc, its affiliates and / or subsidiaries. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution and / or the taking of any action based upon reliance on the contents of this transmission is strictly forbidden. If you have received this message in error please notify the sender by return e-mail and delete it from your system. If you require assistance, please contact our IT department at helpdesk at spirent.com. Spirent Communications plc, Spirent House, Crawley Business Quarter, Fleming Way, Crawley, West Sussex, RH10 9QL, United Kingdom. Tel No. +44 (0) 1293 767676 Fax No. +44 (0) 1293 767677 Registered in England Number 470893 Registered at Spirent House, Crawley Business Quarter, Fleming Way, Crawley, West Sussex, RH10 9QL, United Kingdom Or if within the US, Spirent Communications, 26750 Agoura Road, Calabasas, CA, 91302, USA. Tel No. 1-818-676- 2300
    -------------- next part -------------- An HTML attachment was scrubbed... URL: From gerard.blais at gmail.com Fri Jul 6 14:39:26 2007 From: gerard.blais at gmail.com (Gerry) Date: Fri, 06 Jul 2007 18:39:26 -0000 Subject: file reading anomaly In-Reply-To: <1183746006.340425.96840@c77g2000hse.googlegroups.com> References: <1183740495.413999.133660@g13g2000hsf.googlegroups.com> <1183746006.340425.96840@c77g2000hse.googlegroups.com> Message-ID: <1183747166.690117.132610@q75g2000hsh.googlegroups.com> Final update: problem solved. In the big script, the snippet was reading depstats.txt which hadn't been closed. Sorry for all the bother. Gerry From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 20 03:35:27 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 20 Jul 2007 09:35:27 +0200 Subject: Converting between objects In-Reply-To: References: Message-ID: <46a065bb$0$26410$426a34cc@news.free.fr> Nathan Harmston a ?crit : > Hi, > > I have being thinking about this and was wondering with built in types > you can do things like > > float(1) or str(200) > > is there way I can define conversion functions like this: > > say i have a class A and a class B > > bobj = B() > aobj = a(bobj) > > in a neater way than just defining a set of methods > > def a(object_to_convert) > # if object_to_convert of type...... > # do some stuff > return A() > > def b(object_to_convert) > # if object_to_convert of type...... > # do some stuff > return B() > > Cause this seems a little verbose and not very OO. Just about the "not very OO" part: in Python, a class is a callable object - just like functions - that when called usually returns an instance of itself. IOW, a class is a Factory. So, from the client code POV, the fact that the factory is a class or function (both being callable objects) doesn't make any difference. Remember that OO is about objects, not about classes. > Please correct me if I m wrong or offer me hints as to a better way to > do it ? Others already answered the question. Note that if you need the factory to be able to return different subtypes based on it's argument or on some 'external' condition (platform, settings, whatever), you can also override the class '__new__' method, which is the real constructor (__init__ being the initialiser). From eviltabbycat at gmail.com Mon Jul 2 08:49:18 2007 From: eviltabbycat at gmail.com (evil tabby cat) Date: Mon, 02 Jul 2007 12:49:18 -0000 Subject: The best platform and editor for Python In-Reply-To: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> Message-ID: <1183380558.135204.83790@e16g2000pri.googlegroups.com> On Jul 2, 5:10 am, kimiraikkonen wrote: > Hi, > For experienced with Pyhton users, which developing software and > enviroment would you suggest for Pyhton programming? Compiler+Editor > +Debugger. > > Also what are your suggestions for beginners of Pyhton programming? > > Thank you. http://www.wingware.com/ is pretty impressive but non-free of both beer & speech varieties From mensanator at aol.com Thu Jul 26 14:10:41 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Thu, 26 Jul 2007 11:10:41 -0700 Subject: From D In-Reply-To: <87d4yfivyv.fsf@benfinney.id.au> References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> <87ps2ghtd7.fsf@benfinney.id.au> <1185412639.075218.186290@z24g2000prh.googlegroups.com> <87d4yfivyv.fsf@benfinney.id.au> Message-ID: <1185473441.740084.85920@l70g2000hse.googlegroups.com> On Jul 26, 12:18 am, Ben Finney wrote: > "mensana... at aol.com" writes: > > IDLE 1.2c1 > > >>> s = '123 456' > > >>> s.split() > > ['123', '456'] > > The str.split method has no bearing on this discussion, It most certainly does. To make '123 456' into an integer, you split it and then join it. >>> z = '123 456' >>> y = z.split() >>> x = ''.join(y) >>> w = int(x) >>> w 123456 Just wanted to be sure that this must still be done explicitly and that the language won't do it for me behind my back. > which is about > the Python language syntax, Provided it is confined to the language syntax. > and numeric literal values in particular. Fine, as long as int('123 456') continues to be an error. > > -- > \ "Pinky, are you pondering what I'm pondering?" "Wuh, I think | > `\ so, Brain, but burlap chafes me so." -- _Pinky and The Brain_ | > _o__) | > Ben Finney From bbxx789_05ss at yahoo.com Sat Jul 28 18:24:42 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 28 Jul 2007 15:24:42 -0700 Subject: Installing mod_python on mac os 10.4.7 In-Reply-To: <1185660599.329035.193820@d55g2000hsg.googlegroups.com> References: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> <1184458002.961657.267830@x35g2000prf.googlegroups.com> <1184466882.446791.127670@x35g2000prf.googlegroups.com> <1185658013.859359.47700@57g2000hsv.googlegroups.com> <1185660599.329035.193820@d55g2000hsg.googlegroups.com> Message-ID: <1185661482.675336.134720@b79g2000hse.googlegroups.com> I'm using Apache 2.2.4 whose root is /Library/Apache2. My installation of python 2.4 is here: /Library/Frameworks/Python.framework/Versions/2.4/ /Library/Frameworks/Python.framework/Versions/Current/ "Current" is a link to the 2.4 directory: ---- $ ls -al /Library/Frameworks/Python.framework/Versions/ total 8 drwxr-xr-x 4 root admin 136 Mar 22 14:22 . drwxr-xr-x 6 root admin 204 Mar 22 14:22 .. drwxrwxr-x 12 root admin 408 May 2 22:59 2.4 lrwxr-xr-x 1 root admin 3 Apr 8 01:45 Current -> 2.4 ---- And /usr/local/bin looks like this: -------- $ ls -al /usr/local/bin lrwxr-xr-x 1 root wheel 68 Apr 8 01:45 python -> ../../../Library/Frameworks/Python.framework/Versions/2.4/ bin/python lrwxr-xr-x 1 root wheel 71 Apr 8 01:45 python2.4 -> ../../../Library/Frameworks/Python.framework/Versions/2.4/ bin/python2.4 lrwxr-xr-x 1 root wheel 69 Apr 8 01:45 pythonw -> ../../../Library/Frameworks/Python.framework/Versions/2.4/ bin/pythonw lrwxr-xr-x 1 root wheel 72 Apr 8 01:45 pythonw2.4 -> ../../../Library/Frameworks/Python.framework/Versions/ 2.4/bin/pythonw2.4 ----------- From bignose+hates-spam at benfinney.id.au Tue Jul 31 23:33:54 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 01 Aug 2007 13:33:54 +1000 Subject: [OT] Google message munging (was: Live editing...) References: <1185914335.472511.172040@m37g2000prh.googlegroups.com> Message-ID: <87r6moc4il.fsf@benfinney.id.au> This is unrelated to the topic of the original poster, and is unrelated to Python; hence the off-topic marker. I'm also not saying anything targeted at the original poster, but rather using this message as an opportunity to ask a question. "kirby.urner at gmail.com" writes: > There's been some chatter on edu-sig (python.org) of late regarding > Python's > capabilities in the "edit/continue" tradition, meaning debugging > tools, and/or > IDE tools, that give the developer real time write access to running > programs. > > [... 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. These are so awkward to read that I usually skip straight past them without attempting to parse them, which isn't a benefit to anybody (leaving aside snide remarks about the potential of negative value from my contributions). Is it some setting that users are enabling, or is it the default behaviour? More importantly, whom do we beat with the clue-by-four to make it stop? -- \ "For of those to whom much is given, much is required." -- | `\ John F. Kennedy | _o__) | Ben Finney From python-url at phaseit.net Mon Jul 2 10:11:51 2007 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 2 Jul 2007 14:11:51 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Jul 2) Message-ID: QOTW: "Modules are objects too - they're a good example of singletons. If you want to create a class containing only static methods: use a module instead. If you want to create a class having a single instance (a singleton), most of the time you can use a module instead. Functions don't *have* to be methods in a class, and the resulting design may still be a good design from an OO point of view." - Gabriel Genellina "I recommend gmane.org's NNTP server for all your mailing list needs." - Grant Edwards A "new mailing list has been started to discuss and get help with ... the Python/C api." http://groups.google.com/group/comp.lang.python/msg/aaa4787b320aea0a Ben Finney and others advertise the virtues of SQLAlchemy: http://groups.google.com/group/comp.lang.python/browse_thread/thread/31374383f59e321f/ IronPython Exception-handling involves a few new techniques: http://groups.google.com/group/comp.lang.python/msg/a2b697f8e4628dca Relative imports present a challenge for which there's no canonical solution. Josiah and Gabriel help analyze the situation: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c44c769a72ca69fa/ How can a report's columns be made to line up? http://groups.google.com/group/comp.lang.python/browse_thread/thread/4256781d326edf8c/ It's common enough to see advertisements for employment, contract development, authoring, ... in comp.lang.python; now we're getting legitimate announcements of Python-based higher-order businesses: http://groups.google.com/group/comp.lang.python/browse_thread/thread/f82f9ee231a99909/ ======================================================================== 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. The Python Papers aims to publish "the efforts of Python enthusiats". http://pythonpapers.org/ Readers have recommended the "Planet" sites: http://planetpython.org http://planet.python.org comp.lang.python.announce announces new Python software. Be sure to scan this newsgroup weekly. http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce Python411 indexes "podcasts ... to help people learn Python ..." Updates appear more-than-weekly: http://www.awaretek.com/python/index.html Steve Bethard continues the marvelous tradition early borne by Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim Lesher of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python Many Python conferences around the world are in preparation. Watch this space for links to them. Among several Python-oriented RSS/RDF feeds available are http://www.python.org/channews.rdf http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi http://python.de/backend.php For more, see http://www.syndic8.com/feedlist.php?ShowMatch=python&ShowStatus=all The old Python "To-Do List" now lives principally in a SourceForge reincarnation. http://sourceforge.net/tracker/?atid=355470&group_id=5470&func=browse http://www.python.org/dev/peps/pep-0042/ The online Python Journal is posted at pythonjournal.cognizor.com. editor at pythonjournal.com and editor at pythonjournal.cognizor.com welcome submission of material that helps people's understanding of Python use, and offer Web presentation of your work. del.icio.us presents an intriguing approach to reference commentary. It already aggregates quite a bit of Python intelligence. http://del.icio.us/tag/python *Py: the Journal of the Python Language* http://www.pyzine.com Archive probing tricks of the trade: http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python&num=100 http://groups.google.com/groups?meta=site%3Dgroups%26group%3Dcomp.lang.python.* Previous - (U)se the (R)esource, (L)uke! - messages are listed here: http://www.ddj.com/topic/python/ (requires subscription) http://groups-beta.google.com/groups?q=python-url+group:comp.lang.python*&start=0&scoring=d& http://purl.org/thecliff/python/url.html (dormant) or http://groups.google.com/groups?oi=djq&as_q=+Python-URL!&as_ugroup=comp.lang.python There is *not* an RSS for "Python-URL!"--at least not yet. Arguments for and against are occasionally entertained. Suggestions/corrections for next week's posting are always welcome. E-mail to should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask to subscribe. Mention "Python-URL!". Write to the same address to unsubscribe. -- The Python-URL! Team-- Phaseit, Inc. (http://phaseit.net) is pleased to participate in and sponsor the "Python-URL!" project. Watch this space for upcoming news about posting archives. From steve at holdenweb.com Mon Jul 2 17:51:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Jul 2007 17:51:21 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> Message-ID: Donn Cave wrote: > In article <1i0ikru.1uccqtm1efnzn3N%aleax at mac.com>, > aleax at mac.com (Alex Martelli) wrote: > >> "Dynamic typing is recommended", they conclude, "when programs must be >> as flexible as possible". I recommend reading the Agile Manifesto to >> understand why maximal flexibility is crucial in most real-world >> application programming -- and therefore why, in said real world rather >> than in the more academic circles Dr. Van Roy and Dr. Hadidi move in, >> dynamic typing is generally preferable, and not such a tiny issue as >> they make the difference to be. > > I guess there may be more than one kind of flexibility. The language > I fool around with sometimes that has strong static typing is Haskell. > Though a relatively elementary Haskell programmer (the learning curve > with this language is something you would have to experience to believe), > I feel that the type checking actually helps me program faster. > The compiler's check for structural correctness is after all for my > benefit, and expedites development and maintenance of code, in my > limited experience. The more extensive my changes, the more useful > the type checking is - I'm much more casual about significant code > revision when writing in Haskell, somewhat more casual when writing > in C, and worried when writing Python. > > This is the kind of flexibility where you make significant changes > to something, but the result is as structurally consistent as it > would have been if written that way from the start. I have also > seen the kind of flexibility where you use expedient hacks to make > changes with relatively small amounts of code, and I've seen it in > Python applications. It's flexibility when you're doing it, but > it paradoxically causes rigidity as the hacks create more points > of articulation and more things that aren't obvious to the person > making the changes. If that's flexibility, you can have it. > Indeed you describe an arthritic design quite well, but I don't think it's fair to single Python out as a potential problem. As we have known for a long time you can write unstructured code in almost any language, and you can do structured programming in almost any language given discipline. I certainly agree that if the programmer shows insufficient discipline the results will likely be bad, but in that light Haskell is really the ultimate bondage language. Some of us don't like to be tied that tightly. I don't feel the same trepidation you appear to do when refactoring Python code. I suppose I might say that in my experience Python allows you to appreciate a better-engineered solution more easily, and so it tends to encourage better engineering. In some ways C# is quite Python-like, and I am beginning to enjoy writing it from time to time, but when you are dealing with amorphous collections the casting and conversions can drive you almost insane. And since the collections are ultimately collections of Object, none of it actually gets you any nearer your programming goal. 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 gal.diskin at gmail.com Wed Jul 11 09:35:23 2007 From: gal.diskin at gmail.com (Gal Diskin) Date: Wed, 11 Jul 2007 16:35:23 +0300 Subject: profiling a C++ python extension In-Reply-To: <1184113272.962640.41240@22g2000hsm.googlegroups.com> References: <1184113272.962640.41240@22g2000hsm.googlegroups.com> Message-ID: <4694DC9B.7060000@gmail.com> rasmus wrote: > I have used gprof to profile stand alone C++ programs. I am also > aware of pure python profilers. However, is there a way to get > profile information on my C++ functions when they are compiled in a > shared library (python extension module) and called from python. From > what I can tell, gmon.out will not be generated unless the entire > executable (python interpreter) was compiled with -pg. Is my only > solution to recompile the python interpreter with -pg so that my > extension module (also compiled with -pg) produces a gmon.out? > > Any suggestions or tips would be helpful. > > Matt > > This may not be the best solution but it will work without any recompiles. Use the binary instrumentation tool PIN from Intel (you can get it here: http://rogue.colorado.edu/pin/) as far as I understand the license it's free for non-commercial use (if you're looking for commercial use ask your legal department... :) ). Once you're using PIN all you need to do is write a simple "pintool" (a profiler) that will profile only your shared library and leave the rest of the code alone. (there is a mailing list called pinheads in yahoo that is monitored by the developers and a lot of example code in the released kits). Hope this helps, Gal Diskin -------------- next part -------------- An HTML attachment was scrubbed... URL: From gert.cuykens at gmail.com Wed Jul 4 23:27:05 2007 From: gert.cuykens at gmail.com (gert) Date: Thu, 05 Jul 2007 03:27:05 -0000 Subject: login http://cheeseshop.python.org/pypi broken ? Message-ID: <1183606025.475352.230270@k79g2000hse.googlegroups.com> tried reseting password but i can not login anymore to upload my new source code ? From horpner at yahoo.com Tue Jul 24 08:01:18 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 24 Jul 2007 12:01:18 GMT Subject: Where do they tech Python officialy ? References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com> <7xveca4ajp.fsf@ruckus.brouhaha.com> Message-ID: On 2007-07-24, Paul Rubin wrote: > I think Python is not used in university programs very much. > Look for one that uses SICP (Scheme) or CTM (Mozart/Oz) or a > functional language like Haskell, in preference to the ones > that use Java (the Cobol of the 1990's). With some reasonable > experience in Scheme or Mozart or Haskell, plus a Python > manual, you'll be well on your way. > > The SICP textbook is here: > > http://mitpress.mit.edu/sicp/ > > Maybe it's gotten a little bit old fashioned by now, but it's > still good reading. The only weakness I'm aware of is how well it suits its original target audience--engineers who need an introduction to computer science. If your aren't an engineer, I might recommend _How to Design Programs_ (http://www.htdp.org/), or _Concrete Abstractions_ (http://gustavus.edu/+max/concrete-abstractions.html) instead. One cool advantage of SICP is the free online lectures, which helps make up for its non-programmer slant. http://www.swiss.ai.mit.edu/classes/6.001/abelson-sussman-lectures/ -- Neil Cerutti From iladijas at gmail.com Sat Jul 28 08:46:56 2007 From: iladijas at gmail.com (fynali iladijas) Date: Sat, 28 Jul 2007 05:46:56 -0700 Subject: How to programmatically insert pages into MDI. In-Reply-To: <1185280597.184328.152920@k79g2000hse.googlegroups.com> References: <1185280597.184328.152920@k79g2000hse.googlegroups.com> Message-ID: <1185626816.422978.8290@57g2000hsv.googlegroups.com> On Jul 24, 4:36 pm, fynali iladijas wrote: > Hi, this query is regarding automating page insertions in Microsoft > Document Imaging. > > I have two sets of MDIs generated fortnightly: Invoices and their > corresponding Broadcast Certificates; about 150 of each. > > My billing application can generate one big MDI with all 150 invoices > and another with all the Broadcast Certificates. At the moment I take > the pages of, say invoice #1 and insert them into a new MDI (calling > it in001.mdi). Then I grab the corresponding Broadcast-Certificate- > pages of invoice #1 and insert them into in001.mdi. I proceed to > complete the rest the same way (quite a pain). > > Once done, I print each inxxxxx.mdi, setting various printer options > such as binding direction, staple & hole-punch etc. > > What I would like to automate is the coupling of an Invoice & its > corresponding Broadcast-Certificate-pages into a new appropriately > named MDI & then printing it into one step; iterating over all the > xxxxx until done. > > My billing app can be set to generate each invoice & broadcast > certificate separately with a convenient naming convention to aid in > program logic (for eg. inxxxxx.mdi & bcxxxxx.mdi) where xxxxx > indicates corresponding invoice & respective broadcast certificates. > > All help and advice will be most appreciated. > > Thank you. > > s|a fynali )-: -- s|a fynali From max at alcyone.com Fri Jul 20 18:41:49 2007 From: max at alcyone.com (Erik Max Francis) Date: Fri, 20 Jul 2007 15:41:49 -0700 Subject: Sorting dict keys In-Reply-To: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> References: <1184970471.146819.86280@r34g2000hsd.googlegroups.com> Message-ID: <7eednU-WGZqzpzzbnZ2dnUVZ_vamnZ2d@speakeasy.net> montyphyton at gmail.com wrote: > Consider the following: >>>> a = {1:2, 3:4, 2:5} > > Say that i want to get the keys of a, sorted. First thing I tried: > >>>> b = a.keys().sort() >>>> print b > None > > Doesn't work. Probably because I am actually trying to sort the keys > of the dictionary without copying them first. If that is the case, > fine. .sort returns None. >>>> b = a.keys() >>>> b.sort() > [1, 2, 3] This snippet is clearly edited, because .sort returns None: >>> a = {1:2, 3:4, 2:5} >>> b = a.keys() >>> b.sort() >>> b [1, 2, 3] The problem you're having here is that .sort returns None to indicate that it mutates the object, rather than returning a new one. So get the keys, sort them, and then move along. > Works fine, but I would really like it if I could somehow do it in one > line. Why is doing it in one line a priority? Clarity is more important than brevity. Regardless, you can do it in one line with the sorted builtin: >>> sorted(a.keys()) [1, 2, 3] -- 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 We must all hang together, or, most assuredly, we will all hang separately. -- John Hancock From erik at myemma.com Mon Jul 16 02:56:18 2007 From: erik at myemma.com (Erik Jones) Date: Mon, 16 Jul 2007 01:56:18 -0500 Subject: How to determine which method was used in an inheritance heirarchy? In-Reply-To: References: <1184559788.712146.238190@q75g2000hsh.googlegroups.com> <1184565220.674041.270790@o61g2000hsh.googlegroups.com> Message-ID: <4BC3DC93-5F57-4B24-BE82-EB2D5FD679AF@myemma.com> On Jul 16, 2007, at 1:31 AM, Erik Jones wrote: > On Jul 16, 2007, at 12:53 AM, Michele Simionato wrote: > >> On Jul 16, 7:18 am, Erik Jones wrote: >>> On Jul 15, 2007, at 11:23 PM, Michele Simionato wrote: >>> >>>> On Jul 16, 5:51 am, Erik Jones wrote: >>>>> Say you're given a call event frame for a method call. How can >>>>> you >>>>> tell if the code being executed came from a super class of the >>>>> object >>>>> or class the method was called on? >>> >>>>> Erik Jones >>> >>>> You look if the method was defined in self.__class__.__dict__. >>> >>>> Michele Simionato >>> >>> That doesn't seem to cover calling super class __init__ methods. >>> >> >> I am probably missing something. In the following code the >> method check_init checks if the current instance >> possess an __init__ or if it just inherits one >> from the ancestors. Is this what you want? >> >> class B(object): >> def __init__(self): >> 'something' >> def check_init(self): >> if '__init__' in self.__class__.__dict__: >> print 'possesses __init__' >> else: >> print 'inherits __init__' >> >> class C(B): >> 'something else' >> def __init__(self): >> print 'calling C.__init__' >> >> class D(B): >> pass >> >> c = C() >> d = D() >> >> c.check_init() #possesses __init__ >> d.check_init() #inherits __init__ > > Ok, I see how I was pretty vague with my original questions. > Given the pattern where you need to call a base class's constructor > (or, other overriden method of the same name as that being called > on the child class object): > > class A(object): > def __init__(self): > print self.__class__.__name__ > > class B(A): > def __init__(self): > A.__init__(self) > print self.__class__.__name__ > > B() > > This will output: > > B > B > > How can I get > > A > B Perhaps an even better example of what I'm trying to do would be in order (this is minus any exception handling): import sys def mytrace(frame, event, arg): if event == 'call': func_name = frame.f_code.co_name if func_name in frame.f_locals['self'].__class__.__dict__: print frame.f_locals['self'].__class__.__name__ else: for base in frame.f_locals['self'].__class__.__bases__: if func_name in base.__dict__: print base.__name__ break class A(object): def __init__(self): pass class B(A): def __init__(self): A.__init__(self) sys.settrace(mytrace) B() This will output: B B whereas I'm shooting for: B A 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 jjl at pobox.com Thu Jul 26 17:20:30 2007 From: jjl at pobox.com (John J. Lee) Date: Thu, 26 Jul 2007 21:20:30 GMT Subject: ANN: Snobol 1.0 References: <7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com> Message-ID: <87abtioo9t.fsf@pobox.com> (Sorry if this appears twice, accidentally included c.l.py.announce the first time where it was (correctly) rejected, not sure if that means it didn't get through to c.l.py either). greg writes: > Aahz wrote: >> So adding >> SNOBOL patterns to another library would be a wonderful gift to the >> Python community... > > I wrote a module for Snobol-style pattern matching a > while back, but didn't get around to releasing it. > I've just put it on my web page: > > http://www.cosc.canterbury.ac.nz/greg.ewing/python/Snobol.tar.gz > > There's no manual yet, but there's a fairly complete > set of docstrings and some test cases to figure it > out from. Interesting. Would be nice if tarball contained a top-level directory rather than unpacking directly into the current working directory -- people on traditional (non-Mac) unixy systems don't expect that. PEP 8-style module name (snobol.py not Snobol.py) would be nice too. John From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Jul 23 07:42:18 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 23 Jul 2007 13:42:18 +0200 Subject: Configure apache to run python scripts In-Reply-To: <1185160927.844397.244290@e16g2000pri.googlegroups.com> References: <1185160927.844397.244290@e16g2000pri.googlegroups.com> Message-ID: <46a4941a$0$21663$426a74cc@news.free.fr> joe jacob a ?crit : > I need to configure apache to run python scripts. I followed the steps > mentioned in this site (http://www.thesitewizard.com/archive/ > addcgitoapache.shtml). But I am not able to run python scripts from > Firefox, I got a forbidden error "you do not have permission to > access the file in the server" when I try to run the script form > Firefox browser. Somebody please help me. http://httpd.apache.org/docs//howto/cgi.html with 'your_apache_version_here' in 1.3, 2.0, 2.2 FWIW, your problem relates to apache and permissions, not to Python. HTH From mail at microcorp.co.za Sun Jul 22 04:28:39 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 22 Jul 2007 10:28:39 +0200 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <7x8x9lwka9.fsf@ruckus.brouhaha.com> <7xbqe7ox9n.fsf@ruckus.brouhaha.com> Message-ID: <00cb01c7cc3a$4e6a3060$03000080@hendrik> "Steve Holden" wrote: > The trouble there, though, is that although COBOL was comprehensible (to > a degree) relatively few people have the rigor of thought necessary to > construct, or even understand, an algorithm of any kind. This is true - and in my experience the competent people come in two classes - those that are good at mathematics, and those that are good at languages. If you find someone good at both, employ her. - Hendrik From kyosohma at gmail.com Wed Jul 25 09:11:47 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Wed, 25 Jul 2007 06:11:47 -0700 Subject: How to create a single executable of a Python program In-Reply-To: <1185363517.090457.205480@b79g2000hse.googlegroups.com> References: <1185345286.447757.243070@g4g2000hsf.googlegroups.com> <1185363517.090457.205480@b79g2000hse.googlegroups.com> Message-ID: <1185369107.221838.176460@o61g2000hsh.googlegroups.com> On Jul 25, 6:38 am, Ali wrote: > On Jul 25, 7:34 am, NicolasG wrote: > > > Dear fellows, > > > I'm trying to create a executable file using py2exe . Unfortunately > > along with the python executable file it also creates some other files > > that are needed in order to the executable be able to run in a system > > that doesn't have Python installed. Can some one guide me on how can I > > merge all this files created by py2exe in a single exe file ? If I > > have a python program that uses an image file I don't want this image > > file to be exposed in the folder but only to be accessible through the > > program flow.. > > > Regards, > > Nicolas. > > Hi, > > I know this is not exactly what you asked for, but if you want a > single exe installer, then take a look at something like Inno Setup.http://www.jrsoftware.org/isinfo.php > > It will package all that stuff into a single exe which Windows users > seem happy to click-and-install. > > I blogged the process I use here:http://unpythonic.blogspot.com/2007/07/pygtk-py2exe-and-inno-setup-fo... > (though this has some PyGTK specifics) > > Ali I've been using GUI2Exe, which is a GUI interface to py2exe. Anyway, with it, I've been able to reduce the number of files it compiles down to 3. The main executable, MSVCR71.dll and w9xpopen.exe. Then I use Inno Setup to create an installer executable. Inno can determine if any of the dlls you include are already installed and if not, install them for you. Gui2exe can be found here: http://xoomer.alice.it/infinity77/eng/GUI2Exe.html Hope that helps. Mike From nospam.themindstorm at gmail.com Fri Jul 20 16:17:34 2007 From: nospam.themindstorm at gmail.com (Alex Popescu) Date: Fri, 20 Jul 2007 20:17:34 +0000 (UTC) Subject: Pythonic way for missing dict keys References: <1184961448.456134.153020@k79g2000hse.googlegroups.com> Message-ID: Jakub Stolarski wrote in news:1184961448.456134.153020 at k79g2000hse.googlegroups.com: > Version 1 and 2 do different thing than version 3. The latter doesn't > add value to dict. > > As it was mentioned before, use: > 1 - if you expect that there's no key in dict > 2 - if you expect that there is key in dict > I may be missing something but I think the 3 approaches are completely equivalent in terms of functionality. ./alex -- .w( the_mindstorm )p. From gagsl-py2 at yahoo.com.ar Thu Jul 12 20:54:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Jul 2007 21:54:54 -0300 Subject: 2**2**2**2**2 wrong? Bug? References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> <1184173446.779276.250530@k79g2000hse.googlegroups.com> <1184182757.797808.206480@d55g2000hsg.googlegroups.com> <87ps2xkdn9.fsf@benfinney.id.au> Message-ID: En Thu, 12 Jul 2007 09:30:34 -0300, Ben Finney escribi?: > "Gabriel Genellina" writes: > >> "Which is the largest number that can be written with only 3 >> digits?" Some people stop at 999, others try 99**9 and 9**99, and >> the winner is 9**9**9 > > Since exponentiation is (I think?) the highest-order function we > understand for writing *only* digits on the page, then yes, your > answer is right, if no other mathematical notation is allowed. > > Since others seem to be reading "only 3 digits" as "3 digits plus > other well-defined mathematical notation", here's the best answer > given those criteria: > > Thanks, very interesting article! I like the idea of Busy Beaver numbers: so simple to express, rather comprehensible, but enormously big... -- Gabriel Genellina From conra2004 at yahoo.com Tue Jul 31 09:07:44 2007 From: conra2004 at yahoo.com (yadin Bocuma Rivas) Date: Tue, 31 Jul 2007 08:07:44 -0500 (CDT) Subject: create a toolbar + images using wxpython for windows Message-ID: <499006.60499.qm@web51309.mail.re2.yahoo.com> hi everery one I Need help on getting examles of how to create a toolbar with images using wxpython on a windows pc how can i add a toolbar to a GUI all sample codes i could find contain errors. i did the following but it is wrong! what is it with the IMAGES? do i have to create them, load them...? or they come with python like in Matlab thank you. import wx from pylab import* class MainWindow(wx.Frame): def __init__(self,parent,id,title): self.dirname='' wx.Frame.__init__(self,parent,wx.ID_ANY, title,wx.DefaultPosition, wx.Size(320,410)) ##############_______________________ADDING A TOOLBAR___________________###################### toolbar = wx.ToolBar(self, -1, style=wx.TB_HORIZONTAL | wx.NO_BORDER) toolbar.AddSimpleTool(1, wx.Image('stock_new.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap(), 'New', '') toolbar.Realize() Frame.Add(toolbar, 0, border=5) app = wx.PySimpleApp() frame = MainWindow(None, -1, " dipole antenna ") frame.show(1) frame.SetBackgroundColour('light grey') app.MainLoop() __________________________________________________ Correo Yahoo! Espacio para todos tus mensajes, antivirus y antispam ?gratis! Reg?strate ya - http://correo.espanol.yahoo.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bj_666 at gmx.net Tue Jul 24 06:14:57 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 24 Jul 2007 10:14:57 GMT Subject: Python pearls required for iteration across fields of data structure References: <1185269175.966730.248470@o61g2000hsh.googlegroups.com> Message-ID: <5gm1p1F3gs3gfU4@mid.uni-berlin.de> On Tue, 24 Jul 2007 02:26:15 -0700, NetHead wrote: > The code below is WRONG, but hopefully illustrates what I am trying to > achieve. > > Any suggestions how to code this is an efficient and maintainable (and > correct) manner? > > [?] > for i in wildcards: > for j in i: > try: > j = self.replaceFieldsAndIndices(j, rcn, rcu, > rcp, indices) > except: > # Ignore errors if condition has no format. > pass Maybe you shouldn't silence all exceptions with a bare except here. This swallows any errors in `replaceFieldsAndIndices()`. Maybe some of them are not the exception you expect, but real errors in your program!? Ciao, Marc 'BlackJack' Rintscj From mensanator at aol.com Tue Jul 10 02:51:25 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 09 Jul 2007 23:51:25 -0700 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: <1184042559.120947.124560@k79g2000hse.googlegroups.com> References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> Message-ID: <1184050285.997766.299860@d55g2000hsg.googlegroups.com> On Jul 9, 11:42?pm, Paul McGuire wrote: > On Jul 9, 11:21 pm, "Jim Langston" wrote:> In Python 2.5 on intel, the statement > > 2**2**2**2**2 > > evaluates to>>> 2**2**2**2**2 > > > 200352993040684646497907235156025575044782547556975141926501697371089405955 63114 > > 530895061308809333481010382343429072631818229493821188126688695063647615470 29165 > > 041871916351587966347219442930927982084309104855990570159318959639524863372 36720 > > > > Exponentiation is right associative, so this is the same as: > > 2**(2**(2**(2**2))) > 2**2**2**4 > 2**2**16 > 2**65536 > > 2=10**0.3010, so 2**65536 is approx 10**19726 > > There are 19730 digits in your answer, >>> import gmpy >>> n = 2**2**2**2**2 >>> gmpy.numdigits(n) 19729 Did you count the 'L'? >so this seems to be at least in > the ball park. > > -- Paul From gagsl-py2 at yahoo.com.ar Mon Jul 9 10:21:43 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Jul 2007 11:21:43 -0300 Subject: Broken MUA interactions (was: Restarting a Python Application) References: <1183498045.092504.229250@m36g2000hse.googlegroups.com> <94ccbe710707071511o3beee718wc12f15082b3c6e18@mail.gmail.com> <87vecvmqw5.fsf_-_@benfinney.id.au> <4866bea60707090648v772e81d2r261e8d927310591c@mail.gmail.com> Message-ID: En Mon, 09 Jul 2007 10:48:39 -0300, Chris Mellon escribi?: > It's working as instructed, but that doesn't mean that it's doing the > best thing. It's common practice for mailing lists to set the reply-to > to the list itself, because that's the common case, and because it's > encouraged to keep discussion on the list. > > If whoever manages the python lists doesn't want to do it, either > because they have some practical reason or because they've got a bug > up their ass about mail readers without list support, thats fine. But > it's hardly incorrect to configure it with the reply-to set to the > list, either. No, it's not correct to modify Reply-To. Some reasons: http://www.unicom.com/pw/reply-to-harmful.html -- Gabriel Genellina From software at ginstrom.com Fri Jul 20 21:41:41 2007 From: software at ginstrom.com (Ryan Ginstrom) Date: Sat, 21 Jul 2007 10:41:41 +0900 Subject: code packaging In-Reply-To: <7xfy3jpem8.fsf_-_@ruckus.brouhaha.com> References: <7xfy3jpem8.fsf_-_@ruckus.brouhaha.com> Message-ID: <00df01c7cb38$49f83980$030ba8c0@MOUSE> > On Behalf Of Paul Rubin > I'm wondering how other projects go about this. I develop an automated build system from the very beginning. Running the build script: * Creates the API documentation (epydoc) * Creates the help files (extracting some information from the source) * Builds a windows executable (py2exe) * Builds an installer (Inno Setup) * Runs the installer (AutoIt) * Runs a smoke test on the installed application (AutoIt) The program must at least install and pass the smoke tests at any given point in development. Another script uploads the installer to my server, and sends an email to the testers stating that a new version is ready, with a list of additions/improvements. Regards, Ryan Ginstrom From duncan.booth at invalid.invalid Sun Jul 1 05:19:07 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 1 Jul 2007 09:19:07 GMT Subject: howto resend args and kwargs to other func? References: <1183279997.244378.105810@n60g2000hse.googlegroups.com> <1183280667.542964.175570@u2g2000hsc.googlegroups.com> Message-ID: dmitrey wrote: > On Jul 1, 12:00 pm, Duncan Booth wrote: > >> You 'need something like this', so write something like that. >> Did you intend to ask a question? > > I would gladly write the one, but the example doesn't work, and I > don't know any easy way (moreover any way) to make it work correctly. > D. > The example doesn't work because it isn't a real example (what are some_cond or some_other_args?). An identical example which runs but doesn't give the output you expect would be more meaningful. If you actually wrote a runnable example, and explained what about it you think doesn't work, then I could probably tell you how to fix it without having to engage my telepathy. The only thing I can see wrong with your made-up example is that you may have intended a * before some_other_args, but since it isn't a real example it is probably just a typo rather than being your question. From grante at visi.com Wed Jul 25 17:13:38 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 25 Jul 2007 21:13:38 -0000 Subject: first, second, etc line of text file References: <5f56302b0707251244p24080f1ct87a5f459cb175dae@mail.gmail.com> <13afdpp7a6t24c5@corp.supernews.com> <1185396840.702955.31890@l70g2000hse.googlegroups.com> Message-ID: <13aff82d1v7ge0f@corp.supernews.com> On 2007-07-25, Jeff wrote: > That might be a memory problem if you are running multiple processes > regularly, such as on a webserver. I suppose if you did it in parallel 50 processes, you could use up 250MB of RAM. Still not a big deal on many servers. A decent OS will swap regions that aren't being used to disk, so it's likely not to be a problem. If you're talking several hundred instances, you could start to use up serios amounts of VM. Still, I say do it the simple, obvious way first, and optimize it _after_ you've determined you have a performance problem (and determined where the bottleneck is). Premature optimization... -- Grant Edwards grante Yow! This PORCUPINE knows at his ZIPCODE ... And he has visi.com "VISA"!! From iwinux at gmail.com Fri Jul 27 09:14:11 2007 From: iwinux at gmail.com (iwinux) Date: Fri, 27 Jul 2007 21:14:11 +0800 Subject: Compile python with Mingw In-Reply-To: References: Message-ID: fdu.xiaojf at gmail.com ??: > Hi all, > > > I was trying to build pymol with mingw on my windows box, but during the > compilation it said that my python.exe was built with VS2003, and in > order to build compatible binary executable file, I have to build pymol > with VS2003. I don't have VS2003, so I think I may compile both pymol > and python with mingw. > > Can somebody give me some hints on how to build python with mingw? I > have googled the web, and it seems that few people have tried mingw > with python. I have found mingwpython, but it's not for python 2.5. > > Thanks. To build python with mingw, there is a common way. First you should install msys, which can be downloaded from mingw's website. Run msys and type 'cd /path/to/source'. Then type "./configure & make & make install". And you will get a python built with mingw. From __peter__ at web.de Mon Jul 30 10:48:50 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 30 Jul 2007 16:48:50 +0200 Subject: File handle not being released by close References: <1185806160.161748.58910@d55g2000hsg.googlegroups.com> Message-ID: bg_ie at yahoo.com wrote: > I'm in the process of writing some code and noticed a strange problem > while doing so. I'm working with PythonWin 210 built for Python 2.5. I > noticed the problem for the last py file processed by this script, > where the concerned tmp file is only actually written to when > PythonWin is closed. In other words, after I run this script, one of > the generated tmp files has a size of 0kB. I then close PythonWin and > it is then written to. > > I'm guessing the garbage collector is causing the file to be written, > but shouldn't close do this? Yes. > f=open(fileBeginning+".tmp", 'w') > f.write("Hello") > f.close In Python () is nessary to call a parameterless function or method: >>> def f(): print "Hi Barry" ... >>> f >>> f() Hi Barry This allows it to treat functions as variables consistently: >>> def f(write): ... write("Hello") ... >>> def write_upper(s): print s.upper() ... >>> import sys >>> write_to_stdout = sys.stdout.write >>> >>> f(write_upper) HELLO >>> f(write_to_stdout) Hello>>> Peter From samwyse at gmail.com Sat Jul 7 17:13:45 2007 From: samwyse at gmail.com (samwyse) Date: Sat, 07 Jul 2007 21:13:45 -0000 Subject: Re-raising exceptions with modified message In-Reply-To: References: Message-ID: <1183842825.057867.169710@q75g2000hsh.googlegroups.com> On Jul 5, 8:53 am, Christoph Zwerschke wrote: > What is the best way to re-raise any exception with a message > supplemented with additional information (e.g. line number in a > template)? Let's say for simplicity I just want to add "sorry" to every > exception message. My naive solution was this: > > try: > ... > except Exception, e: > raise e.__class__, str(e) + ", sorry!" > > This works pretty well for most exceptions, e.g. > > >>> try: > ... 1/0 > ... except Exception, e: > ... raise e.__class__, str(e) + ", sorry!" > ... > Traceback (most recent call last): > File "", line 4, in > ZeroDivisionError: integer division or modulo by zero, sorry! > > But it fails for some exceptions that cannot be instantiated with a > single string argument, like UnicodeDecodeError which gets "converted" > to a TypeError: > > >>> try: > ... unicode('\xe4') > ... except Exception, e: > ... raise e.__class__, str(e) + ", sorry!" > ... > Traceback (most recent call last): > File "", line 4, in > TypeError: function takes exactly 5 arguments (1 given) > > Another approach is using a wrapper Extension class: > > class SorryEx(Exception): > def __init__(self, e): > self._e = e > def __getattr__(self, name): > return getattr(self._e, name) > def __str__(self): > return str(self._e) + ", sorry!" > > try: > unicode('\xe4') > except Exception, e: > raise SorryEx(e) > > But then I get the name of the wrapper class in the message: > > __main__.SorryEx: 'ascii' codec can't decode byte 0xe4 in position 0: > ordinal not in range(128), sorry! > > Yet another approach would be to replace the __str__ method of e, but > this does not work for new style Exceptions (Python 2.5). > > Any suggestions? > > -- Chris Can "try" statements be used in "except" clauses? It appears so, thus a hybrid approach might work well enough. try: ... except Exception, e: try: raise e.__class__, str(e) + ", sorry!" except TypeError: raise SorryEx(e) That leaves the issue of the name being changed for UnicodeDecodeError, which might be fixable by diddling with __name__ properties. Or perhaps SorryEx needs to be a factory that returns exception classes; the last line would be "SorryEx(e)()". I'll have to play with this a bit. From jeffober at gmail.com Wed Jul 25 21:16:18 2007 From: jeffober at gmail.com (Jeff) Date: Wed, 25 Jul 2007 18:16:18 -0700 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <1185411490.250673.165570@z28g2000prd.googlegroups.com> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <7xzm1kqw89.fsf@ruckus.brouhaha.com> <1185411490.250673.165570@z28g2000prd.googlegroups.com> Message-ID: <1185412578.872085.63670@x40g2000prg.googlegroups.com> > For example, if I have > the below structure: > > Big Record > Small Record Type A > Many Small Record Type B > Small Record Type C > > It is pretty natural to use lists, although after a while it is > difficult to figure out the meaning of the fields in the lists. If > only there were a way to 'attach' names to members of the list. You could use dictionaries: big_record = { "small_record_a": { ... }, "many_small_record_b": { "sub_record_of_b": { ... }, "sub_record_of_b2": { ... }, }, "small_record_c": { ... }, } From vodel at informatik.tu-chemnitz.de Fri Jul 20 04:22:41 2007 From: vodel at informatik.tu-chemnitz.de (Matthias Vodel) Date: Fri, 20 Jul 2007 10:22:41 +0200 Subject: Using eggs or py2exe to distribute apps References: Message-ID: Hey, Use pyInstaller ;) http://pyinstaller.hpcf.upr.edu/cgi-bin/trac.cgi Easier to use in comparison to py2exe ... very good tool - try it! Bye, Matthias From crcarleRemoveThis at BOGUSsandia.gov Thu Jul 12 20:51:08 2007 From: crcarleRemoveThis at BOGUSsandia.gov (Chris Carlen) Date: Thu, 12 Jul 2007 17:51:08 -0700 Subject: Understanding python functions - Instant Python tutorial Message-ID: Hi: I have begun learning Python by experimenting with the code snippets here: http://hetland.org/writing/instant-python.html In the section on functions, Magnus Lie Hetland writes: -------------------------------------------------------------------- For those of you who understand it: When you pass a parameter to a function, you bind the parameter to the value, thus creating a new reference. If you change the ?contents? of this parameter name (i.e. rebind it) that won?t affect the original. This works just like in Java, for instance. Let?s take a look at an example: def change(some_list): some_list[1] = 4 x = [1,2,3] change(x) print x # Prints out [1,4,3] As you can see, it is the original list that is passed in, and if the function changes it, these changes carry over to the place where the function was called. Note, however the behaviour in the following example: def nochange(x): x = 0 y = 1 nochange(y) print y # Prints out 1 Why is there no change now? Because we don?t change the value! The value that is passed in is the number 1 ? we can?t change a number in the same way that we change a list. The number 1 is (and will always be) the number 1. What we did do is change the contents of the local variable (parameter) x, and this does not carry over to the environment. -------------------------------------------------------------------- What this looks like to me is what would happen if in C I passed a pointer to the list x to the function change(), as in: change(&x); Thus the function could change the original list. I don't understand Hetland's terminology though, when he is speaking of "binding" and "reference." Actually, Hetland's entire first paragraph is unclear. Can anyone reword this in a way that is understandable? Thanks. -- Good day! ________________________________________ Christopher R. Carlen Principal Laser&Electronics Technologist Sandia National Laboratories CA USA crcarleRemoveThis at BOGUSsandia.gov NOTE, delete texts: "RemoveThis" and "BOGUS" from email address to reply. From steve at holdenweb.com Mon Jul 30 11:51:35 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Jul 2007 11:51:35 -0400 Subject: Bug? exec converts '\n' to newline in docstrings!? In-Reply-To: References: Message-ID: <46AE0907.3090700@holdenweb.com> Edward K Ream wrote: > It looks like both exec and execfile are converting "\n" to an actual > newline > in docstrings! > > Start idle: > > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on > win32 > [rest of signon deleted] > >>>> s = '''\ > strings = 'abc'.split("\n") > ''' >>>> print s > strings = 'abc'.split(" > ") > > I see this in my own calls to exec and execfile. Is this a bug or am I > missing something? > Python is doing exactly what you told it to do. You created a string with triple single-quote delimiters. Nothing in the string literal syntax says that escape sequences will not be actioned, so the literal has a value that includes a newline. This has nothing to do with exec, and I don't believe it will happen with execfile should you create a file with a legal Python program inside it. The problem is because you are trying to represent a Python program as a Python string literal, and doing it incorrectly. What you did is no different from writing: >>> s = '''\ ... This is a string with\nan embedded newline''' >>> print s This is a string with an embedded newline >>> It just doesn't match your expectations, is 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 mail at microcorp.co.za Sat Jul 7 02:32:52 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 7 Jul 2007 08:32:52 +0200 Subject: Where is the syntax for the dict() constructor ?! References: <468D1D9D.6060002@gmail.com><468D3445.2060408@gmail.com><1183675552.466967.136360@i13g2000prf.googlegroups.com> <5f6fo1F3b25tsU1@mid.uni-berlin.de> Message-ID: <003e01c7c060$a5ba6c80$03000080@hendrik> "Marc 'BlackJack' Rintsch" wrote: > On Fri, 06 Jul 2007 08:34:55 +0200, Hendrik van Rooyen wrote: > > > You can even do it more simply - by writing a GetField() that > > scans for either the delimiter or end of line or end of file, and > > returns the "field" found, along with the delimiter that caused > > it to exit, and then writing a GetRecord() that repetitively calls > > the GetField and assembles the row record until the delimiter > > returned is either the end of line or the end of file, remembering > > that the returned field may be empty, and handling the cases based > > on the delimiter returned when it is. > > > > This also makes all the decisions based on the current character > > read, no lookahead as far as I can see. > > > > Also no state variables, no switch statements... > > > > Is this the method that you would call "Mickey Mouse"? > > Maybe, because you've left out all handling of quoting and escape > characters here. Consider this: > > erik,viking,"ham, spam and eggs","He said ""Ni!""","line one > line two" > > That's 5 elements: > > 1: eric > 2: viking > 3: ham, spam and eggs > 4: He said "Ni!" > 5: line one > line two Also true - What can I say - I can only wriggle and mutter... I see that you escaped the quotes by doubling them up - What would the following parse to?: erik,viking,ham, spam and eggs,He said "Ni!",line one line two - Hendrik From arkanes at gmail.com Fri Jul 27 13:27:22 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 27 Jul 2007 12:27:22 -0500 Subject: Compiling python2.5.1 results in 3.5MB python lib? In-Reply-To: <1185556268.287077.258080@d55g2000hsg.googlegroups.com> References: <1185556268.287077.258080@d55g2000hsg.googlegroups.com> Message-ID: <4866bea60707271027x5200f47bidaa4999e85a534d@mail.gmail.com> On 7/27/07, simonbun wrote: > Hi all, > > I'm compiling 2.5.1 and end up with a 3.5MB libpython2.5.so file. I > seem to remember it should be somewhere around the 1MB mark. What > could be causing this? > > I'm using ./configure --enable-shared > > This is a problem for me seeing as i'm using apache+mod_python to > serve web content. Each apache child process incorporates libpython > and ends up starting at 7MB, which is quite large. Especially > considering the framework + code I'm using adds another 10+MB. > > Any help is appreciated. Let me know if i need to give some more > information. > Shared libraries are *shared*. The size of them is irrelevant for the purpose you list here. From steve at holdenweb.com Sat Jul 21 08:51:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 21 Jul 2007 08:51:00 -0400 Subject: Spam filter? In-Reply-To: <59f9c5160707202257x221ffdddh345326c8861da4fe@mail.gmail.com> References: <59f9c5160707202257x221ffdddh345326c8861da4fe@mail.gmail.com> Message-ID: <46A20134.7000501@holdenweb.com> Danyelle Gragsone wrote: > So, > > Can mailing lists have its mail filtered? I get more spam via mailing > lists than I do in my own inbox. I am not just singling this mailing > list. I see it a lot now. > If you had searched the list you would have found that this topic has been discussed from time to time. The fact of the matter is that a lot of effort does go into spam filtering this list, and the residual spam that you see actually represents a very low false negative rate. You wouldn't believe how much spam gets sent to the active mailing lists and newsgroups. If your own spam filtering is so good then maybe you should just subscribe to python-list instead of using a newsgroup, then your email filters will be applied to incoming articles from the list too. Oh, I see you *are* using python-list. So how come your filters don't work for the spam that gets posted? 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 hamish at cloud.net.au Wed Jul 11 00:16:32 2007 From: hamish at cloud.net.au (Hamish Moffatt) Date: Wed, 11 Jul 2007 04:16:32 GMT Subject: SafeConfigParser can set unsafe values In-Reply-To: <1184111631.293350.106340@o11g2000prd.googlegroups.com> References: <46940a3e$0$18464$afc38c87@news.optusnet.com.au> <1184111631.293350.106340@o11g2000prd.googlegroups.com> Message-ID: Matimus wrote: >> Should SafeConfigParser.set() be escaping automatically? > > It seems like that would be a nice feature. However, may I offer up > that if you are setting an option and then later on getting that value > back in the same program, you probably should have used some other > storage mechanism in the first place. That is, you shouldn't store > values needed during the runtime of your program in a ConfigParser > instance. I agree, but that was a trivial example to demonstrate the problem. Writing the file out to disk writes it exactly as set(), causing a get() to fail just the same later. > While I think you have technically pointed out a potential bug, I'm > not sure why it matters. Such a bug only comes about for (IMHO) flawed > use cases. Sorry, that's incorrect. Hamish From stefan.behnel-n05pAM at web.de Sun Jul 8 12:22:28 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 08 Jul 2007 18:22:28 +0200 Subject: Validating XML in Windows In-Reply-To: References: Message-ID: <46910F44.8090506@web.de> Omari Norman wrote: > My app needs to validate XML. That's easy enough in Unix. What is the > best way to do it in Windows? > > The most obvious choice would of course be PyXML. However, apparently it > is no longer maintained: > > http://sourceforge.net/project/showfiles.php?group_id=6473 > > so there are no Windows binaries that work with Python 2.5. Getting > other XML libraries like libxml2 also seems to be quite difficult on > Windows. > > Has anyone else dealt with this problem and found a solution? It would > even be fine if I could find a free command-line validator that I could > invoke with subprocess, but I haven't even had luck with that. lxml has statically built Windows binaries available for version 1.2.1, those for 1.3.2 should become available soon. It supports RelaxNG, XMLSchema, DTDs and (with a little patching) Schematron. http://codespeak.net/lxml/ Stefan From Xin.Zheng at jpl.nasa.gov Tue Jul 10 21:05:52 2007 From: Xin.Zheng at jpl.nasa.gov (Jason Zheng) Date: Tue, 10 Jul 2007 18:05:52 -0700 Subject: os.wait() losing child? In-Reply-To: References: Message-ID: Hate to reply to my own thread, but this is the working program that can demonstrate what I posted earlier: import os from subprocess import Popen pids = {} counts = [0,0,0] for i in xrange(3): p = Popen('sleep 1', shell=True, cwd='/home', stdout=file(os.devnull,'w')) pids[p.pid] = i print "Starting child process %d (%d)" % (i,p.pid) while (True): (pid,exitstat) = os.wait() i = pids[pid] del pids[pid] counts[i]=counts[i]+1 #terminate if count>10 if (counts[i]==10): print "Child Process %d terminated." % i if reduce(lambda x,y: x and (y>=10), counts): break continue print "Child Process %d terminated, restarting" % i p = Popen('sleep 1', shell=True, cwd='/home', stdout=file(os.devnull,'w')) pids[p.pid] = i From bthate at gmail.com Sun Jul 8 19:06:32 2007 From: bthate at gmail.com (bthate) Date: Sun, 08 Jul 2007 23:06:32 -0000 Subject: ANN: gozerbot 0.7 released Message-ID: <1183935992.848431.131890@r34g2000hsd.googlegroups.com> it time for a new gozerbot release ! we made a 0.7 release of gozerbot. new in gozerbot 0.7: * we have a new developer on the team .. Wijnand 'tehmaze' Modderman he contributed most of the new work in this release. copyright on tehmaze's work is BSD * new plugins: rest, lag, nickserv, snarf, tinyurl, umode, popcon, job * udp messaging can now be encrypted * remote installable plugins are now signed .. this means gnupg is required to install these plugins * new plugin site: http://plugins.gozerbot.org * gozerbot now has it own popularity contest webpage .. see http://plugins.gozerbot.org/popcon * new periodical class for easy scheduling of jobs * new bugtracker site: http://dev.gozerbot.org the new release can be downloaded from the following resources: * http://gozerbot.org/ * http://code.google.com/p/gozerbot * debian users can install the bot from sid/unstable From rcdailey at gmail.com Tue Jul 24 12:21:14 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Tue, 24 Jul 2007 16:21:14 -0000 Subject: wxPython - How to add sorting to a ListCtrl? Message-ID: <1185294074.410142.214140@22g2000hsm.googlegroups.com> Hi, I have 3 columns in my list control, each with a different "type" of data (for example, one column has names, the other has dates, etc). Can anyone reference a tutorial for solving this issue? I've done my share of googling to no avail. I need the user to be able to click any of the column headers and sort the rows of data by that column in ascending or descending order. Thanks for your time. From gregcorradini at gmail.com Sun Jul 29 12:41:31 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Sun, 29 Jul 2007 09:41:31 -0700 (PDT) Subject: Understanding mxODBC Insert Error Message-ID: <11852950.post@talk.nabble.com> Hello, I'm trying to perform a simple insert statement into a table called Parcel_Test (see code below). Yet, I get an error message that I've never seen before (see traceback below). I've tried to put a semicolon at the end of the sql statement, but with no luck. Any ideas from more experienced mx.ODBC users? CODE >>> driv='DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace >>> conn = odbc.DriverConnect(driv) >>> crs = conn.cursor() >>> sql = "INSERT into Parcel_Test(NEAR_FID,NEAR_DIST) values >>> ('0.000000','0.000000') where PIN_ID = '042822120008'" >>> crs.execute(sql) TRACEBACK Traceback (most recent call last): File "", line 1, in ? crs.execute(sql) ProgrammingError: ('37000', -3516, '[Microsoft][ODBC Microsoft Access Driver] Missing semicolon (;) at end of SQL statement.', 4612) -- View this message in context: http://www.nabble.com/Understanding-mxODBC-Insert-Error-tf4166125.html#a11852950 Sent from the Python - python-list mailing list archive at Nabble.com. From bignose+hates-spam at benfinney.id.au Thu Jul 26 19:45:41 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 27 Jul 2007 09:45:41 +1000 Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> <87ps2ghtd7.fsf@benfinney.id.au> <1185412639.075218.186290@z24g2000prh.googlegroups.com> <87d4yfivyv.fsf@benfinney.id.au> <1185473441.740084.85920@l70g2000hse.googlegroups.com> Message-ID: <87r6muhgpm.fsf@benfinney.id.au> "mensanator at aol.com" writes: > > The str.split method has no bearing on this discussion, > > It most certainly does. To make '123 456' into an integer, > you split it and then join it. Indeed. Which has nothing to do with the Python syntax for creating a numeric literal in code. -- \ "God forbid that any book should be banned. The practice is as | `\ indefensible as infanticide." -- Dame Rebecca West | _o__) | Ben Finney From horpner at yahoo.com Tue Jul 24 13:04:27 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Tue, 24 Jul 2007 17:04:27 GMT Subject: classmethod & staticmethod References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> <46a5b2ad$0$18903$426a74cc@news.free.fr> Message-ID: On 2007-07-24, Alex Popescu wrote: > Bruno Desthuilliers wrote > in news:46a5b2ad$0$18903$426a74cc at news.free.fr: > > >> >> [snip...] >> >> >> Not necessarily - you can access class attributes from within an >> instance method (but obviously a classmethod cannot access instance >> attributes). >> > > What I am doing wrong here then: > > class MyClass(object): > class_list = ['a', 'b'] > > def instance_method(self): > print "instance_method with class list %s" % class_list There's no implicit self or class for Python identifiers. The name class_list must be quailified: self.class_list or MyClass.class_list. -- Neil Cerutti From aleax at mac.com Sat Jul 14 00:43:43 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 13 Jul 2007 21:43:43 -0700 Subject: Can a low-level programmer learn OOP? References: Message-ID: <1i17kzo.1kphm951d3jl5dN%aleax@mac.com> Chris Carlen wrote: > From what I've read of OOP, I don't get it. I have also found some > articles profoundly critical of OOP. I tend to relate to these articles. OOP can be abused (particularly with deep or intricate inheritance structures). But the base concept is simple and clear: you can bundle state and behavior into a stateful "black box" (of which you may make as many instances, with independent state but equal behavior, as you need). > Hence, being a hardware designer rather than a computer scientist, I am > conditioned to think like a machine. I think this is the main reason > why OOP has always repelled me. I'm an MS in EE (minoring in computer engineering) by training (over a quarter century ago:-); I "slid" into programming kind of inexhorably (fate obviously wanted me to:-) but paradigms such as OOP (and functional programming, but that's another subject) always made sense to me *in direct analogy to my main discipline*. A JK flip-flop and a D flip-flop are objects with 1-bit states and different behavior; I may put in my circuit as many (e.g.) J-K flip-flops as I need, and each will have separate state, even though each will have identical behavior (how it responds to signals on the J and K lines). I don't need to think about how a J-K flip-flop is *made*, inside; I use it as a basic component in designing richer circuits (well, I did back when I DID design circuits, but I haven't _totally_ forgotten:-). I do know how to make one in terms of transistors, should I ever need to (well, maybe I'd have to look it up, but I _used_ to know:-), but such a need is unlikely to arise, because it's likely to be there as a basic component in whatever design library I'm supposed to use for this IC. Components much richer than J-K flip-flops are obviously more common nowadays, but remember my real-world experience designing chips is from the early '80s;-). Nevertheless the concept of a "bundle of state and behavior" is still there -- and a direct, immediate analogy to OOP. (Functional programming, OTOH, is analogous to stateless input-output transformation circuits, an even more basic concept in HW design:-). If anything, it's the concept of "procedural programming" that has no direct equivalent in HW design (unless you consider microcode "HW", and, personally, I don't;-). [[Fortunately as a part of the CE minor I did learn Fortran, Lisp and Pascal, and a few machine-languages too, so I wasn't totally blown away when I found myself earning a living by programming rather than by designing chips, but that's another story:-)]] Alex From jeffober at gmail.com Wed Jul 25 16:54:00 2007 From: jeffober at gmail.com (Jeff) Date: Wed, 25 Jul 2007 20:54:00 -0000 Subject: first, second, etc line of text file In-Reply-To: <13afdpp7a6t24c5@corp.supernews.com> References: <5f56302b0707251244p24080f1ct87a5f459cb175dae@mail.gmail.com> <13afdpp7a6t24c5@corp.supernews.com> Message-ID: <1185396840.702955.31890@l70g2000hse.googlegroups.com> Grant, That might be a memory problem if you are running multiple processes regularly, such as on a webserver. From michele.simionato at gmail.com Mon Jul 16 01:53:40 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Mon, 16 Jul 2007 05:53:40 -0000 Subject: How to determine which method was used in an inheritance heirarchy? In-Reply-To: References: <1184559788.712146.238190@q75g2000hsh.googlegroups.com> Message-ID: <1184565220.674041.270790@o61g2000hsh.googlegroups.com> On Jul 16, 7:18 am, Erik Jones wrote: > On Jul 15, 2007, at 11:23 PM, Michele Simionato wrote: > > > On Jul 16, 5:51 am, Erik Jones wrote: > >> Say you're given a call event frame for a method call. How can you > >> tell if the code being executed came from a super class of the object > >> or class the method was called on? > > >> Erik Jones > > > You look if the method was defined in self.__class__.__dict__. > > > Michele Simionato > > That doesn't seem to cover calling super class __init__ methods. > I am probably missing something. In the following code the method check_init checks if the current instance possess an __init__ or if it just inherits one from the ancestors. Is this what you want? class B(object): def __init__(self): 'something' def check_init(self): if '__init__' in self.__class__.__dict__: print 'possesses __init__' else: print 'inherits __init__' class C(B): 'something else' def __init__(self): print 'calling C.__init__' class D(B): pass c = C() d = D() c.check_init() #possesses __init__ d.check_init() #inherits __init__ From mensanator at aol.com Tue Jul 17 20:25:05 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Tue, 17 Jul 2007 17:25:05 -0700 Subject: a=0100; print a ; 64 how to reverse this? In-Reply-To: <1184676038.231330.115220@e16g2000pri.googlegroups.com> References: <1184670575.205759.115360@i13g2000prf.googlegroups.com> <1184673934.660465.228280@i13g2000prf.googlegroups.com> <1184676038.231330.115220@e16g2000pri.googlegroups.com> Message-ID: <1184718305.415567.144940@e9g2000prf.googlegroups.com> On Jul 17, 7:40 am, mosi wrote: > Thank you, > this is great, > I thought that this should be standard in python 2.4 or 2.5 or in some > standard library (math ???) > Didn`t find anything. You can also look up the gmpy module (not part of standard library). It contains a lot of functions for use with binary numbers (there are many others, I'm just showing the ones used for binary numbers): DESCRIPTION gmpy 1.04 - General Multiprecision arithmetic for PYthon: exposes functionality from the GMP 4 library to Python 2.{2,3,4}. Allows creation of multiprecision integer (mpz), float (mpf), and rational (mpq) numbers, conversion between them and to/from Python numbers/strings, arithmetic, bitwise, and some other higher-level mathematical operations; also, pretty good-quality linear-congruential random number generation and shuffling. mpz has comparable functionality to Python's builtin longs, but can be faster for some operations (particularly multiplication and raising-to-power) and has many further useful and speedy functions (prime testing and generation, factorial, fibonacci, binary-coefficients, gcd, lcm, square and other roots, ...). mpf and mpq only offer basic arithmetic abilities, but they do add the ability to have floating-point numbers ensuring at least a predefined number of bits' worth of precision (and with potentially-huge or extremely-tiny magnitudes), as well as unlimited-precision rationals, with reasonably-fast operations, which are not built-in features of Python. FUNCTIONS digits(...) digits(x[,base]): returns Python string representing x in the given base (2 to 36, default 10 if omitted or 0); leading '-' present if x<0, but no leading '+' if x>=0. x must be an mpz, or else gets coerced into one. getbit(...) getbit(x,n): returns 0 or 1, the bit-value of bit n of x; n must be an ordinary Python int, >=0; x is an mpz, or else gets coerced to one. hamdist(...) hamdist(x,y): returns the Hamming distance (number of bit- positions where the bits differ) between x and y. x and y must be mpz, or else get coerced to mpz. lowbits(...) lowbits(x,n): returns the n lowest bits of x; n must be an ordinary Python int, >0; x must be an mpz, or else gets coerced to one. numdigits(...) numdigits(x[,base]): returns length of string representing x in the given base (2 to 36, default 10 if omitted or 0); the value returned may sometimes be 1 more than necessary; no provision for any 'sign' characte, nor leading '0' or '0x' decoration, is made in the returned length. x must be an mpz, or else gets coerced into one. popcount(...) popcount(x): returns the number of 1-bits set in x; note that this is 'infinite' if x<0, and in that case, -1 is returned. x must be an mpz, or else gets coerced to one. scan0(...) scan0(x, n=0): returns the bit-index of the first 0-bit of x (that is at least n); n must be an ordinary Python int, >=0. If no more 0-bits are in x at or above bit-index n (which can only happen for x<0, notionally extended with infinite 1-bits), None is returned. x must be an mpz, or else gets coerced to one. scan1(...) scan1(x, n=0): returns the bit-index of the first 1-bit of x (that is at least n); n must be an ordinary Python int, >=0. If no more 1-bits are in x at or above bit-index n (which can only happen for x>=0, notionally extended with infinite 0-bits), None is returned. x must be an mpz, or else gets coerced to one. setbit(...) setbit(x,n,v=1): returns a copy of the value of x, with bit n set to value v; n must be an ordinary Python int, >=0; v, 0 or ! =0; x must be an mpz, or else gets coerced to one. From donn at u.washington.edu Fri Jul 13 14:52:06 2007 From: donn at u.washington.edu (Donn Cave) Date: Fri, 13 Jul 2007 11:52:06 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <87zm20iw3e.fsf@benfinney.id.au> <7x1wfcviqx.fsf@ruckus.brouhaha.com> Message-ID: In article <7x1wfcviqx.fsf at ruckus.brouhaha.com>, Paul Rubin wrote: > Ben Finney writes: > > This is interesting. Do you have any references we can read about this > > assertion -- specifically, that "GOTO" was not well loved (I assume > > "by the programming community at large") even by around 1966? > > Dijkstra's famous 1968 "GOTO considered harmful" letter > (http://www.acm.org/classics/oct95/) quotes a 1966 article by N. Wirth > and C.A.R. Hoare: > > The remark about the undesirability of the go to statement is far from > new. I remember having read the explicit recommendation to restrict > the use of the go to statement to alarm exits, but I have not been > able to trace it; presumably, it has been made by C. A. R. Hoare. In > [1, Sec. 3.2.1.] Wirth and Hoare together make a remark in the same > direction in motivating the case construction: "Like the conditional, > it mirrors the dynamic structure of a program more clearly than go to > statements and switches, and it eliminates the need for introducing a > large number of labels in the program." > > Reference: 1. Wirth, Niklaus, and Hoare C. A. R. A contribution > to the development of ALGOL. Comm. ACM 9 (June 1966), 413-432. So, all I need is comments from a computer scientist or two, pointing out problems with the procedural/imperative programming model, and we can establish that it was already hated and on its way out by the late 90's? How about OOP? Already on its way out by the time Python 1.0 hit the streets? The thing that allows us to be so smug about the follies of the past, is that we can pretend everyone knew better. Donn Cave, donn at u.washington.edu From danb_83 at yahoo.com Tue Jul 3 23:46:58 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Tue, 03 Jul 2007 20:46:58 -0700 Subject: Questions about input lines (maximum length and continuation) In-Reply-To: <1183520480.036284.254770@n60g2000hse.googlegroups.com> References: <1183520480.036284.254770@n60g2000hse.googlegroups.com> Message-ID: <1183520818.830032.318990@k29g2000hsd.googlegroups.com> On Jul 3, 10:41 pm, Robert Dodier wrote: > Hello, > > I'm planning to write a program which automatically generates > Python code. > > (1) Is there a limit on the length of a line in a Python program? No. > (2) From what I understand, symbols, operators, and numbers > cannot be broken across lines continued with the backslash > character. Is there any way to allow symbols, operators, and > numbers to be broken across lines? >>> exec '''my_ ... var = 1234 ... 567'''.replace('\n', '') >>> my_var 1234567 Why do you want to do this? From kyosohma at gmail.com Thu Jul 12 18:28:52 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: Thu, 12 Jul 2007 22:28:52 -0000 Subject: wx.App console window [Windows] In-Reply-To: <1184273064.350399.152490@o61g2000hsh.googlegroups.com> References: <1184273064.350399.152490@o61g2000hsh.googlegroups.com> Message-ID: <1184279332.640059.120140@k79g2000hse.googlegroups.com> On Jul 12, 3:44 pm, siw... at gmail.com wrote: > Hi All, > > I'm looking for a way to hide console window created by wx.App class. > > examplary code below: > > import wx > > class Gui(wx.App): > def __init__(self, *pargs, **kwargs): > wx.App.__init__(self, *pargs, **kwargs) > > if __name__ == "__main__": > app = Gui() > app.MainLoop() > > produces a blank console window (than dies). > > What shall I do to make wx.App run without raising console window? > > thanks in advance Save the file as a *.pyw. And I would recommend adding the following 2 lines to your __init__ : frame = wx.Frame(None, wx.ID_ANY, title='My Title') frame.Show() Maybe even stick in a panel object for that matter. Mike From doug at alum.mit.edu Mon Jul 2 13:39:06 2007 From: doug at alum.mit.edu (Douglas Alan) Date: Mon, 02 Jul 2007 13:39:06 -0400 Subject: Python's "only one way to do it" philosophy isn't good? References: <7xejjzmk7u.fsf@ruckus.brouhaha.com> <7xy7i7xjl5.fsf@ruckus.brouhaha.com> <9uRhi.17027$xk5.14289@edtnps82> Message-ID: Lenard Lindstrom writes: >>> Explicitly clear the exception? With sys.exc_clear? >> Yes. Is there a problem with that? > As long as nothing tries to re-raise the exception I doubt it breaks > anything: > > >>> import sys > >>> try: > raise StandardError("Hello") > except StandardError: > sys.exc_clear() > raise > > > Traceback (most recent call last): > File "", line 5, in > raise > TypeError: exceptions must be classes, instances, or strings > (deprecated), not NoneType I guess I don't really see that as a problem. Exceptions should normally only be re-raised where they are caught. If a piece of code has decided to handle an exception, and considers it dealt with, there is no reason for it not to clear the exception, and good reason for it to do so. Also, any caught exception is automatically cleared when the catching procedure returns anyway, so it's not like Python has ever considered a caught exception to be precious information that ought to be preserved long past the point where it is handled. > But it is like calling the garbage collector. You are tuning the > program to ensure some resource isn't exhausted. I'm not sure I see the analogy: Calling the GC can be expensive, clearing an exception is not. The exception is going to be cleared anyway when the procedure returns, the GC wouldn't likely be. It's much more like explicitly assigning None to a variable that contains a large data structure when you no longer need the contents of the variable. Doing this sort of thing can be a wise thing to do in certain situations. > It relies on implementation specific behavior to be provably > reliable*. As Python is not a formally standardized language, and one typically relies on the fact that CPython itself is ported to just about every platform known to Man, I don't find this to be a particular worry. > If this is indeed the most obvious way to do things in your > particular use case then Python, and many other languages, is > missing something. If the particular problem is isolated, > formalized, and general solution found, then a PEP can be > submitted. If accepted, this would ensure future and cross-platform > compatibility. Well, I think that the refcounting semantics of CPython are useful, and allow one to often write simpler, easier-to-read and maintain code. I think that Jython and IronPython, etc., should adopt these semantics, but I imagine they might not for performance reasons. I don't generally use Python for it's speediness, however, but rather for it's pleasant syntax and semantics and large, effective library. |>oug From bj_666 at gmx.net Tue Jul 3 06:19:59 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 3 Jul 2007 10:19:59 GMT Subject: restructuredtext latin1 encoding (FAQ?) References: <5eulnmF3ates7U1@mid.dfncis.de> Message-ID: <5eum6fF39v66mU1@mid.uni-berlin.de> On Tue, 03 Jul 2007 12:12:04 +0200, Helmut Jarausch wrote: > Is there a way to write documents with the reST tools using the Latin1 > encoding? Yes of course there is. Just write the documents in Latin-1 encoding. Take a look at the charset command line options if Latin-1 is not the default encoding used by your operating system. Ciao, Marc 'BlackJack' Rintsch From brianjiang at gdnt.com.cn Tue Jul 10 00:58:18 2007 From: brianjiang at gdnt.com.cn (brianjiang at gdnt.com.cn) Date: Tue, 10 Jul 2007 12:58:18 +0800 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: Message-ID: <63F95800EDD046419F17688AAFD41CCF01AE140D@rnd-ex01.rnd.gdnt.local> >>> ((((2**2)**2)**2)**2) 65536 >>> 2**(2**(2**(2**2))) 200352993040684646497907235156025575044782547556975141926501697371089405955631145308950613088............................................. The same as "2**2**2**2**2" -----Original Message----- From: python-list-bounces+brianjiang=gdnt.com.cn at python.org [mailto:python-list-bounces+brianjiang=gdnt.com.cn at python.org] On Behalf Of Jim Langston Sent: 2007?7?10? 12:47 To: python-list at python.org Subject: Re: 2**2**2**2**2 wrong? Bug? "Paul Rubin" wrote in message news:7xbqek7ty1.fsf at ruckus.brouhaha.com... > "Jim Langston" writes: >> In Python 2.5 on intel, the statement >> 2**2**2**2**2 >> evaluates to >> >>> 2**2**2**2**2 > > I get the same number from hugs--why do you think it might be wrong? 2**2 = 4 4**2 = 16 16**2 = 256 256**2 = 65536 65536**2 = 4294967296 In fact, if I put (2**2)**2**2**2 it comes up with the correct answer, 4294967296 -- http://mail.python.org/mailman/listinfo/python-list From horpner at yahoo.com Thu Jul 5 10:53:39 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 05 Jul 2007 14:53:39 GMT Subject: The best platform and editor for Python References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183644537.859604.27790@w5g2000hsg.googlegroups.com> <1183645746.239349.68260@n2g2000hse.googlegroups.com> Message-ID: On 2007-07-05, Paul McGuire wrote: > On Jul 5, 9:21 am, Roy Smith wrote: >> In article <1183644537.859604.27... at w5g2000hsg.googlegroups.com>, >> Nicola Musatti wrote: >> >> > On Jul 5, 1:23 pm, Gregor Horvath wrote: >> > [...] >> > > That's a property of open source projects. >> > > Features nobody really needs are not implemented. >> >> > No, no, you got it all wrong. It's in *commercial* projects that >> > features nobody really needs are not implemented. >> >> No, no, squared. In a commercial project, the only features that get >> implemented are the ones somebody is willing to pay for. Whether there is >> any correlation between need and willingness to pay is an open question. > > Then tell us, pray, who was willing to pay for the epitome of useless > features in MS Word, that Useless Features' Useless Feature, the > ability to format text with the animated effect "Marching Red Ants"? > I'm sure I paid for it, but it wasn't willingly... You should count your blessings. At least it doesn't play pinball any more. At least, I hope not. -- Neil Cerutti From semanticist at gmail.com Wed Jul 11 03:59:55 2007 From: semanticist at gmail.com (Miles) Date: Wed, 11 Jul 2007 00:59:55 -0700 Subject: bool behavior in Python 3000? In-Reply-To: References: <5ficp9F3cram2U2@mid.individual.net> <469472f4$0$1293$9b622d9e@news.freenet.de> Message-ID: <1184140795.974059.302830@22g2000hsm.googlegroups.com> On Jul 11, 2:50 am, Alan Isaac wrote: > >>> bool(False-True) > > True What boolean operation does '-' represent? From ricaraoz at gmail.com Tue Jul 31 14:33:48 2007 From: ricaraoz at gmail.com (=?ISO-8859-1?Q?Ricardo_Ar=E1oz?=) Date: Tue, 31 Jul 2007 15:33:48 -0300 Subject: Encryption recommendation In-Reply-To: <1185903692.138145.42210@z28g2000prd.googlegroups.com> References: <1185903692.138145.42210@z28g2000prd.googlegroups.com> Message-ID: <46AF808C.1060000@bigfoot.com> Azazello wrote: > On Jul 31, 10:19 am, "JS" wrote: >> Can someone help me find the proper way to do AES encryption/decryption >> using Python? >> >> Thanks! > > I did a quick look around the internet and found this seemingly good > link AES in general. Might be a good start. > > http://msdn.microsoft.com/msdnmag/issues/03/11/AES/#S4 > > Looks like you'll need some matrix manipulations modules, and > hopefully you'll be able to utilize Python's indexing and data > strengths to keep things simple! > Or you might use PyCrypto (http://python.codezoo.com/pub/component/5284) which might be easier. From kipster-t at earthlink.net Fri Jul 13 13:43:36 2007 From: kipster-t at earthlink.net (Kip Lehman) Date: Fri, 13 Jul 2007 17:43:36 GMT Subject: Tibco Rendezvous Message-ID: Circa summer 2003, at a company I previously worked at, a co-worker and I had an occasion to see if we could get Python and TIBCO Rendezvous working together. The SWIG-based tibrv mechanism was insufficient, buggy and was problematic in terms of keeping up with Python releases. We resorted to using ctypes with the relevant TIBCO header files and confabulating our own package to work with TIBCO Rendezvous messages (both publishing and subscribing). We didn't concern ourselves with certified messages. Feel free to contact me directly if you want me to see if I can unearth any further info. -- -- Kip Lehman kipster t earthlink net ...still waiting for PanAm, Amtrack and the USPS to deliver my .sig From owntheweb at gmail.com Mon Jul 9 16:03:44 2007 From: owntheweb at gmail.com (Ultrus) Date: Mon, 09 Jul 2007 20:03:44 -0000 Subject: dealing with nested xml within nested xml within...... Message-ID: <1184011424.662766.176530@k79g2000hse.googlegroups.com> Hello all, I don't need specific examples, but I'm trying to wrap my head around parsing xml within xml and even further, not limiting how far someone will nest xml. I'm already making great use of BeautifulSoup's BeautifulStoneSoup to parse xml, but what do I do if I come across something like this?
  • This is a random response (once parsed)
  • This is a random response within a random response
  • This is a random response within a random response, within another random response
  • Like above, this is another random response.
  • Not knowing how far one will nest random responses, how would one manage digging into xml like this? Right now I'm thinking about not even going there. I would presently write scripts that would parse 3 or so levels deep, but no further. :P It would make an interesting project, like an interactive adventure story. From garyfreder at gmail.com Sat Jul 7 07:31:36 2007 From: garyfreder at gmail.com (Gary) Date: Sat, 07 Jul 2007 04:31:36 -0700 Subject: Empty string namespace on XP in minidom Message-ID: <1183807896.846998.239560@r34g2000hsd.googlegroups.com> Howdy I ran into a difference between Python on Windows XP and Linux Fedora 6. Writing a dom to xml with minidom works on Linux. It gives an error on XP if there is an empty namespace. The problem was handled in CVS a while ago. http://mail.python.org/pipermail/xml-sig/2003-October/009904.html Here is an example on XP Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> from xml.dom.minidom import parseString >>> doc = parseString('value') >>> doc.toxml() u'value' >>> doc = parseString('value') >>> doc.toxml() Traceback (most recent call last): File "", line 1, in File "C:\tools\Python25\lib\xml\dom\minidom.py", line 45, in toxml return self.toprettyxml("", "", encoding) File "C:\tools\Python25\lib\xml\dom\minidom.py", line 57, in toprettyxml self.writexml(writer, "", indent, newl, encoding) File "C:\tools\Python25\lib\xml\dom\minidom.py", line 1744, in writexml node.writexml(writer, indent, addindent, newl) File "C:\tools\Python25\lib\xml\dom\minidom.py", line 809, in writexml _write_data(writer, attrs[a_name].value) File "C:\tools\Python25\lib\xml\dom\minidom.py", line 299, in _write_data data = data.replace("&", "&").replace("<", "<") AttributeError: 'NoneType' object has no attribute 'replace' and it's working on Linux Python 2.4.4 (#1, Oct 23 2006, 13:58:00) [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from xml.dom.minidom import parseString >>> doc = parseString('value') >>> doc.toxml() u'\nvalue' >>> doc = parseString('value') >>> doc.toxml() u'\nvalue' Should the library on XP be updated? Gary From oneelkruns at hotmail.com Sun Jul 1 19:35:51 2007 From: oneelkruns at hotmail.com (rtk) Date: Sun, 01 Jul 2007 16:35:51 -0700 Subject: Tiny/small/minimalist Python? Message-ID: <1183332951.122782.212720@o11g2000prd.googlegroups.com> I'm looking for information on building a tiny/small/minimalist/ vanilla python interpreter. One that implements the core language and a few of the key modules but isn't tied to any specific operating system. I guess I'm asking for the smallest subset of the standard Python source code files that is necessary to get a working interpreter using a plain C compiler. Is this even possible? If so, has someone done it already? I've looked on Google and in comp.lang.python but nothing comes up. Thanks! Ron From alberto.griggio at gmail.com Thu Jul 26 06:53:12 2007 From: alberto.griggio at gmail.com (Alberto Griggio) Date: Thu, 26 Jul 2007 12:53:12 +0200 Subject: wxGlade: Who knows how to drive this application? References: Message-ID: <200707261051.l6QApTMC009045@dit.unitn.it> Hello, > I've been trying to use wxGlade recently and I am finding it something > of a challenge. Is there any user who finds the user interface > satisfactory and the operation of the program predictable? > > If so I would love to hear from you. Do you have some specific example of what you mean? Sure, wxGlade has bugs and isn't always in sync with the latest wxPython changes (usually the CVS version is better in this respect), but suggestions on how to improve it are always welcome... Alberto From china_city2008 at yahoo.com.cn Tue Jul 3 11:45:06 2007 From: china_city2008 at yahoo.com.cn (jim) Date: Tue, 03 Jul 2007 08:45:06 -0700 Subject: ebay In-Reply-To: <1182352821.514197.148330@j4g2000prf.googlegroups.com> References: <1182352821.514197.148330@j4g2000prf.googlegroups.com> Message-ID: <1183477506.344685.16610@m37g2000prh.googlegroups.com> On 6 20 , 11 20 , jim wrote: > hello: madam and sir . we sell all kinds of laptops and digital > cam .our product is a quantity best, the price is the lowest in the > world, i think you will be interested in our product . thanks a lot! > Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com > mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam > and sir. we sell all kinds of laptops and digital cam .our product is > a quantity best, the price is the lowest in the world, i think you > will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . > we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and > sir. we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > hello: madam and sir . we sell all kinds of laptops and digital > cam .our product is a quantity best, the price is the lowest in the > world, i think you will be interested in our product . thanks a lot! > Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com > mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam > and sir. we sell all kinds of laptops and digital cam .our product is > a quantity best, the price is the lowest in the world, i think you > will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . > we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and > sir. we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > hello: madam and sir . we sell all kinds of laptops and digital > cam .our product is a quantity best, the price is the lowest in the > world, i think you will be interested in our product . thanks a lot! > Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com > mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam > and sir. we sell all kinds of laptops and digital cam .our product is > a quantity best, the price is the lowest in the world, i think you > will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . > we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and > sir. we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > hello: madam and sir . we sell all kinds of laptops and digital > cam .our product is a quantity best, the price is the lowest in the > world, i think you will be interested in our product . thanks a lot! > Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com > mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam > and sir. we sell all kinds of laptops and digital cam .our product is > a quantity best, the price is the lowest in the world, i think you > will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . > we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and > sir. we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > hello: madam and sir . we sell all kinds of laptops and digital > cam .our product is a quantity best, the price is the lowest in the > world, i think you will be interested in our product . thanks a lot! > Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com > mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam > and sir. we sell all kinds of laptops and digital cam .our product is > a quantity best, the price is the lowest in the world, i think you > will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . > we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and > sir. we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > hello: madam and sir . we sell all kinds of laptops and digital > cam .our product is a quantity best, the price is the lowest in the > world, i think you will be interested in our product . thanks a lot! > Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com > mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam > and sir. we sell all kinds of laptops and digital cam .our product is > a quantity best, the price is the lowest in the world, i think you > will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . > we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and > sir. we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > hello: madam and sir . we sell all kinds of laptops and digital > cam .our product is a quantity best, the price is the lowest in the > world, i think you will be interested in our product . thanks a lot! > Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com > mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam > and sir. we sell all kinds of laptops and digital cam .our product is > a quantity best, the price is the lowest in the world, i think you > will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . > we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and > sir. we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > hello: madam and sir . we sell all kinds of laptops and digital > cam .our product is a quantity best, the price is the lowest in the > world, i think you will be interested in our product . thanks a lot! > Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com > mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam > and sir. we sell all kinds of laptops and digital cam .our product is > a quantity best, the price is the lowest in the world, i think you > will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . > we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and > sir. we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > hello: madam and sir . we sell all kinds of laptops and digital > cam .our product is a quantity best, the price is the lowest in the > world, i think you will be interested in our product . thanks a lot! > Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com > mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam > and sir. we sell all kinds of laptops and digital cam .our product is > a quantity best, the price is the lowest in the world, i think you > will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . > we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and > sir. we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > hello: madam and sir . we sell all kinds of laptops and digital > cam .our product is a quantity best, the price is the lowest in the > world, i think you will be interested in our product . thanks a lot! > Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com > mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam > and sir. we sell all kinds of laptops and digital cam .our product is > a quantity best, the price is the lowest in the world, i think you > will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone > @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . > we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with > everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and > sir. we sell all kinds of laptops and digital cam .our product is a > quantity best, the price is the lowest in the world, i think you will > be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/Msn: prs_cool_... at hotmail.com mail: > prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http://www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello: madam and sir . we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone . @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ hello : madam and sir. we sell all kinds of laptops and digital cam .our product is a quantity best, the price is the lowest in the world, i think you will be interested in our product . thanks a lot! Our Website:http:// www.prs-123.com/ Msn: prs_cool_... at hotmail.com mail: prs_cool_... at yahoo.com.cn thanks for everyone good luck with everyone From the.mindstorm.mailinglist at gmail.com Thu Jul 12 11:47:20 2007 From: the.mindstorm.mailinglist at gmail.com (Alex Popescu) Date: Thu, 12 Jul 2007 08:47:20 -0700 Subject: Lists in classes In-Reply-To: <1184253811.052346.220470@22g2000hsm.googlegroups.com> References: <1184253811.052346.220470@22g2000hsm.googlegroups.com> Message-ID: <1184255240.559017.61330@o61g2000hsh.googlegroups.com> On Jul 12, 6:23 pm, Jeremy Lynch wrote: > Hello, > > Learning python from a c++ background. Very confused about this: > > ============ > class jeremy: > list=[] > def additem(self): > self.list.append("hi") > return > > temp = jeremy() > temp.additem() > temp.additem() > print temp.list > > temp2 = jeremy() > print temp2.list > ============== > The output gives: > ['hi','hi'] > ['hi','hi'] > > Why does adding items to one instance produce items in a separate > instance? Doesn't each instance of jeremy have its' own "list"? > > Many thanks for clearing up this newbie confusion. > > Jeremy. You are defining the list in the class context and so it becomes a class field/member. For defining instance members you need to always prefix those with self (this) in the contexts it is available (f.e. in the instance method context). bests, ./alex -- .w( the_mindstorm )p. From martin at v.loewis.de Mon Jul 30 01:47:14 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 30 Jul 2007 07:47:14 +0200 Subject: Compiling 2.5.1 on OpenBSD 4.1 In-Reply-To: References: <46AC1B91.3070706@v.loewis.de> <46ACC344.1020701@v.loewis.de> Message-ID: <46AD7B62.3090506@v.loewis.de> > __BSD_VISIBLE is there (it wasn't there before and that's what was causing my original problem). > dnm at kili:/bu/pkg/Python-2.5.1$ grep _BSD_SOURCE pyconfig.h > dnm at kili:/bu/pkg/Python-2.5.1$ grep _BSD_VISIBLE pyconfig.h > #define __BSD_VISIBLE 1 It being in pyconfig.h is irrelevant - it was there before; my proposed patch hasn't changed that. The problem is that sys/cdefs.h defines __BSD_VISIBLE to 0 under certain circumstances; I was hoping that my patch would change these circumstances. I don't have OpenBSD available, so I have to do all my research over the web. I would really appreciate if this problem could be solved "for good". In the past, it was always difficult that the *BSDs would hide interfaces if I say that my program uses XOPEN/Unix. Python uses a "POSIX+" approach: use POSIX interfaces where available; use platform-specific ones elsewhere. It seems that OpenBSD (now) also supports such an approach, with the _BSD_SOURCE define. So I would much appreciate some help in making it so that Python actually gets access to these interfaces; then, from OpenBSD 4.1 on, no additional system-specific changes would have to be made. > posixmodule.i: > ssize_t pread(int, void *, size_t, off_t); > ssize_t pwrite(int, const void *, size_t, off_t); > int ttyname_r(int, char *, size_t) > __attribute__((__bounded__(__string__,2,3))); > # 188 "/usr/include/unistd.h" 3 4 > int lockf(int, int, off_t); > --- In some versions of gcc, there is a mechanism to also record the #define's and #undefines in the preprocessor output (e.g. -dD). If such a mechanism is available in the OpenBSD gcc, please use it to see what gets defined (and undefined) in what order. If that fails, sprinkle #ifndef __BSD_VISIBLE #error broken #endif throughout the files, e.g. between #include directives, and (if you can) into the system headers themselves. > Plus, I get lots of warnings that I didn't get using my patch. Sample: > > gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include -DPy_BUILD_CORE -c ./Modules/threadmodule.c -o Modules/threadmodule.o > In file included from Include/Python.h:57, > from Modules/threadmodule.c:5: > Include/pyport.h:520: warning: `struct winsize' declared inside parameter list > Include/pyport.h:520: warning: its scope is only this definition or declaration, which is probably not what you want > Include/pyport.h:521: warning: `struct winsize' declared inside parameter list This should be the same problem: struct winsize is conditional. > Here are the differences between the pyconfig.h with my patch and with yours: > > dnm at kili:/bu/pkg/Python-2.5.1$ diff pyconfig.h pyconfig.h.martin I see. The macros _BSD_SOURCE didn't actually get defined. Please try the revised patch below. Regards, Martin Index: configure =================================================================== --- configure (Revision 56599) +++ configure (Arbeitskopie) @@ -1388,6 +1388,14 @@ _ACEOF +# OpenBSD undoes our definition of __BSD_VISIBLE if _XOPEN_SOURCE is +# also defined. This can be overridden by defining _BSD_SOURCE + +cat >>confdefs.h <<\_ACEOF +#define _BSD_SOURCE 1 +_ACEOF + + # The later defininition of _XOPEN_SOURCE and _POSIX_C_SOURCE disables # u_int on Irix 5.3. Defining _BSD_TYPES brings it back. Index: pyconfig.h.in =================================================================== --- pyconfig.h.in (Revision 56599) +++ pyconfig.h.in (Arbeitskopie) @@ -909,6 +909,9 @@ # undef _ALL_SOURCE #endif +/* Define on OpenBSD to activate all library features */ +#undef _BSD_SOURCE + /* Define on Irix to enable u_int */ #undef _BSD_TYPES From samwyse at gmail.com Thu Jul 12 12:48:45 2007 From: samwyse at gmail.com (samwyse) Date: Thu, 12 Jul 2007 09:48:45 -0700 Subject: Re-raising exceptions with modified message In-Reply-To: <1184239885.828717.271410@r34g2000hsd.googlegroups.com> References: <1183863713.876365.111820@57g2000hsv.googlegroups.com> <1184239885.828717.271410@r34g2000hsd.googlegroups.com> Message-ID: <1184258925.321462.50270@k79g2000hse.googlegroups.com> On Jul 12, 6:31 am, samwyse wrote: > On Jul 8, 8:50 am, Christoph Zwerschke wrote: > > > With Py 2.5 I get: > > > new.__class__ = old.__class__ > > TypeError: __class__ must be set to a class Hmmm, under Python 2.4.X, printing repr(old.__class__) gives me this: while under 2.5.X, I get this: So, let's try sub-classing the type: def modify_message(old, f): class Empty: pass new = Empty() print "old.__class__ =", repr(old.__class__) print "Empty =", repr(Empty) new.__class__ = Empty class Excpt(old.__class__): pass print "Excpt =", repr(Excpt) print "Excpt.__class__ =", repr(Excpt.__class__) new.__class__ = Excpt new.__dict__ = old.__dict__.copy() new.__str__ = f return new Nope, that gives us the same message: old.__class__ = Empty = Excpt = Excpt.__class__ = Traceback (most recent call last): [...] TypeError: __class__ must be set to a class Excpt ceratinly appears to be a class. Does anyone smarter than me know what's going on here? From brotherjenos at gmail.com Thu Jul 19 01:51:57 2007 From: brotherjenos at gmail.com (Walker Lindley) Date: Wed, 18 Jul 2007 22:51:57 -0700 Subject: Pickled objects over the network In-Reply-To: References: <9c8d48280707171457p4448fdf3of40562bf62a18fc6@mail.gmail.com> <20070718095248.4947.1882106103.divmod.quotient.13020@ohm> Message-ID: <9c8d48280707182251v4adc3f08h1427eb67b2eedab@mail.gmail.com> I tried implementing the sending the length and then the pickle string method and that worked most of the time. The problem we ran into was if the string got split up into multiple packets and you read the first one and tried to unpickle it, you'd get an error. So a while loop that keeps calling recv until you have the correct amount of data solves that problem. It still doesn't make pickle secure, though, so we'll probably end up doing something else. Thank you to everyone for all of your great help and insight. -Walker On 7/18/07, Eduardo EdCrypt O. Padoan wrote: > > On 7/18/07, Jean-Paul Calderone wrote: > > On Tue, 17 Jul 2007 14:57:16 -0700, Walker Lindley < > brotherjenos at gmail.com> wrote: > [...] > > The obvious thing you're doing wrong is using pickle over a network. ;) > > > > http://jcalderone.livejournal.com/15864.html > > Ok, maybe not the best tools to the job, but there are some more > secure alternatives: > http://trustedpickle.sourceforge.net/ > http://home.gna.org/oomadness/en/cerealizer/index.html > > -- > EduardoOPadoan (eopadoan->altavix::com) > Bookmarks: http://del.icio.us/edcrypt > -- > http://mail.python.org/mailman/listinfo/python-list > -- 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: From S.Mientki-nospam at mailbox.kun.nl Wed Jul 18 02:37:51 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 18 Jul 2007 08:37:51 +0200 Subject: wxPython and threads In-Reply-To: <1184726489.112138.96350@z28g2000prd.googlegroups.com> References: <1184726489.112138.96350@z28g2000prd.googlegroups.com> Message-ID: Benjamin wrote: > I'm writing a search engine in Python with wxPython as the GUI. I have > the actual searching preformed on a different thread from Gui thread. > It sends it's results through a Queue to the results ListCtrl which > adds a new item. This works fine or small searches, but when the > results number in the hundreds, the GUI is frozen for the duration of > the search. I suspect that so many search results are coming in that > the GUI thread is too busy updating lists to respond to events. I've > tried buffer the results so there's 20 results before they're sent to > the GUI thread and buffer them so the results are sent every .1 > seconds. Nothing helps. Any advice would be great. > maybe you'ld better ask this question in the wxPython discussion group: wxPython-users at lists.wxwidgets.org cheers, Stef From rafaelv at spress.com.br Mon Jul 30 10:39:50 2007 From: rafaelv at spress.com.br (Rafael Giannetti Viotti) Date: Mon, 30 Jul 2007 11:39:50 -0300 Subject: Subprocess and pipe-fork-exec primitive Message-ID: <46ADF836.8000109@spress.com.br> Hi, I am working with the subprocess.py module in Python 2.4.4 and I am confused about it's functionality. It uses the standard pipe-fork-exec method to start a subprocess: # create pipes pid = fork() if pid == 0: # child exec(...) # parent status = waitpid(pid, 0) 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. I would like to know if this is correct, or am I missing something here? --- Rafael. From aisaac at american.edu Wed Jul 11 08:59:49 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 11 Jul 2007 12:59:49 GMT Subject: bool behavior in Python 3000? In-Reply-To: <1184140795.974059.302830@22g2000hsm.googlegroups.com> References: <5ficp9F3cram2U2@mid.individual.net> <469472f4$0$1293$9b622d9e@news.freenet.de> <1184140795.974059.302830@22g2000hsm.googlegroups.com> Message-ID: <9v4li.8359$MV6.308@trnddc01> Miles wrote: > What boolean operation does '-' represent? Complementation. And as usual, a-b is to be interpreted as a+(-b). In which case the desired behavior is False-True = False+(-True)=False+False = False In response to Stargaming, Steve is making a point about the incoherence of certain arguments, not proposing an implementation. Cheers, Alan Isaac From dhwild at talktalk.net Thu Jul 19 12:07:19 2007 From: dhwild at talktalk.net (David H Wild) Date: Thu, 19 Jul 2007 17:07:19 +0100 Subject: Posted messages not appearing in this group References: <1184742315.618696.202600@z24g2000prh.googlegroups.com> <1184859628.544564.127670@m3g2000hsh.googlegroups.com> Message-ID: <469f92ac$0$1345$834e42db@reader.greatnowhere.com> In article <1184859628.544564.127670 at m3g2000hsh.googlegroups.com>, Adrian Petrescu wrote: > Maybe it has shown up and Google simply isn't showing it yet. Can > anyone confirm that a thread posted yesterday (July 18th, 2007) whose > title was something like "interpreting os.lstat() output" exists or > not? That thread is there, with four postings. -- David Wild using RISC OS on broadband www.davidhwild.me.uk From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Jul 27 09:33:11 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 27 Jul 2007 15:33:11 +0200 Subject: Filtering content of a text file References: <1185528507.750436.91140@j4g2000prf.googlegroups.com> Message-ID: <5guagnF3hehbbU1@mid.individual.net> Ira.Kovac at gmail.com wrote: > I'd greatly appreciate if you can take a look at the task I need > help with. > > It'd be outstanding if someone can provide some sample Python > code. Sure. > CP: An inch of time is an inch of gold but you can't buy that inch > of time with an inch of gold. So, how much gold will I get for an "inch" of time? Regards, Bj?rn -- BOFH excuse #135: You put the disk in upside down. From crobc at BOGUS.sbcglobal.net Sun Jul 29 21:30:22 2007 From: crobc at BOGUS.sbcglobal.net (CC) Date: Sun, 29 Jul 2007 18:30:22 -0700 Subject: Hex editor display - can this be more pythonic? In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Sun, 29 Jul 2007 12:24:56 -0700, CC > declaimed the following in comp.lang.python: >>for c in ln: >> if c in printable: sys.stdout.write(c) >> else: >> sys.stdout.write('\x1B[31m.') >> sys.stdout.write('\x1B[0m') > Be aware that this does require having a terminal that understands > the escape sequences (which, to my understanding, means unusable on a > WinXP console window) Yeah, with this I'm not that concerned about Windows. Though, can WinXP still load the ansi.sys driver? >>Thus, I might display data something like this: >> >>00(\0) 01() FF() 20( ) 34(4) 35(5) 36(6) 08(\b) 38(8) 39(9) 61(a) 62(b) >>63(c) 64(d) 65(e) 7E(~) >> > UGH! :-D Lovely isn't it? > If the original "hex bytes dotted ASCII" side by side isn't > workable, I'd suggest going double line... > > 00 01 FF 20 34 35 36 08 38 39 61 62 63 64 65 7E > nul soh xFF sp 4 5 6 bs 8 9 a b c d e ~ Yeah, something like that is probably nicer. > Use the standard "name" for the control codes (though I shortened > "space" to "sp", and maybe just duplicate the hex for non-named, > non-printable, codes (mostly those in the x80-xFF range, unless you are > NOT using ASCII but something like ISO-Latin-1 I've got a lot to learn about this encoding business. > To allow for the names, means using a field width of four. Using a > line width of 16-data bytes makes for an edit window width of 64, and > you could fit a hex offset at the left of each line to indicate what > part of the file is being worked. Right. Thanks for the reply! -- _____________________ Christopher R. Carlen crobc at bogus-remove-me.sbcglobal.net SuSE 9.1 Linux 2.6.5 From steve at holdenweb.com Mon Jul 2 16:14:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Jul 2007 16:14:41 -0400 Subject: Python compilation ?? In-Reply-To: References: Message-ID: Evan Klitzke wrote: > On 7/2/07, Cathy Murphy wrote: >> Is python a compiler language or interpreted language. If it is interpreter >> , then why do we have to compile it? > > It's an interpreted language. It is compiled into bytecode (not > machine code) the first time a script is run to speed up subsequent > executions of a script. > While the flavor of this answer is correct, in strict point of fact Python *doesn't* compile the scripts it executes, only the modules that are imported. That's why you will occasionally see a very small Python program that just calls functions imported from much larger modules. This avoids spending the time that would otherwise have to be spent recompiling a large script at each execution. 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 Thu Jul 26 20:34:22 2007 From: zyzhu2000 at gmail.com (beginner) Date: Fri, 27 Jul 2007 00:34:22 -0000 Subject: C API -- Two questions Message-ID: <1185496462.855297.21240@57g2000hsv.googlegroups.com> Hi Everyone, I am writing a C extension and encountered two problems. 1) How can I include a description of the arguments? I can include a description string. No problem. But whenever I say help(my_func) it shows the arguments are "... ". However, if a function is defined in python, I will definitely be able to see the parameters when I type help(my_func). 2) How can I make the arguments less picky without writing a lot of type conversion code? My function really needs a tuple as its argument. For example, f( (1,2,3) ) would work. However, in order to make it easy to use, I am thinking that it should be able to take a list too. In other words, I want f( [1,2,3] ) to work also. I can certainly check for the types in the code and deal with each situation. But remember this is tedious to do in C. Is there any better way to handle this? Thanks, cg From jstroud at mbi.ucla.edu Fri Jul 13 19:02:42 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 13 Jul 2007 23:02:42 GMT Subject: Pass by reference or by value? In-Reply-To: References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> Message-ID: Erik Max Francis wrote: > James Stroud wrote: > >> Robert Dailey wrote: >> >>> I noticed in Python all function parameters seem to be passed by >>> reference. This means that when I modify the value of a variable of a >>> function, the value of the variable externally from the function is >>> also modified. >>> >>> Sometimes I wish to work with "copies", in that when I pass in an >>> integer variable into a function, I want the function to be modifying >>> a COPY, not the reference. Is this possible? >> >> >> Not only is this possible, that is actually what happens with ints! > > > But that's because ints are immutable, not because there is an explicit > copy of anything being made. > Yes. I was taking his quotes around "copies" to mean a description of behavior and not implementation. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From donn at u.washington.edu Tue Jul 17 17:44:40 2007 From: donn at u.washington.edu (Donn Cave) Date: Tue, 17 Jul 2007 14:44:40 -0700 Subject: Semantics of file.close() References: <1184628945.314844.53300@k79g2000hse.googlegroups.com> Message-ID: In article , "Evan Klitzke" wrote: ... > > How do I ensure that the close() methods in my finally clause do not > > throw an exception? > You should take a look at the man pages for close(2) and write(2) (not > fclose). Generally you will only get an error in C if you try to close > a file that isn't open. In Python you don't even have to worry about > that -- if you close a regular file object more than once no exception > will be thrown, _unless_ you are using os.close(), which mimics the C > behavior. If you are out of space, in C you will get an error returned > by the call to write (even if the data isn't actually flushed to disk > yet by the kernel). I'm pretty sure Python mimics this behavior, so an > exception would be called on the write, not on the close operation. No, he went to the trouble to test this, and he knows how it works. C library I/O can return a disk full error on close, because the last of the buffer will be flushed with write(2), and Python should raise an exception at this point. I don't think there's any remedy for it, other than the obvious - either always flush, or wrap an explicit close in its own exception handler. Donn Cave, donn at u.washington.edu From mail at microcorp.co.za Fri Jul 6 02:34:55 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 6 Jul 2007 08:34:55 +0200 Subject: Where is the syntax for the dict() constructor ?! References: <468D1D9D.6060002@gmail.com><468D3445.2060408@gmail.com> <1183675552.466967.136360@i13g2000prf.googlegroups.com> Message-ID: <01bf01c7bf99$0f800c60$03000080@hendrik> "John Machin" wrote: > > I don't know what you mean by "requires more than one > character of lookahead" -- any non-Mickey-Mouse implementation of a > csv reader will use a finite state machine with about half-a-dozen > states, and data structures no more complicated than (1) completed > rows received so far (2) completed fields in current row (3) bytes in > current field. When a new input byte arrives, what to do can be > determined based on only that byte and the current state; no look- > ahead into the input stream is required, nor is any look-back into > those data structures. > True. You can even do it more simply - by writing a GetField() that scans for either the delimiter or end of line or end of file, and returns the "field" found, along with the delimiter that caused it to exit, and then writing a GetRecord() that repetitively calls the GetField and assembles the row record until the delimiter returned is either the end of line or the end of file, remembering that the returned field may be empty, and handling the cases based on the delimiter returned when it is. This also makes all the decisions based on the current character read, no lookahead as far as I can see. Also no state variables, no switch statements... Is this the method that you would call "Mickey Mouse"? Actually I lie about the no state variables - you have to keep track of where you are in the file - but calling read(1) will do it for you, so no worries, mate... *wondering if someone will call him on the current row number as state variable* - Hendrik From erexsha at gmail.com Thu Jul 19 17:43:13 2007 From: erexsha at gmail.com (Arash Arfaee) Date: Thu, 19 Jul 2007 14:43:13 -0700 Subject: How to check if an item exist in a nested list Message-ID: <266557d0707191443h36eceddoca7bb626f0e0a022@mail.gmail.com> Hi All, Is there any way to check if an item in specific location in a multiple dimension nested exist? For example something like: if M_list[line][row][d] exist: do_something_0 else: do_something_1 One way is to check the length of each dimension. Does any body know a simpler way? is there any way to check if "IndexError: list index out of range" happened or going to happen and stop program from terminating? Thanks Arash -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Tue Jul 17 16:30:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 17 Jul 2007 16:30:49 -0400 Subject: Implementaion of random.shuffle In-Reply-To: <0Q5ni.28576$C96.18680@newssvr23.news.prodigy.net> References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com> <87d4ys9z46.fsf@mulj.homelinux.net> <1184654645.406393.43250@g12g2000prg.googlegroups.com> <0Q5ni.28576$C96.18680@newssvr23.news.prodigy.net> Message-ID: Josiah Carlson wrote: > shabda raaj wrote: [...] > >> Anyway, is there some test harness we can run to test the robustness >> of shuffle? We can run that test harness for large values and see at >> what point all permutations are not possible or come with unequal >> probability. > > Shuffle works as intended. Your assumptions about it's functionality > are incorrect. Testing will only prove that your assumptions are wrong. > Which is alone a good justification for testing. easier-than-proving-oneself-right-ly y'rs - steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden --------------- 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 Thu Jul 5 19:13:33 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 06 Jul 2007 09:13:33 +1000 Subject: The best platform and editor for Python References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183646799.400176.144570@k79g2000hse.googlegroups.com> <1183655933.475488.157270@m36g2000hse.googlegroups.com> <1183670009.035673.256680@w5g2000hsg.googlegroups.com> Message-ID: On Thu, 05 Jul 2007 14:13:29 -0700, Kay Schluehr wrote: > On Jul 5, 7:18 pm, kimiraikkonen wrote: >> I just wanted a simple answer to my simple question, however topic has >> messed up. Think questioner as a beginner and use more understandable >> terms to help :) >> >> Thanks. > > The problem is simply that the Python community has failed in this > respect. There are many platform dependent and ideology driven ways to > do deal with code editing / debugging but not actually a recommend or > "pythonic" way. What makes you think this is a *problem*? Why is it a failure that Python is perfectly usable with a whole range of editors, debuggers and development styles? > Other than Smalltalk, Python has not created an own > style / identity regarding decent development environments and since > half of the community is happy with Emacs and the other half wants to > program in a VS-like environment, neither consensus nor progress has > to be expected. I don't accept that consensus on editing tools is a good thing, let alone a necessity. Nor that progress is only possible when everybody agrees. To quote from one of my favourite fictional characters, Lord Vetinari: "Pulling together is the aim of despotism and tyranny. Free men pull in all kinds of directions." He smiled, "It's the only way to make progress. That and, of course, moving with the times." -Terry Pratchett, "The Truth" -- Steven. From adonis at REMOVETHISearthlink.net Mon Jul 2 19:07:26 2007 From: adonis at REMOVETHISearthlink.net (Adonis Vargas) Date: Mon, 02 Jul 2007 23:07:26 GMT Subject: How to FTP a ASCII file In-Reply-To: <1183417366.036607.233910@n60g2000hse.googlegroups.com> References: <1183417366.036607.233910@n60g2000hse.googlegroups.com> Message-ID: tedpottel at gmail.com wrote: > Hi, > > My program has the following code to transfer a binary file > > f = open(pathanme+filename,'rb') > print "start transfer" > self.fthHandle.storbinary('STOR '+filename, f) > > How can I do an ASCII file transfer?????? > -Ted > Taken from online documentation: http://docs.python.org/lib/ftp-objects.html storlines(command, file) Store a file in ASCII transfer mode. command should be an appropriate "STOR" command (see storbinary()). Lines are read until EOF from the open file object file using its readline() method to provide the data to be stored. Hope this helps. Adonis From walterbyrd at iname.com Wed Jul 25 16:51:47 2007 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 25 Jul 2007 13:51:47 -0700 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185394252.064429.258950@d55g2000hsg.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> <1185394252.064429.258950@d55g2000hsg.googlegroups.com> Message-ID: <1185396707.593255.9410@g12g2000prg.googlegroups.com> On Jul 25, 2:10 pm, Jeff wrote: > I can tell you exactly why PHP > is so popular: it acts as an extension of HTML and is syntactically > similar to Perl. > Although, that can lead to problems, if you're not careful: Perl: my $x = 5 + 9000 || 1; # $x is 9005 PHP: $x = 5 + 9000 || 1; # $x is 6... From steve at holdenweb.com Sat Jul 21 09:02:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 21 Jul 2007 09:02:43 -0400 Subject: PEP 3107 and stronger typing (note: probably a newbie question) In-Reply-To: <7xbqe7ox9n.fsf@ruckus.brouhaha.com> References: <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <7x8x9lwka9.fsf@ruckus.brouhaha.com> <7xbqe7ox9n.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steve Holden writes: >> The issue I have with correctness proofs (at least as they were >> presented in the 1980s - for all I know the claims may have become >> more realistic now) is that the proof of correctness can only relate >> to some highly-formal specification so complex that it's only >> comprehensible to computer scientists. > > Just like software as it is now, is only comprehensible to > programmers. A long while back there was a language called COBOL > designed to be comprehensible to non-programmers, and it actually did > catch on, but it was cumbersome and limited even in its time and in > its application era, not so readable to non-programmers after all, and > is not used much in new projects nowadays. > The trouble there, though, is that although COBOL was comprehensible (to a degree) relatively few people have the rigor of thought necessary to construct, or even understand, an algorithm of any kind. >> In other words, we can never "prove" that a program does what the >> customer wants, because the semantics are communicated in different >> ways, involving a translation which, since it is necessarily performed >> by humans using natural language, will always be incomplete at best >> and inaccurate at worst. > > The types of things one tries to prove are similar to what is less > formally expressed as localized test cases in traditional software. > E.g. for a sorting routine you'd want to prove that output[n+1] >= > output[n] for all n and for all inputs. As the Intel FDIV bug > incident reminds us, even billions of test inputs are not enough to > show that the routine does the right thing for EVERY input. Well I can buy that as a reasonable answer to my point. The early claims of the formal proof crowd were somewhat overblown and unrealistic, but that certainly doesn't negate the value of proofs such as the one you describe. 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 musiccomposition at gmail.com Tue Jul 24 14:50:13 2007 From: musiccomposition at gmail.com (Benjamin) Date: Tue, 24 Jul 2007 18:50:13 -0000 Subject: Any python module for Traversing HTML files In-Reply-To: <1185297135.542235.55290@r34g2000hsd.googlegroups.com> References: <1185297135.542235.55290@r34g2000hsd.googlegroups.com> Message-ID: <1185303013.809931.211600@q75g2000hsh.googlegroups.com> On Jul 24, 12:12 pm, johnny wrote: > Any python module for navigating and selecting, parsing HTML files? htmlparse From exarkun at divmod.com Mon Jul 30 09:56:37 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 30 Jul 2007 09:56:37 -0400 Subject: Detecting __future__ features In-Reply-To: <5h68ggF3idk61U1@mid.uni-berlin.de> Message-ID: <20070730135637.4947.357418669.divmod.quotient.16643@ohm> On Mon, 30 Jul 2007 15:48:00 +0200, "Diez B. Roggisch" wrote: >Neil Cerutti wrote: > >> On 2007-07-30, Andr? wrote: >>> On Jul 30, 9:39 am, Neil Cerutti wrote: >>>> I don't understand the qualification, "at runtime," you're >>>> making. What's wrong with just importing what you want and >>>> using it? If it's already been enabled, no harm will come from >>>> the import statement. >>>> >>> >>> I'm not the OP, so perhaps I am missing his intent. However, I >>> can see a good reason for asking this question. >>> >>> I seem to recall that the "from __future__ import" statement >>> can only be done at the beginning of a script. What if you are >>> designing a module meant to be imported, and used by other >>> programs over which you have no control? You can't use "from >>> __future__ import" in your module. So, you may have to find a >>> way to figure out what's been done. (the example given with >>> the division operator is a good one). >> >> Is "from __future__ import" really that lame? > >Well, if you consider it lame, how about you being a 7331 haX0r who tells us >how python is going to handle this then: > >def foo(): > yield 1 > >if random_condition(): > from __future__ import generators > >def bar(): > yield 2 > >The point is that from __future__ can massively alter the behavior of the >parser - accepting keywords that otherwise won't be keywords, as in this >example, and many more. > >Making the switch between different parser-implementations on the fly isn't >technically impossible - but really, really, really complicated. But then, >if it's lameness sucks so much, you might wanna take a stab at it? > I think you misunderstood the behavior which was being called lame. The earlier poster was suggesting that only the first Python code to run any where in a process could perform future imports. This is, of course, not true. It's only restricted to the first Python code to run in a particular file. Jean-Paul From michael at stroeder.com Tue Jul 24 18:57:31 2007 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Wed, 25 Jul 2007 00:57:31 +0200 Subject: ANN: python-ldap-2.3.1 Message-ID: Find a new release of python-ldap: http://python-ldap.sourceforge.net/ python-ldap provides an object-oriented API to access LDAP directory servers from Python programs. It mainly wraps the OpenLDAP 2.x libs for that purpose. Additionally it contains modules for other LDAP-related stuff (e.g. processing LDIF, LDAPURLs and LDAPv3 schema). ---------------------------------------------------------------- Released 2.3.1 2007-07-25 Changes since 2.3.0: * Support for setuptools (building .egg, thanks to Torsten) * Support for matched values control (RFC 3876, thanks to Andreas) Lib/ * Fixed ldif (see SF#1709111, thanks to Dmitry) * ldap.schema.models: SUP now separated by $ (method __str__() of classes AttributeType, ObjectClass and DITStructureRule, thanks to Stefan) Modules/ * Added constant MOD_INCREMENT to support modify+increment extension (see RFC 4525, thanks to Andreas) From stargaming at gmail.com Thu Jul 26 10:15:51 2007 From: stargaming at gmail.com (Stargaming) Date: 26 Jul 2007 14:15:51 GMT Subject: Scope PyQt question References: <1185457304.755050.308530@z24g2000prh.googlegroups.com> Message-ID: <46a8ac97$0$14317$9b622d9e@news.freenet.de> On Thu, 26 Jul 2007 06:41:44 -0700, dittonamed wrote: > Code pasted below -----> > > Can anyone out there suggest a way to access the object "p" thats > started in playAudio() from inside the stopAudio()? I need the object > reference to use QProcess.kill() on it. The code sample is below. Thanks > to anyone who helps out =) > > More comments in the code below ------> > > > from qt import * > > class Form2(QMainWindow): > def __init__(self,parent = None,name = None,fl = 0): > QMainWindow.__init__(self,parent,name,fl) self.statusBar() > > def playAudio(self): > p = QProcess(self, 'player') > playcmd = '/usr/bin/play' > filename = 'song.ogg' > p.addArgument(playcmd) > p.addArgument(filename) > p.start() > > def stopAudio(self): > ''' #This is just to show that i can "see" the object, though > i > #dont know how to "access" it > #the output shows the QProcess object by name... # but how do > i reference it?? > allobjs = list(QObject.objectTrees()) for obj in allobjs: > objName = QObject.name(obj) > if objName == 'Form2': > print QObject.children(obj) > ''' > > QProcess.kill(NEED THE REFERENCE HERE) Answering from a non-Qt point of view (ie. I don't know if there were cleaner ways using Qt stuff), you have to bind p somewhere not local to the function. Any attribute of `self` (that's hopefully not used by QMainWindow) should be fine. From arkanes at gmail.com Mon Jul 16 11:35:57 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 16 Jul 2007 10:35:57 -0500 Subject: How to determine which method was used in an inheritance heirarchy? In-Reply-To: <865D7C6C-F76B-46F0-9E4C-848E896A1627@myemma.com> References: <1184559788.712146.238190@q75g2000hsh.googlegroups.com> <1184565220.674041.270790@o61g2000hsh.googlegroups.com> <4BC3DC93-5F57-4B24-BE82-EB2D5FD679AF@myemma.com> <865D7C6C-F76B-46F0-9E4C-848E896A1627@myemma.com> Message-ID: <4866bea60707160835w5c64ec50pc8774592768b2b82@mail.gmail.com> On 7/16/07, Erik Jones wrote: > On Jul 16, 2007, at 3:37 AM, Gabriel Genellina wrote: > > > En Mon, 16 Jul 2007 03:56:18 -0300, Erik Jones > > escribi?: > > > >> Perhaps an even better example of what I'm trying to do would be in > >> order (this is minus any exception handling): > >> > >> import sys > >> > >> def mytrace(frame, event, arg): > >> if event == 'call': > >> func_name = frame.f_code.co_name > >> > >> if func_name in frame.f_locals['self'].__class__.__dict__: > >> print frame.f_locals['self'].__class__.__name__ > >> else: > >> for base in frame.f_locals['self'].__class__.__bases__: > >> if func_name in base.__dict__: > >> print base.__name__ > >> break > >> > >> > >> class A(object): > >> def __init__(self): > >> pass > >> > >> class B(A): > >> def __init__(self): > >> A.__init__(self) > >> > >> sys.settrace(mytrace) > >> B() > >> > >> This will output: > >> > >> B > >> B > > > > If you don't mind post-processing the results, you can log the > > function > > name and source module (from frame.f_code.co_name and co_filename) and > > current line number (frame.f_lineno). Later, obtaining the class > > name from > > those is a bit tricky (and not even the inspect module does it > > right), but > > perhaps using the tokenizer module, watching for lines that contain > > "class" is enough. > > > I was afraid of that. I used pretty much that tokenizer trick for a > unit test generator I wrote in php a while back and felt like that > was pretty clunky then. > Hacky, but maybe this will work: import sys import inspect def mytrace(frame, event, arg): if event == 'call': func_name = frame.f_code.co_name klassOb = frame.f_locals['self'].__class__ for klass in inspect.getmro(klassOb): cf = klass.__dict__.get(func_name) if hasattr(cf, "func_code") and cf.func_code == frame.f_code: print klass.__name__ class A(object): def __init__(self): pass class B(A): def __init__(self): A.__init__(self) sys.settrace(mytrace) B() From martin at see.sig.for.address Sun Jul 1 12:37:36 2007 From: martin at see.sig.for.address (Martin Gregorie) Date: Sun, 01 Jul 2007 17:37:36 +0100 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <20070625133843.9e25d0ab.steveo@eircom.net> <82b5l4-tvh.ln1@zoogz.gregorie.org> <7xbqf3lc7i.fsf@ruckus.brouhaha.com> <70c7l4-2gp.ln1@zoogz.gregorie.org> Message-ID: Roedy Green wrote: > On Tue, 26 Jun 2007 13:04:50 +0100, Martin Gregorie > wrote, quoted or indirectly quoted > someone who said : > >> TAI? Care to provide a reference? > > see http://mindprod.com/jgloss/tai.html > Thanks. Your list of NTP servers on http://mindprod.com/jgloss/timesources.html may be a bit out of date: I notice that it doesn't include the European or Oceania time server pools (0.europe.pool.ntp.org, 0.oceania.pool.ntp.org). It may be best to just hold a link to the NTP project servers page, http://support.ntp.org/bin/view/Servers/WebHome -- martin@ | Martin Gregorie gregorie. | Essex, UK org | From p at ulmcnett.com Sun Jul 22 14:02:48 2007 From: p at ulmcnett.com (Paul McNett) Date: Sun, 22 Jul 2007 11:02:48 -0700 Subject: Advice on sending images to clients over network In-Reply-To: <7xlkd8mktt.fsf@ruckus.brouhaha.com> References: <1185095666.627415.108450@w3g2000hsg.googlegroups.com> <7xlkd8mktt.fsf@ruckus.brouhaha.com> Message-ID: <46A39BC8.6030106@ulmcnett.com> Paul Rubin wrote: > Frank Millman writes: >> Any suggestions will be much appreciated. > > Why on earth don't you write the whole thing as a web app instead of > a special protocol? Then just use normal html tags to put images > into the relevant pages. I believe he has a full desktop client app, not a web app. Believe it or not, there's still a solid place for desktop applications even in this ever-increasing webified world. Use the right tool for the job... -- pkm ~ http://paulmcnett.com From horpner at yahoo.com Mon Jul 30 08:39:51 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 30 Jul 2007 12:39:51 GMT Subject: Detecting __future__ features References: Message-ID: On 2007-07-30, Steven D'Aprano wrote: > How would one tell at runtime if a particular feature has been > enabled by the "from __future__ import thing" statement? I don't understand the qualification, "at runtime," you're making. What's wrong with just importing what you want and using it? If it's already been enabled, no harm will come from the import statement. -- Neil Cerutti Will the highways on the Internet become more few? --George W. Bush From kelvie at ieee.org Thu Jul 5 20:20:17 2007 From: kelvie at ieee.org (Kelvie Wong) Date: Thu, 5 Jul 2007 17:20:17 -0700 Subject: None returned? In-Reply-To: <1183677572.648960.49070@m37g2000prh.googlegroups.com> References: <1183677572.648960.49070@m37g2000prh.googlegroups.com> Message-ID: <94ccbe710707051720m723f381exed9e18f0fa288bc9@mail.gmail.com> On 7/5/07, robinsiebler at gmail.com wrote: > I can't figure out -what- is going wrong here. When the code reaches > the 'return' line, there is data to be returned, but when it exits out > to the calling function, 'None' is returned! > > import mx.DateTime > > def get_weeks(weeks, year, dates, date_list={}): > if dates.has_key(year): > date_list[year] = dates[year].keys()[-weeks:] > if len(dates[year].keys()) >= weeks: > return date_list > else: > weeks = weeks - len(dates[year].keys()) Right here. > get_weeks(weeks, str(int(year) -1), dates, date_list) You have to change that line to: return get_weeks(weeks, str(int(year) -1), dates, date_list) Otherwise, if len(dates[year.keys()) < weeks, it doesn't return anything. > > def get_report_dates(weeks, dates): > today = mx.DateTime.now() > this_week = today.iso_week[1] > rpt_dates = get_weeks(weeks, str(today.year), dates) > print rpt_dates > > def main(): > > dates = {'2006': {'50': [50, 'This is the 50th week'], > '51': [51, 'This is the 51st week'], > '52': [52, 'This is the 52nd week']}, > '2007': {'25': [1, 'This is the 1st week'], > '26': [2, 'This is the 2nd week'], > '27': [3, 'This is the 3rd week'], > '28': [4, 'This is the 4th week'], > '29': [5, 'This is the 5th week']}} > > get_report_dates(6, dates) > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Kelvie From rcdailey at gmail.com Fri Jul 6 12:47:19 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 06 Jul 2007 16:47:19 -0000 Subject: Expandable 2D Dictionaries? In-Reply-To: References: <1183736635.415927.208450@57g2000hsv.googlegroups.com> Message-ID: <1183740439.709410.220810@q75g2000hsh.googlegroups.com> Thank you all very much for your valuable replies. I wasn't aware that tuples were valid keys in a dictionary object. This is actually the solution I was looking for. Thank you all once again. From deets at nospam.web.de Wed Jul 25 14:25:43 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 25 Jul 2007 20:25:43 +0200 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185385374.866372.198520@x35g2000prf.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> Message-ID: <5gpit9F3gajh0U1@mid.uni-berlin.de> > Before you can even get started with Python web-development, you have > to understand this entire alphabit soup of: CGI, FASTCGI, MOD_PYTHON, > FLUP, WSGI, PASTE, etc. For me, configuring fastcgi has been the most > difficult part of getting django to work. PHP developers don't have to > bother with anything like that. With PHP, you just throw some code in > the middle of your html file. Which is simply because they are preconfigured. If you have ever tried to recompile a PHP installation because it misses e.g. oracle support. > Also, PHP, and PHP frameworks, are supported everywhere. If you going > to use a PHP MVC framework, like codeignitor, you would have a hard > time finding a hoster that didn't support it - all you need is php4 > and mysql. Dollar-hosting, for $10 a year, should work just fine with > codeignitor. With codeignitor, just copy your files to whatever host, > and that's it, you're done. > > By contrast, the most popular Python frameworks have sky-high system > requirements. Take a look at the requirements and/or recomendations > for popular Python frameworks like Django, TurboGears, or CherryPy: > Apache 2.0, mod_python (latest version), fastcgi (at least), command > line access, PostgreSQL. And a lot of low-cost hosters don't support > Python at all. > > Don't get me wrong: I am not saying that PHP is better than Python for > web-development. But, I sometimes think that Python could learn a few > things from PHP. I don't see that amongst the above is anything that python could learn. Using turbogears, a simple tg-admin quickstart followed by a ./start-.py is all you need. The templating system is simple, allows for embedded python (to some extend, and a healthy one), database-support & model-stuff is easy. The cheap hosting and preconfigured apache setups are things that only the market can solve. Diez From p at ulmcnett.com Wed Jul 25 16:07:16 2007 From: p at ulmcnett.com (Paul McNett) Date: Wed, 25 Jul 2007 13:07:16 -0700 Subject: Why PHP is so much more popular for web-development In-Reply-To: <46A7942D.4030904@holdenweb.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <46A7942D.4030904@holdenweb.com> Message-ID: <46A7AD74.1030007@ulmcnett.com> Steve Holden wrote: > When someone starts to push the limits of PHP they either continue to > push until they get where they want to be (producing an ugly or > ill-maintained bunch of code along the way) or they choose a more > appropriate tool. > > The latter behavior is typical of programmers. The former is typical of > typical users. There are many people producing web sites who I wouldn't > let within yards of any of my code. but it's some kind of tribute to PHP > that it manages to satisfy so many of them. This doesn't mean that > grafting PHP features into Python mindlessly will improve the language. > > The Python approach is a scalpel, which can easily cut your fingers off. > The PHP approach is a shovel, which will do for many everyday tasks. Exactly right on. I actually use PHP quite a bit. For websites that would otherwise be static html pages other than the fact that I want to reuse elements (header, footer, etc.), I choose PHP in a heartbeat, because it's easy, and I'm lazy. Ditto if it is a simple db-driven site. Start adding business rules and complex program flow and I run away from PHP as fast as I can. I wouldn't want to actually code anything in it, after all. ;) I've seen comments that mod_python is hard to use, but I just haven't found that to be the case. For me, mod_python is the next step up when PHP no longer suits my needs. Granted, I'm spoiled because I run my own server and don't rely on some hosting provider to tell me what I can and cannot do. :) -- pkm ~ http://paulmcnett.com From steve at holdenweb.com Thu Jul 26 15:37:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Jul 2007 15:37:17 -0400 Subject: removing items from a dictionary ? In-Reply-To: <46A8EFF5.4060600@mailbox.kun.nl> References: <46A8EFF5.4060600@mailbox.kun.nl> Message-ID: Stef Mientki wrote: > hello, > > I want to remove some items from a dictionary, > so I would expect this should work: > > Nets = {} > ... fill the dictionary Nets > > for net in Nets: > if net.upper() in Eagle_Power_Nets : > del Nets [ net ] > > > But it gives me > Message File Name Line Position > Traceback > ? D:\data_to_test\JALsPy\Eagle_import.py 380 > RuntimeError: dictionary changed size during iteration > > > Now I can solve this problem in the following way > > power_nets = [] > for net in Nets: > if net.upper() in Eagle_Power_Nets : > power_nets.append ( net ) > > # remove power nets from netlist > for net in power_nets: > del Nets [ net ] > > > But I wonder if this is the best way to manipulate a dictionary, > because I've to do more "complex" operations on the dictionary, > like joining items, > I would like to have a better understanding of what can and what can't be done. > Well, modifying *any* structure as you iterate over it runs the same risks as sawing through the tree branch you are sitting on. Since it isn't practical to iterate over Eagle_Power_Nets and test for presence in your Nets dict, you have to iterate over at least the keys of Nets. You could just iterate over the keys rather than the whole table, though: for net in Nets.keys(): # Nets.iterkeys() would avoid building the list # but that runs the same risks as your original if net.upper() in in Eagle_Power_Nets : del Nets[net] Watch that spacing, by the way: Python is easy to keep readable if you follow the style guidelines of PEP 8. 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 http Tue Jul 3 02:15:53 2007 From: http (Paul Rubin) Date: 02 Jul 2007 23:15:53 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com> <5dveb4F360un0U1@mid.individual.net> <467a9209$0$22165$426a74cc@news.free.fr> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> Message-ID: <7xd4za1086.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > I do have (some of:-) that experience, and am reasonably at ease in > Haskell (except when it comes to coding monads, which I confess I still > have trouble wrapping my head around). I recently found the article http://en.wikibooks.org/wiki/Haskell/Category_theory which had (for me anyway) a far more comprehensible explanation of monads than anything I ever saw about Haskell programming. Don't be scared by the title--the article is very readable. It's much clearer than many Haskell tutorials I've seen, whose monad explanations simply wouldn't fit in my mind, with weird analogies about robots handling nuclear waste in containers moving around on conveyor belts, etc. I think right now I could write an explanation of monads understandable by any well-versed Python programmer (it would be based on showing the parallels between Python's list type and Haskell's List monad, then moving onto sequencing with the Maybe monad, instead of trying to start by explaining Haskell I/O), so maybe I'll try to do that sometime. > Eckel's and Martin's well-known essays on why good testing can replace > strict static type checking: > > Those are pretty unpersuasive since they're based on Java and C++. Eckel's example would have been much easier in Haskell, I think. Did you look at Tim Sweeney's presentation "The Next Mainstream Programming Language: A Game Developer's Perspective"? I wonder what you thought of it. It's here: Powerpoint version: http://www.cs.princeton.edu/~dpw/popl/06/Tim-POPL.ppt PDF version: http://www.st.cs.uni-sb.de/edu/seminare/2005/advanced-fp/docs/sweeny.pdf He advocates a mixed functional/procedural language with even fancier static types than Haskell. > Me, I'm always worried about significant code revision _unless I have > good tests in place_. Strict static typechecks catch only a small > subset of frequent mistakes -- good tests catch a far higher quota. It seems to me that the typecheck is sort of like a test that the compiler provides for you automatically. You still have to write tests of your own, but not as many. Also, Python-style unit tests usually are written for fairly small pieces of code. They usually don't manage to cover every way that data can flow through a program. E.g. your program might pass its test and run properly for years before some weird piece of input data causes some regexp to not quite work. It then hands None to some function that expects a string, and the program crashes with a runtime type error. Static typechecking makes sure that a function expecting a string can never ever receive None. I also sometimes have trouble figuring out how to write useful tests, though maybe there's some understanding that I haven't yet grokked. However, a lot of my programs crawl the filesystem, retrieve things over the web, etc. It's hard to make any meaningful tests self-contained. Last week I needed to write a 20-line Python function that used os.walk to find all filenames of a certain format in a certain directory tree and bundle them up in a particular way. The main debugging hassle was properly understanding the output format of os.walk. A static type signature for os.walk, checked against my program, would have taken care of that immediately. Once I got the function to work, I deployed it without writing permanent tests for it. An actual self-contained test would have required making some subdirectories with the right layout before running the function. Writing a test script that really did that would have taken 10x as long as writing the function took, and such a complex test would have needed its own tests (I'd have probably used something like dejagnu). For functions that simply transform data, I've been enjoying using doctest, but for functions like the above os.walk thing, I'm not sure what to do. I'd be happy to receive advice, of course. > Typechecks do catch some mistakes "faster", but, in my experience on > today's machines, that tiny difference is becoming insignificant, > particularly when you consider that typechecks typically require > whole-program analysis while, as Van Roy and Haridi point out, dynamic > typing affords "totally open coding". I don't know if this holds in Haskell, but at least in C, the compiler could usually find several errors in one pass, while dynamic types often mean running the program, seeing some function crash from getting None instead of a string, figuring out and fixing the error, running again, getting a similar crash in a different place, and repeating all the above several times. Lately I've been looking at a somewhat highbrow book on programming language theory: http://www.cs.cmu.edu/~rwh/plbook/book.pdf I don't understand that much of it, but the parts I can make any sense of are giving me a better picture of what PL designers these days think about. It's really nothing like how it was in the 1970's. From bignose+hates-spam at benfinney.id.au Tue Jul 24 19:07:56 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 25 Jul 2007 09:07:56 +1000 Subject: code indentation References: <1185297657.186852.136950@k79g2000hse.googlegroups.com> Message-ID: <87lkd5jt83.fsf@benfinney.id.au> Steve Holden writes: > vedrandekovic at v-programs.com wrote: > > On 24 srp, 05:20, "Gabriel Genellina" wrote: > >> En Mon, 23 Jul 2007 16:53:01 -0300, ...:::JA:::... > >> escribi?: > >>> So......how can I do this????????????? > >>> I will appreciate any help!!!!! > >> Try with a simple example. Let's say you want to convert this: > >> [...] > > [...] Can you give me some example script of this? Please!!! > > > > PS: THANKS FOR YOUR TIME!!!!!!!!!! > > It's unfortunate that you are having difficulty with two languages > simultaneously: your command of English, though impressive, appears > to be insufficient for you to explain the problem [...] And while we're on the topic of communication: The original poster would do well to learn that increasing the number of consecutive punctuation marks (!!!, ???) is a sure way to turn away many people who would otherwise be helpful. Sentences need at most one '!' or '?', adding more does not improve the chances of being taken seriously. -- \ "We have to go forth and crush every world view that doesn't | `\ believe in tolerance and free speech." -- David Brin | _o__) | Ben Finney From jeffober at gmail.com Wed Jul 25 15:31:12 2007 From: jeffober at gmail.com (Jeff) Date: Wed, 25 Jul 2007 19:31:12 -0000 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: <1185387918.702268.54360@l70g2000hse.googlegroups.com> References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> <1185379218.286977.124040@19g2000hsx.googlegroups.com> <1185384306.104549.287510@19g2000hsx.googlegroups.com> <1185384793.577650.256310@d55g2000hsg.googlegroups.com> <1185387918.702268.54360@l70g2000hse.googlegroups.com> Message-ID: <1185391872.161900.192610@19g2000hsx.googlegroups.com> Sorry about that. Hopefully, this should work ;) def flatten(obj): if type(obj) not in (list, tuple, str): raise TypeError("String, list, or tuple expected in flatten().") if len(obj) == 1: if type(obj[0]) in (tuple, list): return flatten(obj[0]) else: return [obj[0]] else: if type(obj[0]) in (list, tuple): return flatten(obj[0]) + flatten(obj[1:]) else: return [obj[0]] + flatten(obj[1:]) x = (1, 2, [3, 4, (5, 6)]) y = ([1, 2, (3, 4)], 5, 6) z = (1, [2, 3, (4, 5)], 6) print flatten(x) print flatten(y) print flatten(z) From mail at gedankenkonstrukt.de Mon Jul 9 16:02:50 2007 From: mail at gedankenkonstrukt.de (Thomas Wittek) Date: Mon, 09 Jul 2007 22:02:50 +0200 Subject: Distributing python apps In-Reply-To: <1184011164.346200.9330@q75g2000hsh.googlegroups.com> References: <1184011164.346200.9330@q75g2000hsh.googlegroups.com> Message-ID: Robert Dailey schrieb: > Ideally, I would like for someone to be able to use my tools without > having to install Python. What about http://www.py2exe.org/ ? "py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation." -- Thomas Wittek http://gedankenkonstrukt.de/ Jabber: streawkceur at jabber.i-pobox.net From andre.roberge at gmail.com Thu Jul 12 23:07:23 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: Fri, 13 Jul 2007 03:07:23 -0000 Subject: Crunchy release 0.9.1 Message-ID: <1184296043.699376.38520@57g2000hsv.googlegroups.com> Crunchy 0.9.1 has been released. It is available at http://code.google.com/p/crunchy Note that, if you have downloaded version 0.9 or version 0.9.0.1 you likely will not need to download this latest version. What is new since version 0.9? * Possibility to log selectively part of a session (as instructed by a tutorial *writer* such as a teacher who may want to evaluate students). This experimental feature is the main reason to have a new release and is of potential interest for Python instructors/teachers. * Bug fix (0.9.0.1): Output containing <....> was not displayed in version 0.9 * Support for generation of image files is now done through threads (rather than subprocess) and addition of a "load image" button, which prevents from having to generate the image twice. * A windows installer version is available. * Minor experimental cosmetic additions. * Improved "readme" file. Bug reports, comments and suggestions are always welcome. Andr?, for the Crunchy team. ====================== What is Crunchy? Crunchy is a an application that transforms html Python tutorials into interactive session viewed within a browser. We are not aware of any other application (in any language) similar to Crunchy. Currently Crunchy has only been fully tested with Firefox; we know that some browsers simply don't work with it. Crunchy should work with all operating systems - it has been tested fairly extensively on Linux, Windows and Mac OS. What is new since a few months ago? Crunchy has been rewritten from scratch from the previous version (0.8.2), to use a custom plugin architecture. This makes easier to extend and add new functionality. Rather than list the differences with the old release, it is easier to list the essential features of this new version. 1. Crunchy can work best with specially marked-up html tutorials. However, it can now work with any html tutorials - including the official Python tutorial on the python.org site. Html pages can be loaded locally or remotely from anywhere on the Internet. Crunchy uses a combination of Elementtree and BeautifulSoup to process html pages. Non W3C-compliant pages can be handled, but the visual appearance is not guaranteed to reproduce that normally seen using a browser. 2. Crunchy can insert a number of Python interpreters inside a web page. In the default mode, it does that whenever it encounters an html
     element which is assumed to contain some Python code.
    These interpreters can either share a common environment (e.g. modules
    imported in one of them are known in the other) or be isolated one
    from another.
    
    3. Crunchy adds automatic css styling to the Python code -  you can
    look at the official Python tutorial using your browser (all Python
    code in blue) and compare with what Crunchy displays to give you a
    good idea.
    
    4. Instead of inserting an interpreter, Crunchy can insert a code
    editor that can be used to modify the Python code on the page and
    execute it.  The editor can be toggled to become a fairly decent
    syntax aware editor that can save and load files.
    
    5. Crunchy has a "doctest" feature where the code inside the 
     is
    taken to be the result
    of an interpreter session and the user has to write the code so as to
    make the interpreter session valid; this is useful in a teaching
    environment. Messages from the Crunchy's doctest are "friendlier" for
    Python beginners than the usual tracebacks.
    
    6. Crunchy has a small graphics library that can be imported, either
    inside an editor or an interpreter, to produce simple graphics (even
    animations!) inside the browser.
    
    7. For the user that needs better quality graphics, Crunchy supports
    programs (such as matplotlib) that can create image files; by
    executing the code, the image produced is loaded inside the browser
    window.  In this capacity, Crunchy could be used as a front end for
    libraries such as matplotlib.
    
    8. Crunchy supports code execution of files as separate processes,
    making it suitable to launch gui based application from the browser
    window.
    
    9. Crunchy's interpreter has an interactive "help" feature like many
    python-aware IDEs.
    
    10. Crunchy includes a fairly comprehensive tutorial on its own use,
    as well as a reference for tutorial writers that want to make their
    tutorials "crunchy-friendlier".
    
    11. As a security feature, crunchy strips all pre-existing javascript
    code from an html page before displaying it inside the browser window.
    
    
    
    From george.sakkis at gmail.com  Thu Jul 19 12:34:39 2007
    From: george.sakkis at gmail.com (George Sakkis)
    Date: Thu, 19 Jul 2007 16:34:39 -0000
    Subject: Posted messages not appearing in this group
    In-Reply-To: 
    References: <1184742315.618696.202600@z24g2000prh.googlegroups.com>
    	
    Message-ID: <1184862879.451366.322400@22g2000hsm.googlegroups.com>
    
    On Jul 18, 6:50 am, Alex Popescu 
    wrote:
    > Sanjay  gmail.com> writes:
    >
    >
    >
    > > Hi All,
    >
    > > I tried posting in this group twice since last week, but the messages
    > > did not appear in the forum. Don't know why. Trying this message
    > > again...
    >
    > > Sanjay
    >
    > Something similar seemed to happen to me too, but when checking with gmane I've
    > noticed that all my posts got in (and now I am trying to figure out how can I
    > apologize for multiple posts :-) ).
    
    Same here, my last three posts haven't appeared (yet) at the google
    group but they show up on the mailing list:
    http://mail.python.org/pipermail/python-list/2007-July/thread.html
    
    George
    
    
    
    From mail at microcorp.co.za  Thu Jul 12 02:17:07 2007
    From: mail at microcorp.co.za (Hendrik van Rooyen)
    Date: Thu, 12 Jul 2007 08:17:07 +0200
    Subject: Tuple vs List: Whats the difference?
    References: <1184177195.569916.184770@22g2000hsm.googlegroups.com>
    Message-ID: <000801c7c47a$f8255980$03000080@hendrik>
    
    "Shafik"  wrote:
    
    
    > Hello folks,
    > 
    > I am an experienced programmer, but very new to python (2 days). I
    > wanted to ask: what exactly is the difference between a tuple and a
    > list? I'm sure there are some, but I can't seem to find a situation
    > where I can use one but not the other.
    
    Welcome to Python.
    
    >From a practical point of view, use lists - you will get exceptions
    if you use a list where a tuple is required, such as a key in a dict,
    and other more obscure cases.
    
    The philosophical differences - "tuple as struct" vs "list as collection"
    argument, makes no practical difference - you can use a list in the same 
    structured way if you want, and lists have more nice methods as they 
    are not immutable as tuples are.
    
    Google this Group for "Index" to see some flame wars.
    
    hth - Hendrik
    
    
    
    From battosaimykle at gmail.com  Fri Jul 27 04:24:02 2007
    From: battosaimykle at gmail.com (Mykle)
    Date: Fri, 27 Jul 2007 08:24:02 -0000
    Subject: Problem with authentification
    Message-ID: <1185524642.187235.245110@19g2000hsx.googlegroups.com>
    
    Hi, I'm french so I apologize for mistakes I'm about to make in
    english...
    
    I installed Paramiko on a Debian Server for making connections with an
    SSH
    Server and here's my issue:
    
    I create a transport connection with the server for getting files from
    it.
    The server asks an authentification but the public key is kept by the
    SSH
    Server and recognize the computer by his public key username at
    computername,
    the server have a username for the public key. There's no password
    anyway !
    Until now, I use a bash script which make an ssh connection with the
    Server
    (like 'ssh -x -a username at sshadress'), but I want to change that
    for some
    verification reasons. I mustn't have to put any key in the code...
    What I
    want is to connect to the Server and that this one accept this
    connection by
    only the recognization of the username at computername. The
    documentation
    doesn't really help me and I'm not pretty much good in Python (maybe
    that
    explains why I'm writing this mail...*sic*).
    
    Here's the begining of my code:
    
    import paramiko
    TR = paramiko.Transport((sshAdress,22))
    ...
    
    ... Yeah I know, it's like there was nothing...
    
    Thank you for your help.
    
    Michael.
    
    
    
    From thermostat at gmail.com  Thu Jul  5 15:14:07 2007
    From: thermostat at gmail.com (Dan)
    Date: Thu, 05 Jul 2007 19:14:07 -0000
    Subject: Callback scoping
    Message-ID: <1183662847.449011.26560@o61g2000hsh.googlegroups.com>
    
    So, I think I understand what python's scoping is doing in the
    following situation:
    >>> x = [ lambda: ind for ind in range(10) ]
    >>> x
    [ at 0x00BEC070>,  at 0x00BEC7F0>,
     at 0x00BECA70>,  at 0x00C1EBF0>,
     at 0x00C1EE30>,  at 0x00C228F0>,
     at 0x00C228B0>,  at 0x00C28730>,
     at 0x00C286F0>,  at 0x00C287F0>]
    >>> x[0]()
    9
    >>> x[5]()
    9
    >>> x[9]()
    9
    >>> ind
    9
    >>> ind = 2
    >>> x[0]()
    2
    >>>
    
    But, I'm wondering what is the easiest (and/or most pythonic) way to
    get the behavior I want? (If you haven't guessed, I want a list of (no
    parameter) functions, each of which returns its index in the list.)
    
    -Dan
    
    
    
    From murali.dhanakoti at gmail.com  Fri Jul 20 09:06:16 2007
    From: murali.dhanakoti at gmail.com (Murali)
    Date: Fri, 20 Jul 2007 13:06:16 -0000
    Subject: Interprocess communication woes
    In-Reply-To: 
    References: <1184810559.180382.179220@j4g2000prf.googlegroups.com>
    	
    Message-ID: <1184936776.889692.279710@m3g2000hsh.googlegroups.com>
    
    On Jul 19, 4:30 am, Nick Craig-Wood  wrote:
    > Murali  wrote:
    > >  After some investigation, I found out that this problem had nothing to
    > >  do with my GUI app not getting refreshed and I was able to reproduce
    > >  this problem with normal python scripts. Here is one such script
    >
    > >  #File test.py
    > >  from subprocess import Popen
    > >  from subprocess import PIPE
    > >  import sys
    > >  if __name__ == '__main__':
    > >   prog = sys.argv[1]
    > >   proc = Popen(prog, shell = True, stdout = PIPE, bufsize = 0)
    > >   out = proc.stdout
    > >   while proc.poll() is None:
    > >     print out.readline()
    >
    > >  Run this program as follows
    > >  $ test.py "ping -c 10www.google.com"
    >
    > >  Now, you would see the responses as if you just launched ping on the
    > >  command line. Now, lets look at another program. Here is a simple C++
    > >  program that prints numbers 1 to 10 at the passage of every second
    > >  (sort of a stopwatch)
    >
    > >  #include 
    > >  #include 
    > >  #include 
    > >  main ( )
    > >  {
    > >   timeval t1, t2;
    > >   gettimeofday(&t1, NULL);
    > >   int prev = -1;
    > >   int cur = 0;
    > >   while (true)
    > >   {
    > >     gettimeofday(&t2,NULL);
    > >     if(t2.tv_sec - t1.tv_sec > 10)
    > >       break;
    > >     else
    > >     {
    > >       cur = t2.tv_sec-t1.tv_sec;
    > >       if (cur != prev)
    > >       {
    > >         printf("%d\r\n",cur);
    > >         prev = cur;
    > >       }
    > >     }
    > >   }
    > >  }
    >
    > >  if you would build this program and call it lets say timer ($ g++ -o
    > >  timer timer.cpp)  and run it with our python script like this
    >
    > >  $python test.py "./timer"
    >
    > >  you would see that every time you run the program your results vary
    > >  and on top of this the stdout of the timer program gets displayed all
    > >  at once presumably when the timer program has completed execution.
    >
    > >  Why this discrepancy between the ping and timer programs? Is my
    > >  test.py script correct? Is there a better or a preferred method for
    > >  doing interprocess communication in Python.
    >
    > Buffering is your problem.
    >
    > If you add a fflush(stdout); after the printf(...); you'll find the
    > c++ program works as you expect.
    >
    > It is just a fact of life of the C stdio system.  If it is connected
    > to a terminal then it will turn off buffering.  If it is connected
    > anything else (eg a pipe via subprocess) then it will buffer stuff as
    > you've seen.
    >
    > So you can
    >
    Thanks Nick. fflush fixed it. Thanks for your pointers on pexpect and
    pty module too.
    
    Murali.
    
    
    > a) modify the c++ prog to add fflush() in or use setvbuf()
    > b) use the pexpect module -http://pexpect.sourceforge.net/
    > c) use the pty module (unix only)
    >
    > The pexpect module will connect to the subprogram with pseudo-ttys,
    > fooling the program, and the C library, into thinking that it is
    > speaking to a terminal and turn off buffering.  Pexpect doesn't work
    > on windows.
    >
    > The fact that ping works is because it uses fflush() - you can see
    > this if you "ltrace" it.
    >
    > --
    > Nick Craig-Wood  --http://www.craig-wood.com/nick
    
    
    
    
    From claird at lairds.us  Fri Jul  6 13:02:24 2007
    From: claird at lairds.us (Cameron Laird)
    Date: Fri, 6 Jul 2007 17:02:24 +0000
    Subject: Tiny/small/minimalist Python?
    References: <1183332951.122782.212720@o11g2000prd.googlegroups.com>
    	<1183389420.175712.59460@z28g2000prd.googlegroups.com>
    	<7xmyyeizf8.fsf@ruckus.brouhaha.com>
    	<468997c7$0$327$e4fe514c@news.xs4all.nl>
    Message-ID: <0692m4-lso.ln1@lairds.us>
    
    In article <468997c7$0$327$e4fe514c at news.xs4all.nl>,
    Irmen de Jong   wrote:
    >Paul Rubin wrote:
    >> rtk  writes:
    >>> FYI.. I wanted a simple version of Python to run on an ancient DEC
    >>> Alpha box.  I got VMS Python 2.5 up and running but it is too slow to
    >>> use.  It takes *minutes* to get the interpreter prompt after typing
    >>> 'python'! 
    >> 
    >> Something is wrong.  Maybe it's trying to DNS itself and timing out,
    >> or something like that.
    >
    >Something is definately wrong.
    >
    >Back in the days my port of Python to the Commodore Amiga machine ran
    >quite comfortably on a 50 mhz CPU with 4 Mb of RAM. (ok ok it was
    >Python 1.5.2, that has to be said).
    >Python started in about 5 seconds on that Amiga if I remember
    >correctly. I'm quite sure your 'ancient' DEC Alpha box is way more
    >powerful than my Amiga back then.
    >
    >--Irmen
    
    Me, too.
    
    I'm all for Lua--I began promoting it over ten years ago.  However,
    I was also working on Alphas at about that time, as well as VMS, and
    of course with Python.  While I don't recall that I ever had occasion
    to test Python under VMS for Alpha much, I've used every other 
    combination quite a bit.  Something's fishy about this report of a
    minute-long launch-time.
    
    
    From skpatel20 at gmail.com  Fri Jul 13 07:55:26 2007
    From: skpatel20 at gmail.com (Sanjay)
    Date: Fri, 13 Jul 2007 04:55:26 -0700
    Subject: pytz giving incorrect offset and timezone
    Message-ID: <1184327726.714645.306520@z28g2000prd.googlegroups.com>
    
    Hi All,
    
    I am facing some strange problem in pytz.
    
    The timezone "Asia/Calcutta" is actually IST, which is GMT + 5:30. But
    while using pytz, it is being recognized as HMT (GMT + 5:53). While I
    digged into the oslan database, I see the following:
    
    # Zone NAME GMTOFF RULES FORMAT [UNTIL]
    Zone Asia/Calcutta 5:53:28 - LMT 1880 # Kolkata
                   5:53:20 - HMT 1941 Oct # Howrah Mean Time?
                   6:30 - BURT 1942 May 15 # Burma Time
                   5:30 - IST 1942 Sep
                   5:30 1:00 IST 1945 Oct 15
                   5:30 - IST
    
    A similar problem is also posted at
    http://groups.google.co.in/group/comp.lang.python/browse_thread/thread/55496e85797ac890
    without any responnses.
    
    Unable to know how to proceed. Needing help. Tried posting in
    launchpad and mailed to Stuart, but yet to get any response.
    
    thanks
    Sanjay
    
    
    
    From rjh at see.sig.invalid  Tue Jul  3 09:53:44 2007
    From: rjh at see.sig.invalid (Richard Heathfield)
    Date: Tue, 03 Jul 2007 13:53:44 +0000
    Subject: Portable general timestamp format, not 2038-limited
    References: <1182544384.709759.235300@o11g2000prd.googlegroups.com>
    	
    	
    	<20070625133843.9e25d0ab.steveo@eircom.net>
    	<82b5l4-tvh.ln1@zoogz.gregorie.org>
    	<7xbqf3lc7i.fsf@ruckus.brouhaha.com>
    	<70c7l4-2gp.ln1@zoogz.gregorie.org>
    	<7xlke6y6y1.fsf@ruckus.brouhaha.com>
    	
    	<7x645al8kc.fsf@ruckus.brouhaha.com>
    	<1182894003.920335.317620@a26g2000pre.googlegroups.com>
    	<7x7ipoy6cf.fsf@ruckus.brouhaha.com>
    	<1183041149.275562.114490@o11g2000prd.googlegroups.com>
    	<7xbqethpr8.fsf@ruckus.brouhaha.com>
    	
    	
    Message-ID: 
    
    Peter J. Holzer said:
    
    > On 2007-07-03 08:57, Richard Heathfield  wrote:
    >> Paul Rubin said:
    >>> sla29970 at gmail.com writes:
    >>>> As for the primacy of UTC vs. TAI, this is the classical chicken
    >>>> and
    >>>> egg problem.  The bureaucratic reality is opposed to the physical
    >>>> reality.
    >>> 
    >>> Well, if you're trying to pick just one timestamp standard, I'd say
    >>> you're better off using a worldwide one rather than a national one,
    >>> no matter how the bureaucracies work.
    >>
    >> In that case, the obvious choice is Greenwich Mean Time.  :-)
    > 
    > Hardly. That hasn't been in use for over 35 years (according to
    > Wikipedia).
    
    Nonsense. I use it every day, and have been doing so for - well, rather 
    more than 35 years.
    
    >> Seriously, GMT is recognised all over the world (far more so, in
    >> fact, than UTC, which tends to be recognised only by some
    >> well-educated people, and there are precious few of those), so why
    >> not use it?
    > 
    > While the layman may recognize the term "GMT", he almost certainly
    > means "UTC" when he's talking about GMT.
    
    Most people of my acquaintance who use the term "GMT" mean precisely 
    that - Greenwich Mean Time.
    
    
    
    >> I always leave my PC's clock set to GMT,
    > 
    > Your PC is directly linked to an observatory?
    
    Nope. My PC *defines* GMT. If the observatory wants to know what the 
    exact time is, they only have to ask.
    
    -- 
    Richard Heathfield 
    Email: -www. +rjh@
    Google users: 
    "Usenet is a strange place" - dmr 29 July 1999
    
    
    From iansan at gmail.com  Wed Jul  4 01:39:08 2007
    From: iansan at gmail.com (IamIan)
    Date: Wed, 04 Jul 2007 05:39:08 -0000
    Subject: XML / Unicode / SAX question
    Message-ID: <1183527548.695326.303120@i13g2000prf.googlegroups.com>
    
    I am using SAX to parse XML that has numeric html entities I need to
    convert and feed to JavaScript as part of a CGI. I can get the
    characters to print correctly, but not without being surrounded by
    linebreaks:
    
    from xml.sax import make_parser
    from xml.sax.handler import ContentHandler
    import htmlentitydefs, re
    
    def unescape_charref(ref):
        name = ref[2:-1]
        base = 10
        if name.startswith("x"):
            name = name[1:]
            base = 16
        return unichr(int(name, base))
    
    def replace_entities(match):
        ent = match.group()
        if ent[1] == "#":
            return unescape_charref(ent)
    
        repl = htmlentitydefs.name2codepoint.get(ent[1:-1])
        if repl is not None:
            repl = unichr(repl)
        else:
            repl = ent
        return repl
    
    def unescape(data):
        return re.sub(r"&#?[A-Za-z0-9]+?;", replace_entities, data)
    
    class newsHandler(ContentHandler):
      def __init__(self):
        self.isNews = 0
    
      def startElement(self, name, attrs):
        if name == 'title':
          self.isNews = 1
    
      def characters(self, ch):
        if self.isNews:
          ch = unescape(ch)
          print ch
    
      def endElement(self, name):
        if name == 'title':
          self.isNews = 0
    
    parser = make_parser()
    parser.setContentHandler(newsHandler())
    parser.parse('http://www.some.com/rss/rss.xml')
    
    For a line like 'Mark à Capbreton'
    my results print as:
    'Mark
    ?
    Capbreton'
    
    Is this another SAX quirk? I've already had to hack my way around SAX
    not being able to split results on a colon. No matter if I try strip,
    etc the results are always the same: newlines surrounding the html
    entities. I'm using version 2.3.5 and need to stick to the standard
    libraries. Thanks.
    
    
    
    From kyosohma at gmail.com  Wed Jul 25 11:00:39 2007
    From: kyosohma at gmail.com (kyosohma at gmail.com)
    Date: Wed, 25 Jul 2007 08:00:39 -0700
    Subject: Flatten a list/tuple and Call a function with tuples
    In-Reply-To: <1185375018.793020.224890@w3g2000hsg.googlegroups.com>
    References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com>
    Message-ID: <1185375639.761280.262490@b79g2000hse.googlegroups.com>
    
    On Jul 25, 9:50 am, beginner  wrote:
    > Hi,
    >
    > I am wondering how do I 'flatten' a list or a tuple? For example, I'd
    > like to transform[1, 2, (3,4)] or [1,2,[3,4]] to  [1,2,3,4].
    >
    > Another question is how do I pass a tuple or list of all the
    > aurgements of a function to the function. For example, I have all the
    > arguments of a function in a tuple a=(1,2,3). Then I want to pass each
    > item in the tuple to a function f so that I make a function call
    > f(1,2,3). In perl it is a given, but in python, I haven't figured out
    > a way to do it. (Maybe apply? but it is deprecated?)
    >
    > Thanks,
    > cg
    
    I'm not sure about the first question, but as for the second, you
    could do a few different things. You could just pass the tuple itself
    into the function and have the tuple unpacked inside the function.
    
    
    
    f(a)
    
    def f (tuple):
        x,y,z = tuple
    
    
    
    You could also pass the elements of the tuple in:
    
    f(a[0], a[1], a[2])
    
    That would do it the way you describe in your post.
    
    Mike
    
    
    
    From greg at cosc.canterbury.ac.nz  Wed Jul  4 21:45:15 2007
    From: greg at cosc.canterbury.ac.nz (greg)
    Date: Thu, 05 Jul 2007 13:45:15 +1200
    Subject: Building a Python app with Mozilla
    In-Reply-To: <1183524527.709730.190290@q75g2000hsh.googlegroups.com>
    References: 
    	<1183524527.709730.190290@q75g2000hsh.googlegroups.com>
    Message-ID: <5f30vsF3aicltU1@mid.individual.net>
    
    sjdevnull at yahoo.com wrote:
    
    > wxWidgets will give you native looking apps on both Linux and Windows
    
    Well, maybe. There's more to getting a native feel than
    just using the right widgets. I once saw a Qt-based app on
    MacOSX that had tiny little buttons that were too small
    for the text they contained -- Aqua buttons just don't
    scale down like that. :-(
    
    --
    Greg
    
    
    From attn.steven.kuo at gmail.com  Sat Jul 21 14:00:32 2007
    From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com)
    Date: Sat, 21 Jul 2007 11:00:32 -0700
    Subject: converting 64-bit fixed-point to float
    In-Reply-To: <1i1k9cc.1hyy4zm1ybovgwN%johnmfisher@comcast.net>
    References: <1i1k9cc.1hyy4zm1ybovgwN%johnmfisher@comcast.net>
    Message-ID: <1185040832.243875.48420@e16g2000pri.googlegroups.com>
    
    On Jul 20, 5:59 pm, johnmfis... at comcast.net (John Fisher) wrote:
    > Hi Group,
    >
    > troubles with converting signed 32.32, little-endian, 2's complement
    > back to floating point. I have been trying to brew it myself. I am
    > running Python 2.5 on a Mac. Here is the C-code I have been trying to
    > leverage:
    >
    >  double FPuint8ArrayToFPDouble(uint8 *buffer, int startIndex)
    > {
    >   uint32 resultDec = 0;
    >   uint32 resultWh = 0;
    >   int i;
    >
    >   for(i = 0; i < 4; i++)
    >   {
    >     resultDec += (uint32)buffer[startIndex + i] * pow(2, (i*8));
    >     resultWh += (uint32)buffer[startIndex + i + 4] * pow(2, (i*8));
    >   }
    >
    >   return ( (double)((int)resultWh) + (double)(resultDec)/4294967296.0 );
    >
    > }
    
    
    There are a few problem spots in that C code.  I tend to
    think that it "works" because you're on a system that has
    4-byte int and CHAR_BIT == 8.  When the most-significant-bit (MSB)
    of resultWh is 1, then casting to int makes that a negative
    value (i.e., MSB == the sign bit).
    
    I presume that somewhere you include  (from C99)
    and that uint32 is really uint32_t, etc.  For that to be
    portable, you should probably cast to int32_t?
    
    #include 
    #include 
    #include 
    
    double arr2dbl (uint8_t *buffer, int startIndex)
    {
        uint32_t decimal = 0;
        uint32_t whole = 0;
        size_t i;
        for (i = 0; i < 4; ++i)
        {
            decimal += (buffer[startIndex + i] << (i*8));
            whole += (buffer[startIndex + i + 4] << (i*8));
        }
        return (int32_t)whole + (decimal/(UINT32_MAX+1.0));
    }
    
    int main (void)
    {
        uint8_t arr[7][8] = {
            {0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff},
            {0, 0, 0, 0, 0, 0, 0, 0},
            {51, 51, 51, 51, 0, 0, 0, 0},
            {0, 0, 0, 0, 1, 0, 0, 0},
            {0, 0, 0, 0, 2, 0, 0, 0},
            {102, 102, 102, 38, 42, 1, 0, 0 },
            {205, 204, 204, 204, 0xff, 0xff, 0xff, 0xff}};
        size_t i;
        double result;
        for (i = 0; i < sizeof arr/sizeof arr[0]; ++i)
        {
            result = arr2dbl(arr[i], 0);
            printf("%f\n", result);
        }
        return 0;
    }
    
    
    
    
    
    
    
    > Here is my version in Python, with some test code built in:
    >
    > from ctypes import *
    >
    > def conv64(input):
    >     input1=[0]*8
    >     input1[0]=c_ushort(input[0])
    >     input1[1]=c_ushort(input[1])
    >     input1[2]=c_ushort(input[2])
    >     input1[3]=c_ushort(input[3])
    >     input1[4]=c_ushort(input[4])
    >     input1[5]=c_ushort(input[5])
    >     input1[6]=c_ushort(input[6])
    >     input1[7]=c_ushort(input[7])
    >     #print input1[0].value,
    > input1[1].value,input1[2].value,input1[3].value
    >     #print
    > input1[4].value,input1[5].value,input1[6].value,input1[7].value
    >     #print
    >     resultDec=c_ulong(0)
    >     resultWh=c_ulong(0)
    >     for i in range(4):
    >         dec_c=c_ulong(input1[i].value)
    >         Wh_c=c_ulong(input1[i+4].value)
    >         resultDec.value=resultDec.value+dec_c.value*2**(i*8)
    >         resultWh.value=resultWh.value+Wh_c.value*2**(i*8)
    >    conval=float(int(resultWh.value))+float(resultDec.value)/4294967296.0
    >     #print conval
    >     return conval
    > #tabs got messed up bringing this into MacSoup
    
    
    (snipped)
    
    
    >
    > Finally, here is the output I get from my code:
    >
    >
    >
    > output should be -1 is 4294967296.0
    > output should be 0 is 0.0
    > output should be 0.2 is 0.199999999953
    > output should be 1 is 1.0
    > output should be 2 is 2.0
    > output should be 298.15 is 298.15
    > output should be -0.2 is 4294967295.8
    >
    > Thanks for any light you can shed on my ignorance.
    >
    > wave_man
    
    
    This is my translation:
    
    from ctypes import *
    
    def conv64(input):
        input1 = [c_uint8(item) for item in input]
        dec = c_uint32(0)
        whl = c_uint32(0)
        for i in xrange(4):
            dec.value += (input1[i].value << (i*8))
            whl.value += (input1[i+4].value << (i*8))
        cast_whl_to_int = c_int32(whl.value)
        return float(cast_whl_to_int.value + dec.value/4294967296.0)
    
    
    for arr in [[0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff],
            [0, 0, 0, 0, 0, 0, 0, 0],
            [51, 51, 51, 51, 0, 0, 0, 0],
            [0, 0, 0, 0, 1, 0, 0, 0],
            [0, 0, 0, 0, 2, 0, 0, 0],
            [102, 102, 102, 38, 42, 1, 0, 0],
            [205,204,204,204,255,255,255,255]]:
        print "%f" % conv64(arr)
    
    
    
    However, I've not looked deeply into ctypes so I
    don't know if c_int32 is really C's int, or int32_t, or ???
    
    --
    Hope this helps,
    Steven
    
    
    
    From jthacher at unm.edu  Tue Jul 17 12:39:32 2007
    From: jthacher at unm.edu (Jennifer Thacher)
    Date: Tue, 17 Jul 2007 09:39:32 -0700
    Subject: chmod directories recursively
    In-Reply-To: 
    References: 
    Message-ID: <469CF0C4.3020808@unm.edu>
    
    Fabian Steiner wrote:
    > Hello!
    > 
    > As far as I can see os.chmod() doesn't adjust permissions on directories
    > recusively. Is there any other possibility to achieve this aim except for
    > calling os.system('chmod -R /dir') directly?
    > 
    > Thanks,
    > Fabian
    
    Check out os.path.walk.
    
    James
    
    
    From nospam at nospam.com  Sat Jul 28 19:29:36 2007
    From: nospam at nospam.com (Gilles Ganault)
    Date: Sun, 29 Jul 2007 01:29:36 +0200
    Subject: Why no maintained wrapper to Win32?
    References: 
    	<46ab694e$0$17577$9b622d9e@news.freenet.de>
    Message-ID: <59kna3p8r0cu2gk6hs5lbig8cjj8klatju@4ax.com>
    
    On Sat, 28 Jul 2007 18:05:34 +0200, "Martin v. L?wis"
     wrote:
    >Why does it mean that? The Win32 APIs for GUI are up-to-date; they
    >don't need further development. Win32 itself stopped years ago.
    >You can write GUI applications with PyWin32 just fine.
    
    Besides the total lack of documentation, you mean that nothing was
    added to the Win32 API since PyWin32 was last updated?
    
    
    From dvd_km at yahoo.com  Wed Jul 11 19:06:54 2007
    From: dvd_km at yahoo.com (dvd_km)
    Date: Wed, 11 Jul 2007 16:06:54 -0700
    Subject: www.OutpatientSurgicare.com/video/
    Message-ID: <1184195214.271343.147490@e16g2000pri.googlegroups.com>
    
    www.OutpatientSurgicare.com/video/
    Outpatient Doctors Surgery Center is committed to offering the
    healthcare the community needs. We offer patients a meaningful
    alternative to traditional surgery. This state-of-the-art outpatient
    surgery center, located in the heart of Orange County, at 10900 Warner
    Avenue, Suite 101A, Fountain Valley, Ca 92708, offers the latest
    innovations in outpatient surgery and technology.
    Please Call For Our Special Cash Discount
    Toll Free: 1-877-500-2525
    Please Visit Our Websites:
    We offer extreme cosmetic surgery makeover packages.
    http://www.SurgeonToTheStars.com
    http://www.1cosmeticsurgery.com
    Specializing in the cure of hyperhidrosis, sweaty palms, underarm and
    foot sweating.
    http://www.CuresweatyPalms.com
    http://www.ControlExcessiveSweating.com
    No. 1 Weight Loss Surgery Center
    http://www.ControlWeightLossNow.com
    http://www.FreeLapBandSeminar.com
    Hernia Treatment Center
    http://www.HerniaDoc.com
    Take care of your feet
    http://www.CureFootPain.com
    The Experts in CARPAL TUNNEL SYNDROME
    http://www.CureHandPain.com
    
    Accidental Urine Leaks ? End Urinary Incontinence
    http://www.WomanWellnessCenter.com
    Hemorrhoid Treatment Center
    http://www.hemorrhoidtreatmentcenter.com
    
    
    
    From semanticist at gmail.com  Mon Jul 23 01:51:45 2007
    From: semanticist at gmail.com (Miles)
    Date: Mon, 23 Jul 2007 01:51:45 -0400
    Subject: URL parsing for the hard cases
    In-Reply-To: 
    References: 
    	<1185138747.707836.69740@n2g2000hse.googlegroups.com>
    	
    	
    Message-ID: 
    
    On 7/23/07, John Nagle wrote:
    > Here's another hard case.  This one might be a bug in urlparse:
    >
    > import urlparse
    >
    > s = 'ftp://administrator:password at 64.105.135.30/originals/6 june
    > 07/ebay/login/ebayisapi.html'
    >
    > urlparse.urlparse(s)
    >
    > yields:
    >
    > (u'ftp', u'administrator:password at 64.105.135.30', u'/originals/6 june
    > 07/ebay/login/ebayisapi.html', '', '', '')
    >
    > That second field is supposed to be the "hostport" (per the RFC usage
    > of the term; Python uses the term "netloc"), and the username/password
    > should have been parsed and moved to the "username" and "password" fields
    > of the object. So it looks like urlparse doesn't really understand FTP URLs.
    
    Those values aren't "moved" to the fields; they're extracted on the
    fly from the netloc.  Use the .hostname property of the result tuple
    to get just the hostname.
    
    -Miles
    
    
    From puonegf+hfrarg at tznvy.pbz  Tue Jul  3 16:10:14 2007
    From: puonegf+hfrarg at tznvy.pbz (Chris Barts)
    Date: Tue, 03 Jul 2007 14:10:14 -0600
    Subject: The Modernization of Emacs: terminology buffer and keybinding
    References: <1182093200.598418.218620@e9g2000prf.googlegroups.com>
    	<1182453375.531950.141460@m36g2000hse.googlegroups.com>
    	<1182456618.763414.219080@g4g2000hsf.googlegroups.com>
    	 <5ear80F36ga72U3@mid.individual.net>
    Message-ID: 
    
    blmblm at myrealbox.com  wrote on Monday 25 June 2007
    15:43 in comp.emacs <5ear80F36ga72U3 at mid.individual.net>:
    
    > 
    > Eclipse has something that generates "import" statements with
    > a few keystrokes, and for me that's almost in the "killer app
    > [feature]" class.  
    
    This is a sign of a weak programming language, in my eyes: If you need
    keystroke macros to enter boilerplate, you REALLY need a language that
    allows you to package commonly-used idioms into macros. (See Common Lisp,
    Scheme, Emacs Lisp, and, indeed, even Dylan. Python and Ruby almost solve
    the same problem by providing a richer set of primitives, but they aren't
    extensible.)
    
    > (Why do I strongly suspect that with the 
    > right plug-ins emacs can do this too?  :-)   That would send
    > me searching for the Web site where vim macros are collected.)
    > 
    
    Inserting literal text in Emacs using keystroke macros is trivial. Inserting
    more changeable boilerplate is a job for Emacs Lisp.
    
    -- 
    My address happens to be com (dot) gmail (at) usenet (plus) chbarts,
    wardsback and translated.
    It's in my header if you need a spoiler.
    
    
    
    From roberth+news at ifi.uio.no  Thu Jul  5 03:23:38 2007
    From: roberth+news at ifi.uio.no (Robert Bauck Hamar)
    Date: Thu, 05 Jul 2007 09:23:38 +0200
    Subject: ['a', 'b'][True] results 'b'   But how?
    References: <1183618481.636297.96080@e9g2000prf.googlegroups.com>
    Message-ID: 
    
    kath wrote:
    
    > Hi,
    > 
    > Can any one please tell me how is the following code is working?
    > ['a','b'] is a list of string
    
    Yes.
    
    > and [True] is list of boolean value. 
    
    No. It's the subscription operator applied to the list of strings.
    a = ['a', 'b']
    a[True]
    may be clearer.
    
    > How is it making effect....?
    
    >>> int(True)
    1
    >>> int(False)
    0
    >>> isinstance(True, int)
    True
    >>> bool.__bases__
    (,)
    
    > 
    > 
    >>>> ['a','b] [True]
    > 'b'
    >>>> ['a','b'] [False]
    > 'a'
    >>>> ['a','b']['some_string' == r'some_string']
    > 'b'
    >>>> ['a','b']['some_string' == r'somestring']
    > 'a'
    > 
    > 
    
    -- 
    rbh
    
    
    From claird at lairds.us  Fri Jul 27 09:33:09 2007
    From: claird at lairds.us (Cameron Laird)
    Date: Fri, 27 Jul 2007 13:33:09 +0000
    Subject: Submit form, open result in a browser
    References: 
    	<1185530031.986538.270490@m37g2000prh.googlegroups.com>
    	
    Message-ID: 
    
    In article ,
    Tina I   wrote:
    >theju wrote:
    >>> Is there a way to submit a form and then open the resulting page in the
    >>> default browser? (Writing the form submission code is not a problem by
    >>> the way)
    >> 
    >> There is a library called "Client Form" that does this for you.
    >> wwwsearch.sourceforge.net/ClientForm/
    >> 
    >> After the form is submitted through ClientForm open the resulting
    >> response using the webbrowser module.
    >> 
    >> Cheers
    >> Thejaswi Puthraya
    >> 
    >
    >ClientForm is absolutely perfect! Less than 10 lines of extra code and 
    >the job is done :)
    			.
    			.
    			.
    
    has example code related to this topic, that perhaps will
    interest readers other than Tina I (to whom:  congratulations!).
    
    
    From len-l at telus.net  Tue Jul  3 01:23:11 2007
    From: len-l at telus.net (Lenard Lindstrom)
    Date: Tue, 03 Jul 2007 05:23:11 GMT
    Subject: Python's "only one way to do it" philosophy isn't good?
    In-Reply-To: 
    References: 
    	 <7xejjzmk7u.fsf@ruckus.brouhaha.com>
    	 <7xy7i7xjl5.fsf@ruckus.brouhaha.com>
    	
    	
    	
    	
    	
    	
    	 
    	 
    	 
    	
    Message-ID: <33lii.20072$tB5.12886@edtnps90>
    
    Douglas Alan wrote:
    > Lenard Lindstrom  writes:
    > 
    
    >>> Or are you suggesting that early in __main__.main(), when I wish to
    >>> debug something, I do something like:
    >>>    __builtins__.open = __builtins__.file = MyFile
    >>> ?
    >>> I suppose that would work.
    > 
    >> No, I would never suggest replacing a builtin like that. Even
    >> replacing a definite hook like __import__ is risky, should more than
    >> one package try and do it in a program.
    > 
    > That misinterpretation of your idea would only be reasonable while
    > actually debugging, not for standard execution.  Standard rules of
    > coding elegance don't apply while debugging, so I think the
    > misinterpretation might be a reasonable alternative.  Still I think
    > I'd just prefer to stick to the status quo in this regard.
    > 
    
    I totally missed the "when I wish to debug something". Skimming when I 
    should be reading.
    
    ---
    Lenard Lindstrom
    
    
    
    From nospam.themindstorm at gmail.com  Sat Jul 28 11:17:56 2007
    From: nospam.themindstorm at gmail.com (Alex Popescu)
    Date: Sat, 28 Jul 2007 15:17:56 +0000 (UTC)
    Subject: replacement for execfile
    Message-ID: 
    
    Hi all!
    
    >From another thread (and the pointed PEP) I have found that execfile will 
    not be present in Py3k. So, I am wondering what will be its replacement? 
    Considering that most probably Py3k will keep eval and exec, this will 
    still be possible (indeed requiring manual loading of the file string), so 
    I would really appreciate some enlightning comments on this.
    
    Background:
    Basically this question is related to my learning process/working project. 
    In this, I have the need to allow the final user to provide a configuration 
    like script, but built using my API (and whatever other normal Python code 
    they want). For this, having execfile was a nice surprise as I was able to 
    automatically expose the API (so the end user doesn't need to bother about 
    imports) and also easily execute it in the context I wanted.
    
    many thanks in advance,
    ./alex
    --
    .w( the_mindstorm )p.
    
    
    
    From bj_666 at gmx.net  Sat Jul  7 02:58:01 2007
    From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch)
    Date: 7 Jul 2007 06:58:01 GMT
    Subject: Where is the syntax for the dict() constructor ?!
    References: <468D1D9D.6060002@gmail.com>
    	
    	<468D3445.2060408@gmail.com>
    	
    	<1183675552.466967.136360@i13g2000prf.googlegroups.com>
    	
    	<5f6fo1F3b25tsU1@mid.uni-berlin.de>
    	
    Message-ID: <5f8rrpF3c8qopU1@mid.uni-berlin.de>
    
    On Sat, 07 Jul 2007 08:32:52 +0200, Hendrik van Rooyen wrote:
    
    >> erik,viking,"ham, spam and eggs","He said ""Ni!""","line one
    >> line two"
    >> 
    >> That's 5 elements:
    >> 
    >> 1: eric
    >> 2: viking
    >> 3: ham, spam and eggs
    >> 4: He said "Ni!"
    >> 5: line one
    >>    line two
    > 
    > Also true - What can I say - I can only wriggle and mutter...
    > 
    > I see that you escaped the quotes by doubling them up -
    
    That's how Excel and the `csv` module do it.
    
    > What would the following parse to?:
    > 
    >  erik,viking,ham, spam and eggs,He said "Ni!",line one
    >  line two
    
    Why don't you try yourself?  The `csv` module returns two records, the
    first has six items:
    
    1: erik
    2: viking
    3: ham
    4:  spam and eggs
    5: He said "Ni!"
    6: line one
    
    'line two' is the only item in the next record then.
    
    Ciao,
    	Marc 'BlackJack' Rintsch
    
    
    From steve at holdenweb.com  Tue Jul 24 07:17:07 2007
    From: steve at holdenweb.com (Steve Holden)
    Date: Tue, 24 Jul 2007 07:17:07 -0400
    Subject: display image through cgi python html
    In-Reply-To: <5gm1ggF3gs3gfU3@mid.uni-berlin.de>
    References: 
    	<5gm1ggF3gs3gfU3@mid.uni-berlin.de>
    Message-ID: 
    
    Marc 'BlackJack' Rintsch wrote:
    > On Tue, 24 Jul 2007 11:58:47 +0200, Ladislav Andel wrote:
    > 
    >> Here is what I have in image.cgi but it is incorrect and i'm not able to 
    >> find it on the web.
    >>
    >> #!/usr/bin/python
    >> print "Content-Type: image/png\n"
    >> print 'image.png'
    > 
    > You have to print the image, not the name.  Read the binary file and print
    > it.
    > 
    As in:
    
    #!/usr/bin/python
    data = open('image.png', 'rb').read()
    print "Content-Type: image/png\nContent-Length: %d\n" % len(data)
    print data
    
    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 the.mindstorm.mailinglist at gmail.com  Fri Jul  6 04:58:47 2007
    From: the.mindstorm.mailinglist at gmail.com (Alex Popescu)
    Date: Fri, 06 Jul 2007 01:58:47 -0700
    Subject: Re-raising exceptions with modified message
    In-Reply-To: 
    References: 
    	<1183668029.470160.218230@q69g2000hsb.googlegroups.com>
    	
    	<1183673210.409169.51830@n2g2000hse.googlegroups.com>
    	
    Message-ID: <1183712327.457975.227850@q75g2000hsh.googlegroups.com>
    
    On Jul 6, 4:20 am, Christoph Zwerschke  wrote:
    > Alex Popescu wrote:
    >
    
    
    
    From zentraders at gmail.com  Sat Jul 28 01:05:48 2007
    From: zentraders at gmail.com (Zentrader)
    Date: Fri, 27 Jul 2007 22:05:48 -0700
    Subject: a simple string question
    In-Reply-To: <1185589263.743811.204040@x40g2000prg.googlegroups.com>
    References: <1185549793.114644.62170@k79g2000hse.googlegroups.com>
    	
    	<1185558406.916313.32980@r34g2000hsd.googlegroups.com>
    	
    	<1185589263.743811.204040@x40g2000prg.googlegroups.com>
    Message-ID: <1185599148.583067.42910@d30g2000prg.googlegroups.com>
    
    > > vedrandeko... at v-programs.com wrote:
    > > > NEW TEXT :  "Hello world;\nHello:\n\t\t\n\n\n\n\n\nHello2"
    
    If you are doing all of this to format the output into columns,
    Python's print() or write() will do this, and is easier as well.  Some
    more info on what you want to do will clear things up.
    
    
    
    From steve at holdenweb.com  Sat Jul 28 08:15:24 2007
    From: steve at holdenweb.com (Steve Holden)
    Date: Sat, 28 Jul 2007 08:15:24 -0400
    Subject: a simple string question
    In-Reply-To: <1185613816.996100.323090@r34g2000hsd.googlegroups.com>
    References: <1185549793.114644.62170@k79g2000hse.googlegroups.com>		<1185558406.916313.32980@r34g2000hsd.googlegroups.com>		<1185589263.743811.204040@x40g2000prg.googlegroups.com>	<1185599148.583067.42910@d30g2000prg.googlegroups.com>
    	<1185613816.996100.323090@r34g2000hsd.googlegroups.com>
    Message-ID: 
    
    vedrandekovic at v-programs.com wrote:
    > On 28 srp, 07:05, Zentrader  wrote:
    >>>> vedrandeko... at v-programs.com wrote:
    >>>>> NEW TEXT :  "Hello world;\nHello:\n\t\t\n\n\n\n\n\nHello2"
    >> If you are doing all of this to format the output into columns,
    >> Python's print() or write() will do this, and is easier as well.  Some
    >> more info on what you want to do will clear things up.
    > 
    > Hi,
    > 
    > That is confusing me too, so now I will try explain it more.This is
    > text before "translation":
    > Let me explain you with python code. I want to this "function" act
    > code indentation
    > 
    >>>> Short_Text="n=90; if n==90:print 'ok'"
    > Then now I must  write that function for detect ";" and ":", and if
    > that function detect ";" then it appends "\n" before ";" but
    > if detect ":" then it appends "\n\t\t\t\t\t\t\t\t"
    >>>> Short_text_after_translation="n=90;\nif n==90:\n\t\t\t\t\t\t\t\tprint 'ok"
    > ...And now when we run this code with exec this must look like:
    > 
    > n=90;
    > if n==90:
    >        print 'ok'
    > 
    > I think this will be enough for help.
    > 
    OK, but you don't want that many tab characters if you can the code to 
    look like you show it. It's not, anyway, a good idea to use tabs to 
    indent code.
    
    I suspect what you need is to split the code on semicolons first, then 
    re-form lines with colons in them. Some simple code to do this would 
    look *something* like what follows. This will handle a little more than 
    you wanted.
    
     >>> Short_Text="n=90; if n==90:print 'ok'"
     >>> compound_lines = Short_Text.split(";")
     >>> for line in compound_lines:
    ...   line = line.replace(":", ":\n    ")
    ...   print line
    ...
    n=90
      if n==90:
         print 'ok'
     >>>
    
    Note there are issues here that I haven't addressed. The first is that 
    leading spaces on the second statement need to be removed, and the 
    second is that this only works at the outermost level of indentation. 
    For example, if you want to end up translating function definitions with 
    if statements inside them correctly you will need to handle multiple 
    levels of indentation. There are other problems, like semicolons and 
    colons inside string constants should be ignored, but the only way to 
    get over those will be to parse the program text according to some 
    grammar rather than using ad-hoc methods such as the above.
    
    I hope I have finally been of some assistance ... please reply via the 
    newsgroup, not in personal email.
    
    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 willmaier at ml1.net  Wed Jul 18 20:48:33 2007
    From: willmaier at ml1.net (Will Maier)
    Date: Wed, 18 Jul 2007 19:48:33 -0500
    Subject: Newbie: freebsd admin scripting
    In-Reply-To: 
    References: 
    	
    Message-ID: <20070719004833.GJ12728@lass.lfod.us>
    
    On Wed, Jul 18, 2007 at 04:31:35PM -0700, Evan Klitzke wrote:
    > > I found a built in mod for parseconfig but it deal with .ini
    > > file styles (windows) that include a [section] header as well as
    > > uses someiteam=somevalue format. I believe it requires the
    > > header though.
    > 
    > I think you're referring to ConfigParser. This is the standard way
    > to do config files in Python, and it is very simple to use and
    > work with, so I would recommend using it.
    
    rc.conf is a shell script on BSD systems. The OP will need to write
    his own parser to read it. Take a look at the wiki's list of
    parsers[0], specifically shlex[1]. I haven't used it to parse things
    like rc.conf, but I imagine it could be useful.
    
    > > Books or howtos regarding Unix admin scripting(python) would be
    > > great.  Is this type of scripting mainly executing a Unix
    > > command and capturing and parsing its output like this:
    > >
    > > x=command.getoutput("ifconfig")
    > >
    > > and them parsing x for what I want or is there a name space I
    > > can call to get , for example, a list of all interfaces?
    
    Nothing in the standard library handles interface configuration,
    though there may be a package somewhere to help you with that. In
    general, yes, you'll be writing your own scripts wrapping around
    system commands. As Evan says, be smart and keep those scripts
    around. As you figure things out, generalize your scripts and create
    some useful classes, etc.
    
    [0] http://wiki.python.org/moin/LanguageParsing
    [1] http://www.python.org/doc/current/lib/module-shlex.html
    
    -- 
    
    [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/]
    
    
    From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Tue Jul  3 04:23:53 2007
    From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
    Date: Tue, 03 Jul 2007 10:23:53 +0200
    Subject: Programming Idiomatic Code
    In-Reply-To: 
    References: 
    Message-ID: <468a0768$0$14120$426a74cc@news.free.fr>
    
    Nathan Harmston a ?crit :
    > Hi,
    > 
    > I m sorry but I m bored at work (and no ones looking so I can write
    > some Python) and following a job advertisement post,I decided to write
    > the code to do its for the one entitled Ninjas or something like that.
    > I was wondering what could be done to my following code to make it
    > more idiomatic...or whether it was idiomatic and to be honest what
    > idiomatic really means. All comments greatly appreciated and welcomed.
    > 
    > Thanks in advance
    > 
    > Nathan
    > 
    > import urllib2,sys
    > from elementtree.ElementTree import parse
    > 
    > base_url = "http://api.etsy.com/feeds/xml_user_details.php?id="
    
    Using a module global for this kind of data is usually a bad idea 
    (except eventually for run-once throw-away scripts, and even then...)
    
    > def read_id_file(filename):
    >    """ reads a file and generates a list of ids from it"""
    >    ids = [ ]
    >    try:
    >     id_file = open(filename, "r")
    >     for l in id_file:
    >            ids.append( l.strip("\n") )
    >     id_file.close()
    
    Python has other idioms for this (list comprehensions etc).
    
    
    >    except e:
    >        print e
    >        os._exit(99)
    
    This is a very bad way to handle exceptions.
    1/ you use a catch-all except clause, when you should be specific about 
    what kind of exceptions you are willing to handle here
    2/ names starting with an underscore are not part of the API. You should 
    not use them unless you have a *very* compelling reason to do so.
    3/ stdout is for normal outputs. Error messages and such should go to stderr
    3/ anyway, if it's for printing the exception then exit, you'd better 
    not handle anything - you'd have a similar result, but with a full 
    traceback.
    
    >    return ids
    
    def read_id_file(filename):
       try:
         f = open(filename)
       except IOError, e:
         print >> sys.stderr, \
           "failed to open %s for reading : %s" \
            % (filename, e)
         return None
       else:
         ids = [l.strip() for l in f]
         f.close()
         return ids
    
    
    > def generate_count(id_list):
    >    """ takes a list of ids and returns a dictionary of cities with
    > associated counts"""
    >    city_count = {}
    >    for i in id_list:
    >        url = "%s%s" %(base_url,i)
    
    base_url should be passed in as an argument.
    
    >     req = urllib2.Request(url)
    
    I assume there's a problem with indentation here...
    
    >     try:
    >            xml = parse(urllib2.urlopen(url)).getroot()
    >            city  = xml.findtext('user/city')
    >     except e:
    >            print e.reason
    >            os._exit(99)
    
    cf above
    
    >     try:
    >            city_count[city] += 1
    >        except:
    
    should be 'except KeyError:'
    
    >            city_count[city] = 1
    
    This idiom is appropriate if you expect few exceptions - that is, if the 
    normal case is that city_count.has_key(city) == True. Else, you'd better 
    use an explicit test, a defaultdict, etc. The idiomatic expliciti test 
    would be:
    
           if city not in city_count:
             city_count['city'] = 1
           else:
              city_count[city] += 1
    
    
    >    return city_count
    > 
    > if __name__=='__main__':
    >    if len(sys.argv) is 1:
    
    'is' is the identity operator. *Never* use it for numeric equality test. 
    This should be:
          if len(sys.argv) == 1:
    
    >        id_list = [ 42346, 77290, 729 ]
    >    else:
    >        try: id_list = read_id_file(sys.argv[1])
    >        except e: print e
    
    cf above about exception handling.
    
    And FWIW, here, I would have used a try/except :
    
        try:
          filename = sys.argv[1]
        except IndexError:
          id_list = [1, 2, 3]
          print >> sys.stderr, \
            "no id file passed, using default id_list %" % id_list
        else:
          print >> sys.stderr, \
            "reading id_list from id_file %s" % filename
          id_list = read_if_file(filename)
    
        if not id_list:
          sys.exit(1)
    
    >    for k, v in generate_count(id_list).items():
    >        print "%s: %i" %(k, v)
    
    There's a simpler way:
    
          for item in generate_count(id_list).iteritems():
              print "%s: %i" % item
    
    
    From murali.dhanakoti at gmail.com  Wed Jul 18 19:57:48 2007
    From: murali.dhanakoti at gmail.com (Murali)
    Date: Wed, 18 Jul 2007 23:57:48 -0000
    Subject: Interprocess communication
    Message-ID: <1184803068.201801.14160@x40g2000prg.googlegroups.com>
    
    Hi Python Gurus,
    
    I am writing a GUI app (on linux) using pygtk which would launch some
    external applications and display their stdout and stderr inside the
    output window of my application synchronously. I am using the
    subprocess module's Popen to launch the external programs and to
    capture their stdout and stderr. The problem is that, for some
    external programs that I launch inside my interface, I am not able to
    capture and display the stdout as the program *runs*.
    
    After some investigation, I found out that this problem had nothing to
    do with my GUI app not getting refreshed and I was able to reproduce
    this problem with normal python scripts. Here is one such script
    
    #File test.py
    from subprocess import Popen
    from subprocess import PIPE
    import sys
    if __name__ == '__main__':
      prog = sys.argv[1]
      proc = Popen(prog, shell = True, stdout = PIPE, bufsize = 0)
      out = proc.stdout
      while proc.poll() is None:
        print out.readline()
    
    Run this program as follows
    $ test.py "ping -c 10 www.google.com"
    
    Now, you would see the responses as if you just launched ping on the
    command line. Now, lets look at another program. Here is a simple C++
    program that prints numbers 1 to 10 at the passage of every second
    (sort of a stopwatch)
    
    #include 
    #include 
    #include 
    main ( )
    {
      timeval t1, t2;
      gettimeofday(&t1, NULL);
      int prev = -1;
      int cur = 0;
      while (true)
      {
        gettimeofday(&t2,NULL);
        if(t2.tv_sec - t1.tv_sec > 10)
          break;
        else
        {
          cur = t2.tv_sec-t1.tv_sec;
          if (cur != prev)
          {
            printf("%d\r\n",cur);
            prev = cur;
          }
        }
      }
    }
    
    if you would build this program and call it lets say timer ($ g++ -o
    timer timer.cpp)  and run it with our python script like this
    
    $python test.py "./timer"
    
    you would see that every time you run the program your results vary
    and on top of this the stdout of the timer program gets displayed all
    at once presumably when the timer program has completed execution.
    
    Why this discrepancy between the ping and timer programs? Is my
    test.py script correct? Is there a better or a preferred method for
    doing interprocess communication in Python.
    
    Thanks!
    Murali.
    
    
    
    From steve at holdenweb.com  Fri Jul  6 20:18:23 2007
    From: steve at holdenweb.com (Steve Holden)
    Date: Fri, 06 Jul 2007 20:18:23 -0400
    Subject: Repeating Thread Error
    In-Reply-To: <1183758016.776354.241620@g4g2000hsf.googlegroups.com>
    References: <1183758016.776354.241620@g4g2000hsf.googlegroups.com>
    Message-ID: 
    
    Jonathan Shan wrote:
    > Hello,
    > 
    > I am trying to call a function every 5 seconds. My understanding of
    > time.sleep() is during the sleep time everything "stops". However, in
    > my application, there are background processes that must be running
    > continuously during the five second interval. Thus, threading.Timer
    > seems like a good function. Here is the relevant code:
    > 
    > # background processes
    > t = threading.Timer(5.0, function_name, [arguments])
    > while True:
    >      # Do background processes run inside while loop?
    >      t.start()
    > 
    > The above code generates an error:
    > AssertionError: thread already started
    > 
    > Any hints on how to fix the error? Also, do background processes run
    > inside while loops?
    > 
    > Thanks in advance,
    > Jonathan Shan
    > 
    Here's a little thread-test program I wrote a few years ago. I hope it 
    will explain how threads and sleeps interact.
    
    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 embedded and charset-unspecified text was scrubbed...
    Name: threadtest.py
    URL: 
    
    From stefan.behnel-n05pAM at web.de  Fri Jul  6 11:30:35 2007
    From: stefan.behnel-n05pAM at web.de (Stefan Behnel)
    Date: Fri, 06 Jul 2007 17:30:35 +0200
    Subject: Auto-parallelizing with decorators?
    In-Reply-To: 
    References: 
    Message-ID: <468E601B.3020008@web.de>
    
    Kirk Strauser wrote:
    > Suppose that Python had a new decorator, say "@parallelizable".  Functions
    > so decorated would be eligible for multi-processed or multi-threaded
    > execution by such native constructs as list comprehensions, or the map()
    > function.
    
    Wouldn't that require parallelism in the interpreter first? Mind the GIL...
    
    Stefan
    
    
    From dw at botanicus.net  Sat Jul 28 19:34:58 2007
    From: dw at botanicus.net (David Wilson)
    Date: Sun, 29 Jul 2007 00:34:58 +0100
    Subject: Events: The Python Way
    In-Reply-To: 
    References: 
    Message-ID: <98edab2e0707281634q532284e0t5e6f6a2d3dfa58b4@mail.gmail.com>
    
    Hi there,
    
    Python has no built-in way of doing this. You may consider writing
    your own class if you like this pattern (I personally do):
    
    class Event(object):
        def __init__(self):
            self.subscribers = set()
    
        def __iadd__(self, subscriber):
            self.subscribers.add(subscriber)
            return self
    
        def __isub__(self, subscriber):
            self.subscribers.pop(subscriber)
            return self
    
        def __call__(self, *args, **kwargs):
            for subscriber in self.subscribers:
                subscriber(*args, **kwargs)
    
    
    def HandleFoo(strng):
        print "HandleFoo:", strng
    
    OnFoo = Event()
    OnFoo += HandleFoo
    
    OnFoo("Test.")
    
    
    On 29/07/07, Gianmaria  wrote:
    > Hi,
    > i'm a .net programmer and i'm learnig python, so this question can be very
    > stupid or easy for python programmers. I've a doubt about events.... here is
    > what:
    >
    > in c# for example i can write a delegate and an event in this way...
    >
    > public delegate SomethingChangedHandler(string message);
    > public event SomethingChangedHandler SomethingChanged;
    >
    > and later in the code fire this event in this way...
    >
    > if(SomethingChanged != null)
    > {
    >     SomethingChanged("Nothing important");
    > }
    >
    > and the subscription of this event of other objects can be easy as
    >
    > eventGeneratorObject.SomethingChanged += new
    > SomethingChangedHandler(aFunctionto_takecareof_it);
    >
    > and even the handlig of the event is aesy...
    >
    > void aFunctionto_takecareof_it(string msg)
    > {
    >
    > }
    >
    >
    > ....now the question is.. how can i do the same using Python? Every help is
    > appreciated
    >
    >
    >
    >
    >
    > Regards,
    > Gianmaria
    >
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >
    
    
    From jeremy.lynch at gmail.com  Thu Jul 12 11:23:31 2007
    From: jeremy.lynch at gmail.com (Jeremy Lynch)
    Date: Thu, 12 Jul 2007 15:23:31 -0000
    Subject: Lists in classes
    Message-ID: <1184253811.052346.220470@22g2000hsm.googlegroups.com>
    
    Hello,
    
    Learning python from a c++ background. Very confused about this:
    
    ============
    class jeremy:
    	list=[]
    		def additem(self):
    		self.list.append("hi")
    		return
    
    temp = jeremy()
    temp.additem()
    temp.additem()
    print temp.list
    
    temp2 = jeremy()
    print temp2.list
    ==============
    The output gives:
    ['hi','hi']
    ['hi','hi']
    
    Why does adding items to one instance produce items in a separate
    instance? Doesn't each instance of jeremy have its' own "list"?
    
    Many thanks for clearing up this newbie confusion.
    
    Jeremy.
    
    
    
    From roy at panix.com  Wed Jul  4 10:01:53 2007
    From: roy at panix.com (Roy Smith)
    Date: Wed, 04 Jul 2007 10:01:53 -0400
    Subject: PEP 3107 and stronger typing (note: probably a newbie question)
    References: 
    	<1182369568.941307.316260@p77g2000hsh.googlegroups.com>
    	
    	<5dveb4F360un0U1@mid.individual.net>
    	
    	<467a9209$0$22165$426a74cc@news.free.fr>
    	<1182858785.886469.93060@n60g2000hse.googlegroups.com>
    	<46824d8d$0$2324$426a74cc@news.free.fr>
    	
    	<4682eddc$0$23164$426a74cc@news.free.fr>
    	<5ehokpF38ov3jU2@mid.individual.net>
    	<4683d5cd$0$8993$426a74cc@news.free.fr>
    	<7xps3e3g9x.fsf@ruckus.brouhaha.com>
    	<468565a0$0$3686$426a74cc@news.free.fr>
    	<7xhcopj10g.fsf@ruckus.brouhaha.com>
    	<46863ea7$0$970$426a34cc@news.free.fr>
    	<1i0ikru.1uccqtm1efnzn3N%aleax@mac.com>
    	
    	<1i0n0tr.ve0o791347ugyN%aleax@mac.com>
    	<7xd4za1086.fsf@ruckus.brouhaha.com>
    	<5f0mhuF3b0stbU1@mid.individual.net>
    Message-ID: 
    
    greg  wrote:
    
    > Paul Rubin wrote:
    > > E.g. your program might pass its test and run properly for years
    > > before some weird piece of input data causes some regexp to not quite
    > > work.
    > 
    > Then you get a bug report, you fix it, and you add a test
    > for it so that particular bug can't happen again.
    
    The TDD zealots would tell you you've got the order wrong.  Instead of 
    "fix, then write a test", it should be "write a failing test, then fix it".
    
    
    From stefan.behnel-n05pAM at web.de  Tue Jul 24 11:21:13 2007
    From: stefan.behnel-n05pAM at web.de (Stefan Behnel)
    Date: Tue, 24 Jul 2007 17:21:13 +0200
    Subject: Parsing XML with ElementTree (unicode problem?)
    In-Reply-To: <1185287404.060182.314750@57g2000hsv.googlegroups.com>
    References: <1185200976.082516.105420@57g2000hsv.googlegroups.com>
    	<1185279975.254458.7510@57g2000hsv.googlegroups.com>
    	<1185287404.060182.314750@57g2000hsv.googlegroups.com>
    Message-ID: <46A618E9.6010304@web.de>
    
    oren.tsur at gmail.com wrote:
    >> How about trying
    >> root = ElementTree.parse(urlopen(query), encoding ='utf-8')
    
    That doesn't work.
    
    
    > this specific thing is not working, however, parsing the url is not
    > problematic.
    
    So you tried parsing the complete XML file and it works? Then it's the way you
    stripped it down to the interesting parts that broke it. Not ElementTree's fault.
    
    
    > the problem is that after parsing the xml at the url I
    > save some of the fields to a local file and the local file is not
    > being parsed properly due to the non-ascii characters Sauni\xc3\xa8re
    > (french name: Sauni?re).
    
    That looks like it parsed UTF-8 as some single byte encoding, such as
    iso-8859-1. Check if the file you saved retained the XML declaration
    
      
    
    
    > I'm quite new to xml and python so I guess there must be something
    > wrong or dumb in the way I save the file (maybe I miss some important
    > tags?) or in the way I re-open it but I can't find whats wrong.
    
    As I said, try to read the interesting portions of the XML file
    programmatically (especially if you want to do it more than once), or use an
    editor that supports UTF-8 and/or XML when you edit it (i.e.: use an editor).
    Make sure the XML file is well-formed (use e.g. xmllint) when you're save it.
    Otherwise, no XML parser will accept it.
    
    Stefan
    
    
    From http  Tue Jul 17 11:58:08 2007
    From: http (Paul Rubin)
    Date: 17 Jul 2007 08:58:08 -0700
    Subject: Can a low-level programmer learn OOP?
    References:  
    	
    	<7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com>
    	
    Message-ID: <7xy7hfyqcv.fsf@ruckus.brouhaha.com>
    
    aahz at pythoncraft.com (Aahz) writes:
    > .So adding SNOBOL patterns to another library would be a wonderful
    > gift to the Python community...
    
    Snobol patterns were invented at a time when nobody knew anything
    about parsing.  They were extremely powerful (recursive with arbitrary
    amounts of backtracking) but could use exponential time and maybe even
    exponential space.
    
    These days, it makes more sense to use something like pyparsing.  Or I
    wonder if it would be feasible to write something like Parsec for
    Python (Parsec is a parser combinator library for Haskell).
    
    
    From fdu.xiaojf at gmail.com  Fri Jul 27 04:57:24 2007
    From: fdu.xiaojf at gmail.com (fdu.xiaojf at gmail.com)
    Date: Fri, 27 Jul 2007 16:57:24 +0800
    Subject: Compile python with Mingw
    Message-ID: <46A9B374.8090607@gmail.com>
    
    Hi all,
    
    
    I was trying to build pymol with mingw on my windows box, but during the
    compilation it said that my python.exe was built with VS2003, and in
    order to build compatible binary executable file, I have to build pymol
    with VS2003. I don't have VS2003, so I think I may compile both pymol
    and python with mingw.
    
    Can somebody give me some hints on how to build python with mingw? I
    have googled the web, and it seems that few people have tried mingw
    with python. I have found mingwpython, but it's not for python 2.5.
    
    Thanks.
    
    
    From stugots at qwest.net  Sat Jul 28 11:48:10 2007
    From: stugots at qwest.net (John DeRosa)
    Date: Sat, 28 Jul 2007 08:48:10 -0700
    Subject: 128 or 96 bit integer types?
    References: <1185554705.320673.78500@q75g2000hsh.googlegroups.com>
    	
    	<1185562901.206212.52570@j4g2000prf.googlegroups.com>
    	
    	<1185607142.096574.209200@e16g2000pri.googlegroups.com>
    Message-ID: <37pma35qhpca41cvgjfrdkdoru27rgml9s@4ax.com>
    
    On Sat, 28 Jul 2007 00:19:02 -0700, "mensanator at aol.com"
     wrote:
    
    >For example, how many ways can you put 492 marbles into
    >264 ordered bins such that each bin has at least 1 marble?
    >
    >The answer
    >
    >66189415264331559482776409694993032407028709677550
    >59629130019289014193777349831417543311612293951363
    >4124491233746912456893016976209252459301489030
    
    You missed that blue one in the corner...
    
    
    From stefan.behnel-n05pAM at web.de  Sat Jul 28 17:59:11 2007
    From: stefan.behnel-n05pAM at web.de (Stefan Behnel)
    Date: Sat, 28 Jul 2007 23:59:11 +0200
    Subject: Any reason why cStringIO in 2.5 behaves different from 2.4?
    In-Reply-To: <0T49ish0ItfaNv8%stesch@parsec.no-spoon.de>
    References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de>
    	<0T49cr71I3edNv8%stesch@parsec.no-spoon.de>
    	<46A8AA57.4010802@web.de>
    	<0T49dll7I4ilNv8%stesch@parsec.no-spoon.de>
    	
    	<0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de>
    	
    	<0T49iehiIt1hNv8%stesch@parsec.no-spoon.de>
    	<46AB8194.2060906@web.de>
    	<0T49il77ItapNv8%stesch@parsec.no-spoon.de>
    	
    	<0T49ish0ItfaNv8%stesch@parsec.no-spoon.de>
    Message-ID: <46ABBC2F.7030906@web.de>
    
    Stefan Scholl wrote:
    > Chris Mellon  wrote:
    >> On 7/28/07, Stefan Scholl  wrote:
    >>> Just checked on a system without PyXML: xml/sax/__init__.py
    >>> defines parseString() and uses cStringIO (when available).
    >>>
    >>> Python 2.5.1
    >>>
    >> Yes, thats the fixed bug. After all this you still do not seem to be
    >> clear on what the bug is. The bug is not that your code fails in 2.5,
    >> it's that it worked at all in 2.4.
    > 
    > Don't let the subject line fool you. I'm OK with cStringIO. The
    > thread is now about xml.sax's parseString().
    
    ... which works correctly with Python 2.5 and was broken before.
    
    Stefan
    
    
    From slianoglou at gmail.com  Mon Jul  2 20:42:16 2007
    From: slianoglou at gmail.com (Steve Lianoglou)
    Date: Mon, 02 Jul 2007 17:42:16 -0700
    Subject: Programming Idiomatic Code
    In-Reply-To: 
    References: 
    Message-ID: <1183423336.272958.99830@q69g2000hsb.googlegroups.com>
    
    I don't know about idiomatic, but here's a quick list of somethings
    I'd change.
    
    1) In general, I don't think it's a good idea for a called function to
    blow out the system on error. So, in this example, I wouldn't have
    raised errors be caught in the same function only to call os.exit. I'd
    either deal with the exception in some sane way, or have it bubble up
    to the caller to have it then decide what it should do in the face of
    the error.
    
    
    > def read_id_file(filename):
    >     """ reads a file and generates a list of ids from it"""
    >     ids = [ ]
    >     try:
    >         id_file = open(filename, "r")
    >         for l in id_file:
    >             ids.append( l.strip("\n") )
    >         id_file.close()
    >     except e:
    >         print e
    >         os._exit(99)
    >     return ids
    
    Maybe use a list comprehension here (try/except clauses excluded in
    reference to previous comment @ top)
    
    def read_id_file(filename):
        id_file = open(filename, 'r')
        ids = [line.strip() for line in id_file.xreadlines()]
        id_file.close()
        return ids
    
    If you're shooting for only Python 2.5, you can use ``with`` (see
    http://docs.python.org/tut/node10.html#cleanup-with) to make that even
    more concise.
    
    
    > def generate_count(id_list):
    >     """ takes a list of ids and returns a dictionary of cities with
    > associated counts"""
    >     city_count = {}
    >     for i in id_list:
    >         url = "%s%s" %(base_url,i)
    >         req = urllib2.Request(url)
    >         try:
    >             xml = parse(urllib2.urlopen(url)).getroot()
    >             city  = xml.findtext('user/city')
    >         except e:
    >             print e.reason
    >             os._exit(99)
    >         try:
    >             city_count[city] += 1
    >         except:
    >             city_count[city] = 1
    >     return city_count
    
    I maybe wouldn't bail on the error raised when the ``parse`` function
    is called ... I'd rather skip the error and try the next one (but
    that's just my preference, not sure if it's good/bad style)
    
    Also, instead of doing this:
    
    > try:
    >    city_count[city] += 1
    > except:
    >    city_count[city] = 1
    
    I like using the dict.get() methods ... which would make that a one
    liner:
    
    city_count[city] = city_count.get(city, 0) + 1
    
    Now I gotta get back to work, too ... good luck getting that job! ;-)
    
    -steve
    
    
    
    From andre.roberge at gmail.com  Fri Jul 27 17:13:16 2007
    From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=)
    Date: Fri, 27 Jul 2007 21:13:16 -0000
    Subject: Is access to locals() of "parent" namespace possible?
    In-Reply-To: 
    References: <1185569180.544092.283620@57g2000hsv.googlegroups.com>
    	
    Message-ID: <1185570796.534189.10330@57g2000hsv.googlegroups.com>
    
    On Jul 27, 6:01 pm, Carsten Haese  wrote:
    > On Fri, 2007-07-27 at 20:46 +0000, Andr? wrote:
    > > I want to give a user the possibility of "restarting" an interactive
    > > session, by removing all the objects defined by her since the
    > > beginning.  The way I make this possible is by having a "function"
    > > that can be called during the interactive session using locals() as an
    > > argument, as follows:
    >
    > > restart(locals())
    >
    > > It works.  However, I would like to make this "friendlier", i.e.
    > > requiring the user to simply type
    >
    > > restart()
    >
    > > and have the code extract out the value of locals() of the "parent"
    > > namespace.  I thought it might be possible using sys._getframe, but I
    > > have not been able to figure out why.
    >
    > inspect.currentframe(1).f_locals
    >
    > The same caveats for locals() apply here: Modifications to this
    > dictionary may or may not be visible to the caller.
    >
    > HTH,
    >
    > --
    > Carsten Haesehttp://informixdb.sourceforge.net
    
    Thanks, it worked!
    
    Andr?
    
    
    
    From deets at nospam.web.de  Thu Jul  5 02:51:47 2007
    From: deets at nospam.web.de (Diez B. Roggisch)
    Date: Thu, 05 Jul 2007 08:51:47 +0200
    Subject: IDEs for COM scripting: C# v. Python v. Iron Python v. JPython
    In-Reply-To: 
    References: 
    Message-ID: <5f3io9F39m37cU1@mid.uni-berlin.de>
    
    Siegfried Heintze schrieb:
    > I love the typing assist I get when using C# in VS2005 to write COM clients.
    > 
    > I need to write a program to automate some tasks in outlook. Givin that the 
    > typing assist feature is very important to me, what would be the best 
    > combination of IDE and language for COM scripting?
    > 
    > I was experimenting with Groovy and Eclipse and was extremely pleased to 
    > discover that I get the typing assist with that combination. However, I'm 
    > getting an accvio with a minimal outlook COM client. I hear great things 
    > about Iron Python: is there a good IDE for it that has a typing assist?
    
    You won't get it in python. Python has no type declarations, thus the 
    IDE has no idea what type a name points to. This is true for IronPython 
    as well.
    
    There are some other aids - for example eric (a python editor written in 
    python, using Qt) will have API-files generated that at least let you 
    choose the name of a method/property after you typed the first character.
    
    
    But you should still try and see how productive one is in python. I'm 
    working in a Java shop, with eclipse - one of the most intimate 
    IDE-language-relationships imaginable. I get all the auto-completion, 
    refactoring and whatnot-support.
    
    And I'd swap it for python + emacs every minute.
    
    Diez
    
    
    From bronger at physik.rwth-aachen.de  Mon Jul 16 09:43:38 2007
    From: bronger at physik.rwth-aachen.de (Torsten Bronger)
    Date: Mon, 16 Jul 2007 15:43:38 +0200
    Subject: Trouble with email package
    Message-ID: <87r6n8foqd.fsf@wilson.homeunix.com>
    
    Hall?chen!
    
    I thought that with the following code snippet, I could generate a
    MIME email stub:
    
        #!/usr/bin/env python
        # -*- coding: utf-8 -*-
        from email.MIMEText import MIMEText
        from email.Generator import Generator
        import sys
    
        message = MIMEText(u"Hall?chen!", _charset="utf-8")
        Generator(sys.stdout).flatten(message)
    
    However, MIMEText doesn't see that u"Hall?chen!" is a unicode and
    encodes it accoring to _charset.  Additionally, it is encoded as
    base64 (why?).  But okay, I added some lines to work around it:
    
        #!/usr/bin/env python
        # -*- coding: utf-8 -*-
        from email.MIMEText import MIMEText
        from email.Generator import Generator
        from email.Charset import Charset
        import sys
    
        charset = Charset("utf-8")
        charset.body_encoding = None
        message = MIMEText(u"Hall?chen!".encode("utf-8"), _charset="utf-8")
        message.set_charset(charset)
        Generator(sys.stdout).flatten(message)
    
    However, the result of this is
    
        Content-Type: text/plain; charset="utf-8"
        MIME-Version: 1.0
        Content-Transfer-Encoding: base64
    
        Hall?chen!
    
    The Content-Transfer-Encoding is wrong.  Okay (well, not okay but)
    then I added message["Content-Transfer-Encoding"] = "8bit" to my
    code and got
    
        Content-Type: text/plain; charset="utf-8"
        MIME-Version: 1.0
        Content-Transfer-Encoding: base64
        Content-Transfer-Encoding: 8bit
    
        Hall?chen!
    
    I mean, I can work around anything, but is the email package just
    rather buggy or do I something completely misguided here?  Thanks
    for any hints!
    
    Tsch?,
    Torsten.
    
    -- 
    Torsten Bronger, aquisgrana, europa vetus
                                          Jabber ID: bronger at jabber.org
                          (See http://ime.webhop.org for ICQ, MSN, etc.)
    
    
    From Dave.Baum at motorola.com  Wed Jul 11 15:07:32 2007
    From: Dave.Baum at motorola.com (Dave Baum)
    Date: Wed, 11 Jul 2007 14:07:32 -0500
    Subject: Tuple vs List: Whats the difference?
    References: <1184177195.569916.184770@22g2000hsm.googlegroups.com>
    Message-ID: 
    
    In article <1184177195.569916.184770 at 22g2000hsm.googlegroups.com>,
     Shafik  wrote:
    
    > Hello folks,
    > 
    > I am an experienced programmer, but very new to python (2 days). I
    > wanted to ask: what exactly is the difference between a tuple and a
    > list? I'm sure there are some, but I can't seem to find a situation
    > where I can use one but not the other.
    
    Lists and tuples are both sequences, and can be used interchangeably in 
    many situations.  The big difference is that lists are mutable (can be 
    modified), and tuples are immutable (cannot be modified).  Lists also 
    have a richer API (for example the index and count methods).
    
    If you are going to need to change the contents of the sequence 
    (appending, removing, altering a value, etc), then use a list.
    
    If you require the sequence to be immutable (such as being used as the 
    key in a dictionary), then use a tuple.
    
    In general, tuples should be a little more efficient than lists.  
    However, altering a list is more efficient than creating a new tuple, so 
    "always prefer tuples" does not necessarily lead to a faster overall 
    program.  Unless performance is critical, I wouldn't worry about this 
    factor.
    
    IMHO, a more important reason to prefer tuples is that since they are 
    immutable, you don't have to worry about side effects.  If you call a 
    function and pass it a list, you have no guarantee that the list won't 
    be changed during the function call.  With tuples, any attempt to change 
    the tuple will raise an exception.  If it is important to the caller 
    that the sequence remain unchanged, then a tuple is a safer 
    representation for that sequence.
    
    Dave
    
    
    From aleax at mac.com  Wed Jul  4 11:32:06 2007
    From: aleax at mac.com (Alex Martelli)
    Date: Wed, 4 Jul 2007 08:32:06 -0700
    Subject: PEP 3107 and stronger typing (note: probably a newbie question)
    References: <1182369568.941307.316260@p77g2000hsh.googlegroups.com>
    	
    	<5dveb4F360un0U1@mid.individual.net>
    	
    	<467a9209$0$22165$426a74cc@news.free.fr>
    	<1182858785.886469.93060@n60g2000hse.googlegroups.com>
    	<46824d8d$0$2324$426a74cc@news.free.fr>
    	
    	<4682eddc$0$23164$426a74cc@news.free.fr>
    	<5ehokpF38ov3jU2@mid.individual.net>
    	<4683d5cd$0$8993$426a74cc@news.free.fr>
    	<7xps3e3g9x.fsf@ruckus.brouhaha.com>
    	<468565a0$0$3686$426a74cc@news.free.fr>
    	<7xhcopj10g.fsf@ruckus.brouhaha.com>
    	<46863ea7$0$970$426a34cc@news.free.fr>
    	<1i0ikru.1uccqtm1efnzn3N%aleax@mac.com>
    	
    	<1i0n0tr.ve0o791347ugyN%aleax@mac.com>
    	<7xd4za1086.fsf@ruckus.brouhaha.com>
    	<5f0mhuF3b0stbU1@mid.individual.net>
    	
    Message-ID: <1i0pvsz.14gonhq4lhtf4N%aleax@mac.com>
    
    Roy Smith  wrote:
    
    > greg  wrote:
    > 
    > > Paul Rubin wrote:
    > > > E.g. your program might pass its test and run properly for years
    > > > before some weird piece of input data causes some regexp to not quite
    > > > work.
    > > 
    > > Then you get a bug report, you fix it, and you add a test
    > > for it so that particular bug can't happen again.
    > 
    > The TDD zealots would tell you you've got the order wrong.  Instead of
    > "fix, then write a test", it should be "write a failing test, then fix it".
    
    Incidentally, I was pretty surprised recently (re-reading Weinberg's
    "Psychology of Computer Programming" classic from _1971_) to find out
    Weinberg advocating "test-first coding" (not the same thing as
    "test-driven design", but sharing the key insight that tests should be
    written before the code they test) for psychological reasons. He's
    discussing common practices of the '60s, with the same professional
    writing both the code and the tests, and pointing out how often the
    knowledge of the already-written code subconsciously influences the
    programmer to write tests that don't really "challenge" the code enough
    -- writing the tests "in advance" would avoid this problem.
    
    Nihil sub sole novi...
    
    
    Alex
    
    
    From nagle at animats.com  Wed Jul  4 15:25:33 2007
    From: nagle at animats.com (John Nagle)
    Date: Wed, 04 Jul 2007 12:25:33 -0700
    Subject: PEP 3107 and stronger typing (note: probably a newbie question)
    In-Reply-To: <1183575597.272150.152200@w5g2000hsg.googlegroups.com>
    References: <5dveb4F360un0U1@mid.individual.net>
    	
    	<1182858785.886469.93060@n60g2000hse.googlegroups.com>
    	<46824d8d$0$2324$426a74cc@news.free.fr>
    	
    	<4682eddc$0$23164$426a74cc@news.free.fr>
    	<5ehokpF38ov3jU2@mid.individual.net>
    	<4683d5cd$0$8993$426a74cc@news.free.fr>
    	<7xps3e3g9x.fsf@ruckus.brouhaha.com>
    	<468565a0$0$3686$426a74cc@news.free.fr>
    	<7xhcopj10g.fsf@ruckus.brouhaha.com>
    	<46863ea7$0$970$426a34cc@news.free.fr>
    	<1i0ikru.1uccqtm1efnzn3N%aleax@mac.com>
    	
    	<1i0n0tr.ve0o791347ugyN%aleax@mac.com>
    	<7xd4za1086.fsf@ruckus.brouhaha.com>
    	<5f0mhuF3b0stbU1@mid.individual.net>
    	<7xd4z837e2.fsf@ruckus.brouhaha.com>
    	<468b7426$0$9063$426a34cc@news.free.fr>
    	<7x4pkkun56.fsf@ruckus.brouhaha.com>
    	<1183575597.272150.152200@w5g2000hsg.googlegroups.com>
    Message-ID: 
    
    Paul Boddie wrote:
    > Paul Rubin wrote:
    > 
    > The campaign for optional
    > static typing in Python rapidly became bogged down in this matter,
    > fearing that any resulting specification for type information might
    > not be the right combination of flexible and powerful to fit in with
    > the rest of the language, and that's how we really ended up with PEP
    > 3107: make the semantics vague and pretend it has nothing to do with
    > types, thus avoiding the issue completely.
    
         Unfortunately, that may lead to the worst of both worlds.
    
         If you think enforced static typing is painful, try maintaining code with
    non-enforced static typing.  You can't rely on the type information, and
    inevitably some of it will be wrong.  You can't tell by looking which
    is wrong, of course.
    
         This has been tried.  Original K&R C had non-enforced static typing.
    All "struct" pointers were equivalent.  It wasn't pretty.
    
         It takes strict programmer discipline to make non-enforced static
    typing work.  I've seen it work in an aerospace company, but the Python
    crowd probably doesn't want that level of engineering discipline.
    Non-enforced static typing requires a quality assurance group that
    reads code and checks coding standards.
    
    				John Nagle
    
    
    From adrian_p_smith at yahoo.com  Tue Jul  3 09:43:59 2007
    From: adrian_p_smith at yahoo.com (Adrian Smith)
    Date: Tue, 03 Jul 2007 06:43:59 -0700
    Subject: mysteries of urllib/urllib2
    Message-ID: <1183470239.153444.244700@j4g2000prf.googlegroups.com>
    
    I'm trying to use urllib2 to download a page (I'd rather use urllib,
    but I need to change the User-Agent header to look like a browser or
    G**gle won't send it to me, the big meanies). The following (pinched
    from Dive Into Python) seems to work perfectly in Idle, but falls at
    the final hurdle when run as a cgi script - can anyone suggest
    anything I may have overlooked?
    
    request = urllib2.Request(some_URL)
    request.add_header('User-Agent', 'some_plausible_string')
    opener = urllib2.build_opener()
    data = opener.open(request).read()
    
    
    
    From http  Tue Jul 10 14:17:46 2007
    From: http (Paul Rubin)
    Date: 10 Jul 2007 11:17:46 -0700
    Subject: C Extension Seg Faults
    References: <1184090600.764290.160210@d30g2000prg.googlegroups.com>
    Message-ID: <7x7ip8gm2d.fsf@ruckus.brouhaha.com>
    
    Daryl  writes:
    > The inner loop runs a few hundred times (263) then fails with a
    > segmentation fault.  I've trolled through the documentation online and
    > in the various .h files but can't seem to find anything.
    > 
    > Anybody have an idea what really obvious foolish thing I'm doing?
    
    It's not worth staring at code to try to figure out things like that.
    Run it under gdb, examine the relevant data objects when it crashes
    and see what's broken (e.g. some pointer is unexpectedly null), then
    set a conditional breakpoint that stops execution when that incorrect
    condition happens (e.g. the pointer gets set to null), run the program
    til the breakpoint triggers, see what other condition X caused the
    condition that caused the crash, set another breakpoint that triggers
    when X occurs, etc.  Work backwards systematically til you find the bug.
    
    
    
    From bj_666 at gmx.net  Wed Jul 11 10:04:04 2007
    From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch)
    Date: 11 Jul 2007 14:04:04 GMT
    Subject: bool behavior in Python 3000?
    References:  
    	
    	
    	
    	
    	<7xodijdd8r.fsf@ruckus.brouhaha.com>
    	
    	<1184139458.063988.63510@w3g2000hsg.googlegroups.com>
    Message-ID: <5fk6ajF3cu82eU1@mid.uni-berlin.de>
    
    On Wed, 11 Jul 2007 00:37:38 -0700, Rob Wolfe wrote:
    
    > Steven D'Aprano wrote:
    > 
    >> From a purely functional perspective, bools are unnecessary in Python. I
    >> think of True and False as syntactic sugar. But they shouldn't be
    >> syntactic sugar for 1 and 0 any more than they should be syntactic sugar
    >> for {"x": "foo"} and {}.
    > 
    > But `bools` are usefull in some contexts. Consider this:
    > 
    >>>> 1 == 1
    > True
    >>>> cmp(1, 1)
    > 0
    >>>> 1 == 2
    > False
    >>>> cmp(1, 2)
    > -1
    > 
    > At first look you can see that `cmp` does not return boolean value
    > what not for all newbies is so obvious.
    
    Sorry I fail to see your point!?  What has ``==`` to do with `cmp()` here?
    The return of `cmp()` is an integer that cannot and should not be seen as
    boolean value.
    
    Ciao,
    	Marc 'BlackJack' Rintsch
    
    
    From gagsl-py2 at yahoo.com.ar  Thu Jul  5 02:41:32 2007
    From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
    Date: Thu, 05 Jul 2007 03:41:32 -0300
    Subject: connecting to serial port + python
    References: <1183467711.963266.137590@m37g2000prh.googlegroups.com>
    Message-ID: 
    
    En Tue, 03 Jul 2007 10:01:51 -0300, Japan Shah   
    escribi?:
    
    > I am trying to connect my Nokia 6610 using usb cable,
    > I have installed usb-serial driver of it.
    > I hv tested it with Hyperterminal and it works fine.
    > but when I wrote a python script I am not able to receive the responce
    > from the device.
    >
    
    >            lines = self.sock.read(100)
    If the response contains less than 100 bytes, the above line will block.
    
    > command = ['AT','ATI','ATl1','AT+GMMM']
    >
    > for cmd in command:
    >    conn1.write(str(cmd))
    
    Don't you have to send  after each command? "\n"
    
    >    th = connect_serial(conn1)
    >    list1.append(th)
    >    th.start()
    
    You can't have four threads all reading the same serial port. The device  
    sends its responses sequentially anyway.
    
    -- 
    Gabriel Genellina
    
    
    
    From nytrokiss at gmail.com  Wed Jul 25 19:20:20 2007
    From: nytrokiss at gmail.com (James Matthews)
    Date: Wed, 25 Jul 2007 16:20:20 -0700
    Subject: I am giving up perl because of assholes on clpm -- switching to
    	Python
    In-Reply-To: 
    References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com>
    	
    Message-ID: <8a6b8e350707251620l6defd838gd26d003560e02f1f@mail.gmail.com>
    
    Wow! They might leave this newsgroup now also!
    
    On 7/25/07, J?rgen Exner  wrote:
    >
    > Martha_Jones at tx.net wrote:
    > > 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!!!
    >
    > Considering that your total posting history according to DejaNews consists
    > of exactly 3 posts (not including this last one) from 2001 to 2003 in NGs
    > that are so closely related to programming as pregnancy, marriage, and
    > cancer I believe the last sentiment is very mutual. After all, you didn't
    > ever leave any trace in CLPM until today.
    >
    > jue
    >
    >
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >
    
    
    
    -- 
    http://www.goldwatches.com/watches.asp?Brand=55
    http://www.jewelerslounge.com
    -------------- next part --------------
    An HTML attachment was scrubbed...
    URL: 
    
    From stefan.behnel-n05pAM at web.de  Wed Jul  4 02:19:43 2007
    From: stefan.behnel-n05pAM at web.de (Stefan Behnel)
    Date: Wed, 04 Jul 2007 08:19:43 +0200
    Subject: XML / Unicode / SAX question
    In-Reply-To: <468B3B9B.9070504@web.de>
    References: <1183527548.695326.303120@i13g2000prf.googlegroups.com>
    	<468B3B9B.9070504@web.de>
    Message-ID: <468B3BFF.1060202@web.de>
    
    Stefan Behnel wrote:
    > Note that you have to merge character sequences yourself in SAX.
    > There is no guarantee into how many chunks the textual context of a single tag
                                                           ^ content ^
    > is broken before it is passed to the characters() SAX method.
    
    Oh, well...
    
    Stefan
    
    
    From mccredie at gmail.com  Thu Jul 19 11:44:41 2007
    From: mccredie at gmail.com (Matimus)
    Date: Thu, 19 Jul 2007 15:44:41 -0000
    Subject: Break up list into groups
    In-Reply-To: 
    References: <1184620307.340479.253430@z28g2000prd.googlegroups.com>
    	<1184694533.380918.169640@m37g2000prh.googlegroups.com>
    	<469D09CC.3080402@ronadam.com>
    	<9e95df10707171408k2dfc8e08wd4056b80fcbe309b@mail.gmail.com>
    	
    Message-ID: <1184859881.860066.198940@e16g2000pri.googlegroups.com>
    
    > A little renaming of variables helps it be a bit more elegant I think ...
    >
    > def getgroups8(seq):
    >      groups = []
    >      iseq = iter(xrange(len(seq)))
    >      for start in iseq:
    >          if seq[start] & 0x80:
    >              for stop in iseq:
    >                  if seq[stop] & 0x80:
    >                      groups.append(seq[start:stop])
    >                      start = stop
    >              groups.append(seq[start:])
    >      return groups
    
    Excellent work! One more modification and I get below 10us/pass:
    
    def getgroups(seq):
         groups = []
         push = groups.append
         iseq = iter(xrange(len(seq)))
         for start in iseq:
             if seq[start] & 0x80:
                 for stop in iseq:
                     if seq[stop] & 0x80:
                         push(seq[start:stop])
                         start = stop
                 push(seq[start:])
         return groups
    
    -Matt
    
    
    
    From ptmcg at austin.rr.com  Sun Jul 22 11:06:39 2007
    From: ptmcg at austin.rr.com (Paul McGuire)
    Date: Sun, 22 Jul 2007 08:06:39 -0700
    Subject: ANN: pyparsing1.4.7
    Message-ID: 
    
    I just uploaded the latest release (v1.4.7) of pyparsing, and I'm
    happy to say, it is not a very big release - this module is getting
    to be quite stable.  A few bug-fixes, and one significant notation
    enhancement: setResultsNames gains a big shortcut in this release
    (see below).  No new examples in this release, sorry.
    
    Here are the notes:
    
    - NEW NOTATION SHORTCUT: ParserElement now accepts results names
      using a notational shortcut, following the expression with the
      results name in parentheses.  So this:
    
        stats = "AVE:" + realNum.setResultsName("average") + \
                "MIN:" + realNum.setResultsName("min") + \
                "MAX:" + realNum.setResultsName("max")
    
      can now be written as this:
    
        stats = "AVE:" + realNum("average") + \
                "MIN:" + realNum("min") + \
                "MAX:" + realNum("max")
    
      The intent behind this change is to make it simpler to define
      results names for significant fields within the expression, while
      keeping the grammar syntax clean and uncluttered.
    
    - Fixed bug when packrat parsing is enabled, with cached ParseResults
      being updated by subsequent parsing.  Reported on the pyparsing
      wiki by Kambiz, thanks!
    
    - Fixed bug in operatorPrecedence for unary operators with left
      associativity, if multiple operators were given for the same term.
    
    - Fixed bug in example simpleBool.py, corrected precedence of "and"
      vs. "or" operations.
    
    - Fixed bug in Dict class, in which keys were converted to strings
      whether they needed to be or not.  Have narrowed this logic to
      convert keys to strings only if the keys are ints (which would
      confuse __getitem__ behavior for list indexing vs. key lookup).
    
    - Added ParserElement method setBreak(), which will invoke the pdb
      module's set_trace() function when this expression is about to be
      parsed.
    
    - Fixed bug in StringEnd in which reading off the end of the input
      string raises an exception - should match.  Resolved while
      answering a question for Shawn on the pyparsing wiki.
    
    Download pyparsing 1.4.7 at http://sourceforge.net/projects/pyparsing/.
    The pyparsing Wiki is at http://pyparsing.wikispaces.com
    
    -- Paul
    
    ========================================
    Pyparsing is a pure-Python class library for quickly developing
    recursive-descent parsers.  Parser grammars are assembled directly in
    the calling Python code, using classes such as Literal, Word,
    OneOrMore, Optional, etc., combined with operators '+', '|', and '^'
    for And, MatchFirst, and Or.  No separate code-generation or external
    files are required.  Pyparsing can be used in many cases in place of
    regular expressions, with shorter learning curve and greater
    readability and maintainability.  Pyparsing comes with a number of
    parsing examples, including:
    - "Hello, World!" (English, Korean, Greek, and Spanish(new))
    - chemical formulas
    - configuration file parser
    - web page URL extractor
    - 5-function arithmetic expression parser
    - subset of CORBA IDL
    - chess portable game notation
    - simple SQL parser
    - Mozilla calendar file parser
    - EBNF parser/compiler
    - Python value string parser (lists, dicts, tuples, with nesting)
      (safe alternative to eval)
    - HTML tag stripper
    - S-expression parser
    - macro substitution preprocessor
    
    
    
    From aahz at pythoncraft.com  Tue Jul 17 10:22:49 2007
    From: aahz at pythoncraft.com (Aahz)
    Date: 17 Jul 2007 07:22:49 -0700
    Subject: Can a low-level programmer learn OOP?
    References:  
    	
    	<7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com>
    Message-ID: 
    
    In article <7cqo93pona4qoc4s94hh9rjrjalniilqts at 4ax.com>,
    Wolfgang Strobl   wrote:
    >
    >SNOBOLs powerfull patterns still shine, compared to Pythons clumsy
    >regular expressions. 
    
    Keep in mind that Python regular expressions are modeled on the
    grep/sed/awk/Perl model so as to be familiar to any sysadmin -- but
    there's a reason why Python makes it a *library* unlike Perl.  So adding
    SNOBOL patterns to another library would be a wonderful gift to the
    Python community...
    -- 
    Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/
    
    I support the RKAB
    
    
    From bscrivener42 at gmail.com  Mon Jul 23 14:02:05 2007
    From: bscrivener42 at gmail.com (BartlebyScrivener)
    Date: Mon, 23 Jul 2007 18:02:05 -0000
    Subject: Where do they tech Python officialy ?
    In-Reply-To: <1185209574.045112.163780@g4g2000hsf.googlegroups.com>
    References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com>
    Message-ID: <1185213725.261217.100200@q75g2000hsh.googlegroups.com>
    
    On Jul 23, 11:52 am, NicolasG  wrote:
    >
    > Does some one have any suggestions on which University to attend ?
    > Alternatives solutions are welcome..
    
    You might like this thread.  Or go to comp.lang.python and search for
    "python taught in schools"
    
    http://tinyurl.com/2zlsxl
    
    rd
    
    
    
    From andre.roberge at gmail.com  Mon Jul  9 19:37:40 2007
    From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=)
    Date: Mon, 09 Jul 2007 23:37:40 -0000
    Subject: New release:  Crunchy 0.9
    Message-ID: <1184024260.074366.33120@n2g2000hse.googlegroups.com>
    
    Crunchy 0.9 has been released.  It is available at
    http://code.google.com/p/crunchy
    
    What is Crunchy?
    
    Crunchy is a an application that transforms html Python tutorials into
    interactive session viewed within a browser.  We are not aware of any
    other application (in any language) similar to Crunchy.   Currently
    Crunchy has only been fully tested with Firefox; we know that some
    browsers simply don't work with it.  Crunchy should work with all
    operating systems - it has been tested fairly extensively on Linux,
    Windows and Mac OS.
    
    What is new in this release?
    
    Crunchy has been rewritten from scratch from the previous version
    (0.8.2), to use a custom plugin architecture.  This makes easier to
    extend and add new functionality.  Rather than list the differences
    with the old release, it is easier to list the essential features of
    this new version.
    
    1. Crunchy can work best with specially marked-up html tutorials.
    However, it can now work with any html tutorials - including the
    official Python tutorial on the python.org site.  Html pages can be
    loaded locally or remotely from anywhere on the Internet.  Crunchy
    uses a combination of Elementtree and BeautifulSoup to process html
    pages.  Non W3C-compliant pages can be handled, but the visual
    appearance is not guaranteed to reproduce that normally seen using a
    browser.
    
    2. Crunchy can insert a number of Python interpreters inside a web
    page.  In the default mode, it does that whenever it encounters an
    html 
     element which is assumed to contain some Python code.
    These interpreters can either share a common environment (e.g. modules
    imported in one of them are known in the other) or be isolated one
    from another.
    
    3. Crunchy adds automatic css styling to the Python code -  you can
    look at the official Python tutorial using your browser (all Python
    code in blue) and compare with what Crunchy displays to give you a
    good idea.
    
    4. Instead of inserting an interpreter, Crunchy can insert a code
    editor that can be used to modify the Python code on the page and
    execute it.  The editor can be toggled to become a fairly decent
    syntax aware editor that can save and load files.
    
    5. Crunchy has a "doctest" feature where the code inside the 
     is
    taken to be the result
    of an interpreter session and the user has to write the code so as to
    make the interpreter session valid; this is useful in a teaching
    environment. Messages from the Crunchy's doctest are "friendlier" for
    Python beginners than the usual tracebacks.
    
    6. Crunchy has a small graphics library that can be imported, either
    inside an editor or an interpreter, to produce simple graphics (even
    animations!) inside the browser.
    
    7. For the user that needs better quality graphics, Crunchy supports
    programs (such as matplotlib) that can create image files; by
    executing the code, the image produced is loaded inside the browser
    window.  In this capacity, Crunchy could be used as a front end for
    libraries such as matplotlib.
    
    8. Crunchy supports code execution of files as separate processes,
    making it suitable to launch gui based application from the browser
    window.
    
    9. Crunchy's interpreter has an interactive "help" feature like many
    python-aware IDEs.
    
    10. Crunchy includes a fairly comprehensive tutorial on its own use,
    as well as a reference for tutorial writers that want to make their
    tutorials "crunchy-friendlier".
    
    11. As a security feature, crunchy strips all pre-existing javascript
    code from an html page before displaying it inside the browser window.
    
    Bug reports, comments and suggestions are always welcome.
    
    Andr? Roberge, for the Crunchy team.
    
    
    
    From deets at nospam.web.de  Fri Jul 27 06:50:43 2007
    From: deets at nospam.web.de (Diez B. Roggisch)
    Date: Fri, 27 Jul 2007 12:50:43 +0200
    Subject: cls & self
    In-Reply-To: <1185419276.645373.83570@d30g2000prg.googlegroups.com>
    References: <1185419276.645373.83570@d30g2000prg.googlegroups.com>
    Message-ID: <5gu106F3igd71U1@mid.uni-berlin.de>
    
    james_027 schrieb:
    > hi,
    > 
    > is cls & self the same thing?
    > 
    > I have seen something like
    > 
    > class A:
    >     def dosomething(cls):
    >        #doing something
    > 
    > How is cls & self differ? How is it use?
    
    cls and self are just names. And you most certainly haven't seen the 
    above, but this instead:
    
    class A(object):
         @classmethod
         def dosomething(cls):
             pass
    
    
    The decorator "classmethod" makes a method of a class a class-method. 
    That means that it's not invoked like this
    
    a = A()
    a.dosomething()
    
    but
    
    A.dosomething()
    
    instead. Common usage are e.g. factory methods. And because it is a 
    classmethod, it gets the class passed as first argument, not the instance.
    
    
    Diez
    
    
    From http  Mon Jul 16 18:36:38 2007
    From: http (Paul Rubin)
    Date: 16 Jul 2007 15:36:38 -0700
    Subject: Break up list into groups
    References: <1184620307.340479.253430@z28g2000prd.googlegroups.com>
    Message-ID: <7x644kyo09.fsf@ruckus.brouhaha.com>
    
    "danmcleran at yahoo.com"  writes:
    > I can't seem to find an answer to this question anywhere, but I'm
    > still looking. My problem is I have a list of values like this:
    > 
    > l = [0xF0, 1, 2, 3, 0xF0, 4, 5, 6, 0xF1, 7, 8, 0xF2, 9, 10, 11, 12,
    > 13, 0xF0, 14, 0xF1, 15]
    > 
    > A value with bit 0x80 set delineates the start of a new packet of
    > information. What I want to do is to group the packets so that 1, 2, 3
    > go with the 1st packet tagged 0xF0, 4 ,5, 6 go with the 2nd packet
    > tagged 0xF0, 7 & 8 go with the packet tagged 0xF1 and so on. The
    > length of the data associated with each tag can vary. I've already
    > written an algorithm to do this but I was wondering if some
    > combination of itertools functions could do the job faster?
    
    See:
    
    http://groups.google.com/group/comp.lang.python/msg/2410c95c7f3b3654
    
    
    From LarinAM at gmail.com  Thu Jul  5 06:53:05 2007
    From: LarinAM at gmail.com (LarinAM at gmail.com)
    Date: Thu, 05 Jul 2007 10:53:05 -0000
    Subject: Python daemon in Linux
    In-Reply-To: <1183627404.157350.105560@o61g2000hsh.googlegroups.com>
    References: <1183627404.157350.105560@o61g2000hsh.googlegroups.com>
    Message-ID: <1183632785.049018.132080@c77g2000hse.googlegroups.com>
    
    thanx benjamin )
    no more questions
    
    
    
    From info at gegereka.org  Mon Jul  9 04:50:40 2007
    From: info at gegereka.org (GEGEREKA!)
    Date: Mon, 9 Jul 2007 08:50:40 +0000 (UTC)
    Subject: MP3 AVI DIVX MPEG SOFT = www.GEGEREKA.com
    Message-ID: 
    
    Millions files for everyone. Music, movies, soft and other media.
    Check it now!! http://www.gegereka.com
    
    
    From Xin.Zheng at jpl.nasa.gov  Tue Jul 10 21:09:41 2007
    From: Xin.Zheng at jpl.nasa.gov (Jason Zheng)
    Date: Tue, 10 Jul 2007 18:09:41 -0700
    Subject: os.wait() losing child?
    In-Reply-To: <5fioi8F3cchqoU1@mid.individual.net>
    References: 
    	<5fioi8F3cchqoU1@mid.individual.net>
    Message-ID: 
    
    greg wrote:
    > Jason Zheng wrote:
    >> while (True):
    >>   pid = os.wait()
    >>   ...
    >>   if (someCondition):
    >>     break
    >  >   ...
    > 
    > Are you sure that someCondition() always becomes true
    > when the list of pids is empty? If not, you may end
    > up making more wait() calls than there are children.
    > 
    
    Regardless of the nature of the someCondition, what I see from the print 
    output of my python program is that some child processes never triggers 
    the unblocking of os.wait() call.
    
    ~Jason
    
    
    From news2 at mystrobl.de  Sun Jul 22 10:20:02 2007
    From: news2 at mystrobl.de (Wolfgang Strobl)
    Date: Sun, 22 Jul 2007 16:20:02 +0200
    Subject: Can a low-level programmer learn OOP?
    References:  
    	
    	<7cqo93pona4qoc4s94hh9rjrjalniilqts@4ax.com>
    	
    Message-ID: 
    
    aahz at pythoncraft.com (Aahz):
    
    >In article <7cqo93pona4qoc4s94hh9rjrjalniilqts at 4ax.com>,
    >Wolfgang Strobl   wrote:
    >>
    >>SNOBOLs powerfull patterns still shine, compared to Pythons clumsy
    >>regular expressions. 
    >
    >Keep in mind that Python regular expressions are modeled on the
    >grep/sed/awk/Perl model so as to be familiar to any sysadmin 
    
    Sure, I don't dispute that. There is room for both regular expressions
    and SNOBOL type patterns, IMHO, because the concepts are different
    enough.
    
    >-- but
    >there's a reason why Python makes it a *library* unlike Perl.  So adding
    >SNOBOL patterns to another library would be a wonderful gift to the
    >Python community...
    
    Like Eddie Corns if find it hard to do in an elegant way, without
    integrating it into the language. I haven't looked into it for a long
    time, though.
    
    -- 
    Wir danken f?r die Beachtung aller Sicherheitsbestimmungen
    
    
    From sturlamolden at yahoo.no  Sun Jul 29 22:33:40 2007
    From: sturlamolden at yahoo.no (sturlamolden)
    Date: Sun, 29 Jul 2007 19:33:40 -0700
    Subject: Why no maintained wrapper to Win32?
    In-Reply-To: <59kna3p8r0cu2gk6hs5lbig8cjj8klatju@4ax.com>
    References: 
    	<46ab694e$0$17577$9b622d9e@news.freenet.de>
    	<59kna3p8r0cu2gk6hs5lbig8cjj8klatju@4ax.com>
    Message-ID: <1185762820.496821.298530@19g2000hsx.googlegroups.com>
    
    On Jul 29, 1:29 am, Gilles Ganault  wrote:
    
    > Besides the total lack of documentation,
    
    You mean 'total lack of documentation' besides Mark Hammond's O'Reilly
    book on Windows programming in Python?
    
    Not to mention MSDN, Charles Petzold's book, and other sources of
    Win32 API and MFC documentation?
    
    
    
    From horpner at yahoo.com  Tue Jul  3 12:08:02 2007
    From: horpner at yahoo.com (Neil Cerutti)
    Date: Tue, 03 Jul 2007 16:08:02 GMT
    Subject: Pretty Scheme, ??? Python
    References: 
    	<46895e12$0$5078$ba4acef3@news.orange.fr>
    	<_Ddii.36114$G23.10348@newsreading01.news.tds.net>
    	<1183418938.911025.55340@w5g2000hsg.googlegroups.com>
    	
    	<1183469909.444902.147310@57g2000hsv.googlegroups.com>
    Message-ID: 
    
    On 2007-07-03, Paul McGuire  wrote:
    > Here is my alternative solution (not using results names).  I used
    > the base WAE class to accept the tokens as the initialization var,
    > then unpack the list into variables in each respective calc()
    > method.  I did not see the need for a subst() method. 
    
    I used recursion to effect substitution of id's with their
    values, whereas you chose to use a dictionary of stacks. I prefer
    the functional solution for being simpler, and state-less.
    
    Thanks for the nice example. I think I've seen enough to create
    something satisfying.
    
    There seems to be a bug in my current grammar. The factory for
    BinOp is not getting the correct named results. Can you see
    something I've messed up?
    
    LPAR = Literal("(").suppress()
    RPAR = Literal(")").suppress()
    
    wae = Forward()
    num = Word(nums).setResultsName('number')
    id_ = Word(alphas).setResultsName('name')
    
    binop = Group( LPAR + oneOf("+ -").setResultsName('op') + 
            wae.setResultsName('lhs') + wae.setResultsName('rhs') + RPAR )
    with_ = Group( LPAR + "with" + LPAR + id_.setResultsName('bound_id') + 
            wae.setResultsName('named_expr') + RPAR + 
            wae.setResultsName('bound_body') + RPAR )
    
    wae << (binop | with_ | num | id_)
    
    num.setParseAction(lambda t: Num(int(t.number)))
    id_.setParseAction(lambda t: Id(t.name))
    binop.setParseAction(lambda t: BinOp(t.op, t.lhs, t.rhs))
    with_.setParseAction(lambda t: With(t.bound_id, t.named_expr, t.bound_body))
    
    def parse(s):
        return (wae + StringEnd()).parseString(s).asList()[0]
    
    For test case:
    
     '(+ 3 45)'
    
    I get:
    
    C:\WINNT\system32\cmd.exe /c python wae.py
    **********************************************************************
    File "wae.py", line 6, in __main__
    Failed example:
        parse('(+ 3 45)')
    Exception raised:
        Traceback (most recent call last):
          File "c:\edconn32\python25\lib\doctest.py", line 1212, in __run
            compileflags, 1) in test.globs
          File "", line 1, in 
            parse('(+ 3 45)')
          File "wae.py", line 122, in parse
            return (wae + StringEnd()).parseString(s).asList()[0]
          File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 906, in p
    arseString
            loc, tokens = self._parse( instring.expandtabs(), 0 )
          File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 784, in _
    parseNoCache
            loc,tokens = self.parseImpl( instring, preloc, doActions )
          File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 1961, in
    parseImpl
            loc, resultlist = self.exprs[0]._parse( instring, loc, doActions, callPr
    eParse=False )
          File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 784, in _
    parseNoCache
            loc,tokens = self.parseImpl( instring, preloc, doActions )
          File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 2204, in
    parseImpl
            return self.expr._parse( instring, loc, doActions, callPreParse=False )
          File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 784, in _
    parseNoCache
            loc,tokens = self.parseImpl( instring, preloc, doActions )
          File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 2070, in
    parseImpl
            ret = e._parse( instring, loc, doActions )
          File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 810, in _
    parseNoCache
            tokens = fn( instring, tokensStart, retTokens )
          File "C:\edconn32\Python25\Lib\site-packages\pyparsing.py", line 658, in t
    mp
            return f(t)
          File "wae.py", line 118, in 
            binop.setParseAction(lambda t: BinOp(t.op, t.lhs, t.rhs))
          File "wae.py", line 73, in __init__
            '-': (operator.sub, 'Sub')}[op]
        KeyError: ''
    **********************************************************************
    
    op ought to be '+' or '-'. In fact, testing showed than none of
    the result names for binop are being set correctly.
    
    -- 
    Neil Cerutti
    The word "genius" isn't applicable in football. A genius is a guy like Norman
    Einstein. --Joe Theisman
    
    
    From bignose+hates-spam at benfinney.id.au  Fri Jul 20 19:18:54 2007
    From: bignose+hates-spam at benfinney.id.au (Ben Finney)
    Date: Sat, 21 Jul 2007 09:18:54 +1000
    Subject: Weird errors when trying to access a dictionary key
    References: <1184956573.702959.96400@d30g2000prg.googlegroups.com>
    Message-ID: <87zm1qll41.fsf@benfinney.id.au>
    
    robinsiebler at gmail.com writes:
    
    > I have a data structure that looks like this:
    > [...]
    > rpt_file.writelines('\t' + [song].keys() + '\t' + [song].values() + '\n')
    
    Forms the list [song] twice, attempting to call the 'keys()' method
    and the 'values()' method of that list in turn...
    
    > I get the following error:
    > 
    > Traceback (most recent call last):
    > [...]
    > AttributeError: 'list' object has no attribute 'keys'
    
    ... which doesn't exist.
    
    > Here is where it gets weird:
    > 
    > song
    > {"I Don't Wanna Stop": 1}
    > song.keys()
    > ["I Don't Wanna Stop"]
    
    Yes. A list doesn't have a 'keys' or 'values' method, a dict
    does. 'song' is a dict. So why are you not calling the 'keys' method
    of the 'song' object?
    
    -- 
     \           "If [a technology company] has confidence in their future |
      `\      ability to innovate, the importance they place on protecting |
    _o__)  their past innovations really should decline."  -- Gary Barnett |
    Ben Finney
    
    
    From zyzhu2000 at gmail.com  Fri Jul 27 10:10:31 2007
    From: zyzhu2000 at gmail.com (beginner)
    Date: Fri, 27 Jul 2007 14:10:31 -0000
    Subject: Another C API Question
    In-Reply-To: 
    References: <1185498383.333248.225360@19g2000hsx.googlegroups.com>
    	
    Message-ID: <1185545431.975494.215810@j4g2000prf.googlegroups.com>
    
    Hi Robert,
    
    On Jul 26, 8:16 pm, Robert Kern  wrote:
    > beginner wrote:
    > > Hi,
    >
    > > I run into another C API question. What is the simplest way to convert
    > > an PyObject into a double?
    >
    > > For example, I have
    >
    > >  PyObject *obj;
    >
    > > I know obj is a number, but I do not know the exact type. How can I
    > > convert it to double without writing a giant switch() that exhausts
    > > every single type of number?
    >
    > Convert it to a Python float using PyNumber_Float(), then use PyFloat_AsDouble()
    > to get the C double value from it.
    >
    
    Thanks a lot for your help.
    
    Best regards,
    beginner
    
    
    
    
    From the.mindstorm.mailinglist at gmail.com  Wed Jul 11 10:42:28 2007
    From: the.mindstorm.mailinglist at gmail.com (Alex Popescu)
    Date: Wed, 11 Jul 2007 07:42:28 -0700
    Subject: stripping the first byte from a binary file
    In-Reply-To: <5fk3geF3b8794U1@mid.uni-berlin.de>
    References: <1184063032.195000.25880@i13g2000prf.googlegroups.com>
    	
    	<1184115964.912526.273780@e16g2000pri.googlegroups.com>
    	
    	<1184148168.639675.85900@a26g2000pre.googlegroups.com>
    	<4694B01A.30107@web.de>
    	<1184153416.798767.163740@d55g2000hsg.googlegroups.com>
    	<5fk3geF3b8794U1@mid.uni-berlin.de>
    Message-ID: <1184164948.266014.178760@g4g2000hsf.googlegroups.com>
    
    On Jul 11, 4:15 pm, "Diez B. Roggisch"  wrote:
    > > Forgive my newbie ignorance, but I am wondering why the other method
    > > would not work? I mean it may not be very safe,
    > > but I guess it may perform a lot better, than having to read the whole
    > > file just to cut out the first byte.
    >
    > Because seeking is not moving? Shifting data bytewise isn't something that
    > is supported by the underlying OS filesystems, and thus not supported. But
    > replacing bytes with others is. Which seek is for.
    >
    > Diez
    
    As far as I know seek is just about positioning and nothing else.
    So, in fact the problem boils down to os support for deleting a bytes.
    
    bests,
    
    ./alex
    --
    .w( the_mindstorm )p.
    
    
    
    
    From gentoodev at gmail.com  Mon Jul  9 12:39:31 2007
    From: gentoodev at gmail.com (Rob Cakebread)
    Date: Mon, 09 Jul 2007 16:39:31 -0000
    Subject: Tool for finding external dependencies
    In-Reply-To: <1183998180.347827.325100@n60g2000hse.googlegroups.com>
    References: <1183945183.147231.120180@z28g2000prd.googlegroups.com>
    	<1183990671.337753.106370@k79g2000hse.googlegroups.com>
    	<1183991251.354349.326520@e16g2000pri.googlegroups.com>
    	<1183992896.381070.62280@n60g2000hse.googlegroups.com>
    	<1183995767.335243.197190@i38g2000prf.googlegroups.com>
    	<1183998180.347827.325100@n60g2000hse.googlegroups.com>
    Message-ID: <1183999171.325892.214730@o11g2000prd.googlegroups.com>
    
    On Jul 9, 9:23 am, Alex Popescu 
    wrote:
    > Isn't it possible to get from modulefinder what it has found and just
    > filter it out according to your rules?
    > This way you are in control and can deicde what is internal/external.
    >
    
    At first glance it looked easy enough, by just filtering out
    everything that isn't in site-packages, but that isn't quite accurate
    as accurate as pylint and it also shows indirect dependencies too.
    e.g. pkga imports pkgb, which imports pkgc. I don't want pkgc.
    
    To clarify, if I had a module with:
    
    import os,sys, re
    import sqlobject
    
    I only want to know about sqlobject. I don't want any of sqlobject's
    dependencies, such as MySQLdb, pysqlite2, psycopg2 etc. which
    modulefinder shows also.
    
    And as far as I can tell, modulefinder needs a Python script, but its
    much easier for me to find a package's modules automatically.
    
    
    Thanks,
    Rob
    
    
    
    
    
    From paul at boddie.org.uk  Mon Jul 16 19:28:19 2007
    From: paul at boddie.org.uk (Paul Boddie)
    Date: Mon, 16 Jul 2007 16:28:19 -0700
    Subject: The ** operator ambiguous?
    In-Reply-To: <1184607614.904143.219330@w3g2000hsg.googlegroups.com>
    References: <1184607614.904143.219330@w3g2000hsg.googlegroups.com>
    Message-ID: <1184628499.822335.256630@d55g2000hsg.googlegroups.com>
    
    Robert Dailey wrote:
    > I noticed that the ** operator is used as the power operator, however
    > I've seen it used when passing variables into a function.
    
    Others have already pointed out the relevant documentation. However,
    this ambiguous usage of * and ** is one thing I don't recall appearing
    on any of the "Python warts" lists - not that I spend too much time
    following such matters. I imagine that * was initially chosen in order
    to be similar to the way one may handle collections of values in C
    function signatures (ie. using pointers), and that ** was merely a
    convenient next step as opposed to being analogous to the "pointer to
    pointer" notation from C. The same symbols are used in different ways
    in C and C++, of course.
    
    It's interesting to see a fresh interpretation of the notation,
    though.
    
    Paul
    
    
    
    From __peter__ at web.de  Wed Jul  4 02:17:40 2007
    From: __peter__ at web.de (Peter Otten)
    Date: Wed, 04 Jul 2007 08:17:40 +0200
    Subject: import mysteries
    References: 
    	
    	
    Message-ID: 
    
    David Abrahams wrote:
    
    > 
    > on Thu Jun 21 2007, Peter Otten <__peter__-AT-web.de> wrote:
    > 
    >> David Abrahams wrote:
    >>
    >>> I'm pretty comfortable with Python, but recently I'm constantly
    >>> finding mysterious issues with import.  For example, looking at
    >>> 
    >>>   http://genshi.edgewall.org/browser/trunk/genshi/filters/transform.py
    >>> 
    >>> the examples use the symbol 'HTML' but it's not defined locally, it's
    >>> not explicitly imported, and there's no import *.  Yet doctest will
    >>> test this module and it passes with flying colors.  It turns out HTML
    >>> is defined in genshi.input.  How do I know that?  I grepped for it.
    >>> How does it become available to this module?
    >>
    >> Explicitly passed, see
    >>
    >>
    http://genshi.edgewall.org/browser/trunk/genshi/filters/tests/transform.py
    > 
    > IIRC I ran doctest on the file I cited, not the one you're pointing
    > at.  Is there some new magic doctest feature I should know about?
    
    Had you looked at it you'd seen that the file I pointed to is the driver
    script for running the doctests in the file you pointed to -- unfortunately
    they have the same name. [...]/tests/transform.py does indeed inject a HTML
    object into the globals of [...]/filters/transform.py before it runs the
    tests.
     
    >>> Another example: I was recently working on some code that did an
    >>> import from inside a class method.  That import was failing.  I moved
    >>> the import to the top of the file (at module scope) and it succeeded.
    >>> I'm fairly sure that nobody was monkeying around with sys.path in that
    >>> case.  Can anyone think of a likely explanation?
    >>
    >> Too vague, sorry.
    > 
    >   # this will succeed if I do it here
    >   # import foo.bar
    > 
    >   class X:
    >         def y():
    >             import foo.bar # but this fails
     
    Are threads involved? I vaguely remember a problem with Queue.Queue that
    came up on this list some time ago.
    
    Peter
    
    
    
    From deets at nospam.web.de  Thu Jul 26 18:33:55 2007
    From: deets at nospam.web.de (Diez B. Roggisch)
    Date: Fri, 27 Jul 2007 00:33:55 +0200
    Subject: code indentation
    In-Reply-To: <1185478366.910475.110490@19g2000hsx.googlegroups.com>
    References: 
    	
    	<1185297657.186852.136950@k79g2000hse.googlegroups.com>
    	
    	<87lkd5jt83.fsf@benfinney.id.au>
    	<1185357861.989194.117000@r34g2000hsd.googlegroups.com>
    	
    	<1185387723.155661.311510@b79g2000hse.googlegroups.com>
    	
    	
    	<1185478366.910475.110490@19g2000hsx.googlegroups.com>
    Message-ID: <5gslqmF3gtlbpU1@mid.uni-berlin.de>
    
    vedrandekovic at v-programs.com schrieb:
    > On 26 srp, 13:43, Steve Holden  wrote:
    >> Thorsten Kampe wrote:
    >>> *  (Wed, 25 Jul 2007 11:22:03 -0700)
    >>>> On 25 srp, 17:31, Wildemar Wildenburger  wrote:
    >>>>> vedrandeko... at v-programs.com wrote:
    >>>>>>> And while we're on the topic of communication: The original poster
    >>>>>>> would do well to learn that increasing the number of consecutive
    >>>>>>> punctuation marks (!!!, ???) is a sure way to turn away many people
    >>>>>>> who would otherwise be helpful. Sentences need at most one '!' or '?',
    >>>>>>> adding more does not improve the chances of being taken seriously.
    >>>>>> And if you can help me than please help me , but if you can't then
    >>>>>> please don't leave me some stupid messages
    >>>>> Whats stupid about this? It's sane advice.
    >>>>> Which looks more serious to you:
    >>>>> this:
    >>>>> I can't do it!!!! Can you PLEASE help me????!!!?!
    >>>>> or this:
    >>>>> I don't know the answer. Can you please help me?
    >>>>> Even if it makes no difference to you, to many people it does. So Ben is
    >>>>> right: People *will* take your posts more seriously if you restrict your
    >>>>> use of punctuation (if only because its easier to read).
    >>>>> Don't feel offended, nobody was trying to put you down.
    >>>> On this group I ask for serious help and now we talk about
    >>>> communication. Then I you don't know how to help me then please DON'T
    >>>> SAY ANYTHING
    >>> You already got serious help even though you haven't realised that
    >>> yet.
    >> We should be making allowances for this particular poster on account of
    >> relative youth: I hadn't realised earlier, but we are dealing with a
    >> fourteen-year-old. Since fourteen-year-olds already know everything we
    >> should be honored we are being asked for 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 -------------
    > 
    > Hi again,
    > 
    > Just one more question, can I maybe do this indentation with string
    > e.g
    > here is my failed example of try with string:
    > 
    > kl="n=90;if n==90:print'kajmakimar'"
    > 
    > for line in kl.split(";"):
    >     li=[]
    >     m=li.append(line)
    >     if line.endswith(':'):
    >             m.append("\n\t\t\t\t\t\t\t\t")
    >     print m
    > 
    > .....so maybe if you can help me with this?
    
    This won't work. It's impossible to know how deep to indent without any 
    begin/end-tokens. Consider this simple example:
    
    if foo:
        print "foo"
        if bar:
           print "bar"
    
    is equal to
    
    'if foo:;print"foo";if bar:;print "bar"'
    
    But that could as well be
    
    if foo:
        print "foo"
    if bar:
        print "bar"
    
    So - you need some block delimiters.
    
    And as it has been said to you a bazzillion times: stop doing what 
    you're doing. Use python. As it is. Your limited understandig of parsing 
    and language design makes your task beyond your capabilites. For now. 
    And the forseeable future...
    
    diez
    
    
    From gagsl-py2 at yahoo.com.ar  Thu Jul 12 22:55:45 2007
    From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
    Date: Thu, 12 Jul 2007 23:55:45 -0300
    Subject: Understanding python functions - Instant Python tutorial
    References: 
    Message-ID: 
    
    En Thu, 12 Jul 2007 21:51:08 -0300, Chris Carlen  
     escribi?:
    
    > Hi:
    >
    > I have begun learning Python by experimenting with the code snippets  
    > here:
    >
    > http://hetland.org/writing/instant-python.html
    >
    > In the section on functions, Magnus Lie Hetland writes:
    >
    > --------------------------------------------------------------------
    > For those of you who understand it: When you pass a parameter to a
    > function, you bind the parameter to the value, thus creating a new
    > reference. If you change the ?contents? of this parameter name (i.e.
    > rebind it) that won?t affect the original. This works just like in Java,
    > for instance. Let?s take a look at an example:
    >
    > def change(some_list):
    >      some_list[1] = 4
    >
    > x = [1,2,3]
    > change(x)
    > print x # Prints out [1,4,3]
    >
    > As you can see, it is the original list that is passed in, and if the
    > function changes it, these changes carry over to the place where the
    > function was called.  Note, however the behaviour in the following  
    > example:
    >
    > def nochange(x):
    >      x = 0
    >
    > y = 1
    > nochange(y)
    > print y # Prints out 1
    >
    > Why is there no change now? Because we don?t change the value! The value
    > that is passed in is the number 1 ? we can?t change a number in the same
    > way that we change a list. The number 1 is (and will always be) the
    > number 1. What we did do is change the contents of the local variable
    > (parameter) x, and this does not carry over to the environment.
    > --------------------------------------------------------------------
    >
    > What this looks like to me is what would happen if in C I passed a
    > pointer to the list x to the function change(), as in:
    >
    > change(&x);
    >
    > Thus the function could change the original list.
    >
    > I don't understand Hetland's terminology though, when he is speaking of
    > "binding" and "reference."  Actually, Hetland's entire first paragraph
    > is unclear.
    >
    > Can anyone reword this in a way that is understandable?
    
    First, see this short article http://effbot.org/zone/python-objects.htm
    
    Now, forget about C "variables" and "pointers" because you won't get much  
    far with those concepts.
    Objects exist - and we usually use names to refer to them. This line:
    
    a =  1
    
    means "make the name 'a' refer to the object 1", or, "bind the name 'a' to  
    the instance of type int with value 1", or "let 'a' be a reference to the  
    object 1"
    
    This line:
    
    some_list[1] = 4
    
    means "make the second element of some_list refer to the object 4", or  
    "alter some_list so its element [1] is a reference to the object 4"
    
    bind the name 'a' to the instance of type int with value 1", or "let 'a'  
    be a reference to the object 1"
    
    Note that some objects are immutable - like the number 1, which will  
    always be the number 1 (*not* an integer "variable" that can hold any  
    integer value). Other objects -like lists and dictionaries, by example, or  
    most user defined classes- are mutable, and you can change its contents  
    and properties. Modifying an object is not the same as rebinding its name:
    
    x = [1,2,3]
    y = x
    x[1] = 4
    print x		# [1, 4, 3]
    print y 	# [1, 4, 3]
    
    x = [1,2,3]
    y = x
    x = [1,4,3]
    print x		# [1, 4, 3]
    print y		# [1, 2, 3]
    
    You can test is two names refer to the same object using the is operator:  
    x is y. You will get True in the first case and False in the second case.
    
    -- 
    Gabriel Genellina
    
    
    
    From nytrokiss at gmail.com  Wed Jul 25 16:35:39 2007
    From: nytrokiss at gmail.com (James Matthews)
    Date: Wed, 25 Jul 2007 13:35:39 -0700
    Subject: I am giving up perl because of assholes on clpm -- switching to
    	Python
    In-Reply-To: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com>
    References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com>
    Message-ID: <8a6b8e350707251335t352fat4b1d1f8d29170e48@mail.gmail.com>
    
    Welcome aboard
    
    On 7/25/07, Martha_Jones at tx.net  wrote:
    >
    > 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
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >
    
    
    
    -- 
    http://www.goldwatches.com/watches.asp?Brand=55
    http://www.jewelerslounge.com
    -------------- next part --------------
    An HTML attachment was scrubbed...
    URL: 
    
    From will at willNOmcguganSPAM.com  Mon Jul 30 06:22:34 2007
    From: will at willNOmcguganSPAM.com (Will McGugan)
    Date: Mon, 30 Jul 2007 11:22:34 +0100
    Subject: Cross platform Python app deployment
    Message-ID: <46adbbec$0$15210$fa0fcedb@news.zen.co.uk>
    
    Hi,
    
    Is there some reference regarding how to package a Python application 
    for the various platforms? I'm familiar with Windows deployment - I use 
    Py2Exe & InnoSetup - but I would like more information on deploying on 
    Mac and Linux.
    
    TIA,
    
    Will McGugan
    --
    http://www.willmcgugan.com
    
    
    From gagsl-py2 at yahoo.com.ar  Sat Jul 14 08:14:51 2007
    From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
    Date: Sat, 14 Jul 2007 09:14:51 -0300
    Subject: MaildirMessage
    References: <1184287592.509355.310110@g4g2000hsf.googlegroups.com>
    	
    	<874pk8kedo.fsf@benfinney.id.au>
    	
    	<87vecniw4u.fsf@benfinney.id.au>
    	
    	<1184405203.481400.171600@m3g2000hsh.googlegroups.com>
    Message-ID: 
    
    En Sat, 14 Jul 2007 06:26:43 -0300, Tzury   
    escribi?:
    
    >> What do you actually think
    >>
    >> ...     for m in msg:
    >> ...             print m
    >>
    >> should do? Why do you believe that what you think it should do would be
    >> a natural choice?
    >
    > I needed to know how to extract particular parts of a message, such as
    > the message 'body', 'subject', 'author', etc.
    > I couldn't find it in the documentation this kind of information until
    > I ran the inspect.getmembers(msg)
    
    Well, you took the hard way... the easy way would be to read the  
    documentation: http://docs.python.org/lib/module-email.message.html
    
    > and found out that the message body
    > stored in _payload. that is msg._payload is the content of the
    > message.
    
    You should perceive the initial _ in _payload as a yellow light - a  
    warning. It's an implementation detail and one should avoid messing with  
    it - best to stick to the documented API, get_payload() in this case.
    
    > Regarding the *bug* thing it is very simple. If you iterate an int you
    > get an exception , clear
    > enough. Yet here I got the following exception  object has no attribute 'lower'> which suggest an attempt to iterate
    > ---. I do think that a message should support iteration for the very
    > fact that each can contain a different type and amount of headers, and
    > iteration in this case will make application's code clean and unified.
    
    I don't see what you mean. You can always enumerate the message headers  
    using msg.keys(), along with has_key(), items(), etc. And what you want to  
    unify the code with?
    
    Even if Message becomes iterable, I still don't see why should iteration  
    over its *headers* be the preferred meaning. For a multipart/* MIME  
    message, iterating over the parts looks much more interesting.
    
    -- 
    Gabriel Genellina
    
    
    
    From fattie at tpu.ru  Fri Jul 27 13:30:37 2007
    From: fattie at tpu.ru (Valentina Vaneeva)
    Date: Sat, 28 Jul 2007 00:30:37 +0700
    Subject: Imported globals?
    Message-ID: <244eaab1bc1b0d3f90ca87112da3b697@tpu.ru>
    
    
    On Jul 27, 2007, at 10:56 PM, Gary Herron wrote:
    
    > The variable "value" is global in module_a, and "change_value" will 
    > always refer to that variable.
    >
    > However, in module_b, when you      from module_a import value, 
    > change_value
    > you have created two new variables global to module_b that references 
    > values from the other module.
    > Now running change_value (which changes "value" in module_a has no 
    > affect on the version of "value" in module_b.   Your print is then 
    > printing value from module_b -- the unchanged version.
    
    Thank you, Gary, but I still have one question. What happens in the 
    second case? If I add a call to change_value() to module_a, the value 
    in module_b is imported changed. Why? What exactly does the import 
    statement import in my example?
    
    > Ideas:
    > 1 If you want module_a to manage such a global variable, you could 
    > include functions for getting, and setting it, as well as your 
    > function for changing it's value.
    >
    > 2. You could also dispense with use of global values -- various OOP 
    > techniques could help there.
    
    Thanks, this part is not a problem :)
    
    
    Cheers,
    	Valia
    
    
    
    From robinsiebler at gmail.com  Fri Jul 20 14:36:13 2007
    From: robinsiebler at gmail.com (robinsiebler at gmail.com)
    Date: Fri, 20 Jul 2007 11:36:13 -0700
    Subject: Weird errors when trying to access a dictionary key
    Message-ID: <1184956573.702959.96400@d30g2000prg.googlegroups.com>
    
    I have a data structure that looks like this:
    
    #    dates = {'2007': {'25': {'06/23/07': {'aerosmith': [{'sweet
    emotion': 1}, {'dream on': 2}],
    #                                          'Metallica': [{'Fade to
    Black': 1}, {'Master of Puppets': 1}]},
    #             'last_song': [Master of Puppets', 'Fade to Black',
    'sweet emotion']}}}
    
    I have a section where I try to loop through a set of dates and print
    out all of the songs for a given artist:
    
        if type == 'artist':
            rpt_file.writelines('Song Summary for ' + artist + '\n\n')
            for year in sorted(rpt_dates):
                for week in sorted(rpt_dates[year]):
                    for date in sorted(dates[year][week]):
                        if artist in dates[year][week][date]:
                            report.append(date)
                            for song in sorted(dates[year][week][date]
    [artist]):
                                rpt_file.writelines('\t' + [song].keys() \
                                                    + '\t' +
    [song].values() + '\n')
    
    
    I get the following error:
    
    Traceback (most recent call last):
      File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
    \pythonlib\dbgp\client.py", line 1843, in runMain
        self.dbg.runfile(debug_args[0], debug_args)
      File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
    \pythonlib\dbgp\client.py", line 1538, in runfile
        h_execfile(file, args, module=main, tracer=self)
      File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
    \pythonlib\dbgp\client.py", line 596, in __init__
        execfile(file, globals, locals)
      File "C:\scripts\python\Songs\song_report.py", line 136, in 
        if __name__== '__main__': main()
      File "C:\scripts\python\Songs\song_report.py", line 134, in main
        print_rpt(options.type, rpt_dates, dates, args)
      File "C:\scripts\python\Songs\song_report.py", line 107, in
    print_rpt
        + '\t' + [song].values() + '\n')
    AttributeError: 'list' object has no attribute 'keys'
    
    Here is where it gets weird:
    
    type(song)
    Traceback (most recent call last):
      File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
    \pythonlib\dbgp\client.py", line 3241, in runcode
        locals = self.frame.f_locals)
      File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
    \pythonlib\dbgp\client.py", line 1583, in runcode
        h_exec(code, globals=globals, locals=locals, module=module)
      File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp
    \pythonlib\dbgp\client.py", line 520, in __init__
        exec code in globals, locals
      File "", line 0, in 
    TypeError: 'str' object is not callable
    song
    {"I Don't Wanna Stop": 1}
    song.keys()
    ["I Don't Wanna Stop"]
    
    For the complete script and data file, go to
    http://members.dslextreme.com/users/robinsiebler/python/
    
    
    
    From byte8bits at gmail.com  Mon Jul 23 15:13:16 2007
    From: byte8bits at gmail.com (brad)
    Date: Mon, 23 Jul 2007 15:13:16 -0400
    Subject: inet_addr() in Python
    Message-ID: 
    
    Does Python have an equivalent to C's inet_addr()?
    
    Thanks,
    Brad
    
    
    From jelleferinga at gmail.com  Thu Jul 26 04:28:42 2007
    From: jelleferinga at gmail.com (jelle)
    Date: Thu, 26 Jul 2007 08:28:42 -0000
    Subject: adding a docstring to an instancemethod
    In-Reply-To: 
    References: <1185361537.733690.238280@k79g2000hse.googlegroups.com>
    	
    Message-ID: <1185438522.978804.118010@19g2000hsx.googlegroups.com>
    
    
    > Set the __doc__ on the *function* from which you build the instance method.
    
    Thanks for you reply Gabriel,
    Though setting the docstring to the functions wouldn't be an option
    for me.
    The thing is that I have a
    
    wrappedCppModule.Class.Method I'd like to give a docstring, so there's
    no prior function to refer to.
    
    Thanks,
    
    -jelle
    
    
    
    From tleeuwenburg at gmail.com  Wed Jul  4 01:23:30 2007
    From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com)
    Date: Wed, 04 Jul 2007 05:23:30 -0000
    Subject: Building a Python app with Mozilla
    In-Reply-To: <1183524527.709730.190290@q75g2000hsh.googlegroups.com>
    References: 
    	<1183524527.709730.190290@q75g2000hsh.googlegroups.com>
    Message-ID: <1183526610.556723.70440@d30g2000prg.googlegroups.com>
    
    On Jul 4, 2:48 pm, "sjdevn... at yahoo.com"  wrote:
    > Thorsten Kampe wrote:
    > > Hi,
    >
    > > I've already sent this to the Komodo mailing list (which seemed to me
    > > the more appropriate place) but unfortunately I got no response.
    >
    > > I'd like to build a Python GUI app. Neither Tkinter nor Wxpython nor
    > > PyQT are actually what I want (because the lack of GUI builders and
    > > they don't really look good on Windows and Linux).
    >
    > > Komodo itself is an excellent example of a - at least Python driven -
    > > application that looks superb
    >
    > I dunno about Windows, but on Linux Komodo/Firefox/etc stick out like
    > a sore thumb with their ugly, non-native looking widgets (idem. Tk).
    > wxWidgets will give you native looking apps on both Linux and Windows
    > (and I think on Macs as well but it's been a while since I looked).
    
    They stick out like a grand painting at a kid's art class...
    
    -T
    
    
    
    From tenax.raccoon at gmail.com  Thu Jul 19 17:54:33 2007
    From: tenax.raccoon at gmail.com (Jason)
    Date: Thu, 19 Jul 2007 14:54:33 -0700
    Subject: Copy List
    In-Reply-To: <1184862114.094387.257580@i13g2000prf.googlegroups.com>
    References: <-29831789359750479@unknownmsgid>
    	<6a2ccd190707180544k4909ad3enc6a962917a26f43d@mail.gmail.com>
    	
    	<1184862114.094387.257580@i13g2000prf.googlegroups.com>
    Message-ID: <1184882073.777882.311310@k79g2000hse.googlegroups.com>
    
    On Jul 19, 10:21 am, Falcolas  wrote:
    > On Jul 18, 6:56 am, "Rustom Mody"  wrote:
    >
    > > This is shallow copy
    > > If you want deep copy then
    > > from copy import deepcopy
    >
    > What will a "deep copy" of a list give you that using the slice
    > notation will not?
    
    With a shallow copy, you end up with a new list object, but the items
    contained within the new list object are the same as in the original
    list object.  This makes no real difference if the original list only
    contains immutable values (such as strings, integers, or floats), but
    it can make a big difference if the values are mutable.
    
    >>> originalList = [1, 2, [3, 4]]
    >>> shallowCopy = originalList[:]
    >>> shallowCopy.append(5)
    >>> print str(originalList), '\n', str(shallowCopy)
    [1, 2, [3, 4]]
    [1, 2, [3, 4], 5]
    >>> originalList[2].append(100) # Mutate the list inside this list
    >>> print str(originalList), '\n', str(shallowCopy)
    [1, 2, [3, 4, 100]]
    [1, 2, [3, 4, 100], 5]
    >>>
    
    As you can see in the above code snipped, the original list contains a
    list at index 2.  The slice copy is a different list, so appending a 5
    to it doesn't modify the original list.  However, the result of
    appending 100 to the object at index 2 can be seen in both lists.  A
    deep copy creates a new object for ever item in the list, and all
    items in those items, and so forth, so the lists guaranteed to be
    truly disconnected:
    
    >>> from copy import deepcopy
    >>> originalList = [1, [2, [3, 4]]]
    >>> fullCopy = deepcopy(originalList)
    >>> originalList[1][1].append(100)
    >>> print originalList, '\n', fullCopy
    [1, [2, [3, 4, 100]]]
    [1, [2, [3, 4]]]
    >>>
    
    
      --Jason
    
    
    
    From spamtrap at dot-app.org  Thu Jul 26 13:50:49 2007
    From: spamtrap at dot-app.org (Sherm Pendley)
    Date: Thu, 26 Jul 2007 13:50:49 -0400
    Subject: I am giving up perl because of assholes on clpm -- switching to
    	Python
    References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com>
    	
    	
    Message-ID: 
    
    Steve Holden  writes:
    
    > On c.l.py there are standards of behavior, and we encourage people to
    > observe them (while attempting to engage politely with those who
    > don't).
    
    We also do that on c.l.perl.misc.
    
    The problems tend to arise when people get defensive and argumentative in
    reaction to the polite reminder. For example, "Please don't top-post here.
    Have you read the posting guidelines?" is as polite as it gets - but I've
    lost track of the number of children who respond with variants of "Don't
    tell me how to post! What's with the jerks in this group anyway?"
    
    Just like in any other group, you reap what you sow in c.l.perl.misc.
    
    > I suppose, in fairness, I should admit that the tone of your
    > post is actually far more polite than that of the one you were
    > responding to. I shudder to think what Martha underwent to make her
    > vent like that ...
    
    As far as I can find, it's "her" first post to the group. That, and the
    fact that it was cross-posted, leads me to think it's just trolling.
    
    sherm--
    
    -- 
    Web Hosting by West Virginians, for West Virginians: http://wv-www.net
    Cocoa programming in Perl: http://camelbones.sourceforge.net
    
    
    From ahlongxp at gmail.com  Sat Jul  7 10:51:47 2007
    From: ahlongxp at gmail.com (ahlongxp)
    Date: Sat, 07 Jul 2007 14:51:47 -0000
    Subject: socket: connection reset by server before client gets response
    Message-ID: <1183819907.249945.239700@o11g2000prd.googlegroups.com>
    
    Hi, everyone,
    
        I'm implementing a simple client/server protocol.
    
        Now I've got a situation:
    client will send server command,header paires and optionally body.
    server checks headers and decides whether to accept(read) the body.
    if server decided to throw(dump) the request's body, it'll send back a
    response message, such as  "resource already exists" and close the
    connection.
    the problem is, client will never get the response but a "peer reset"
    exception.
    
    
    any comments or help will be appreciated.
    
    --
    ahlongxp
    
    Software College,Northeastern University,China
    ahlongxp at gmail.com
    http://www.herofit.cn
    
    
    
    From nis at superlativ.dk  Wed Jul  4 09:09:50 2007
    From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=)
    Date: Wed, 04 Jul 2007 15:09:50 +0200
    Subject: Generator for k-permutations without repetition
    In-Reply-To: <1183551857.077116.149310@e16g2000pri.googlegroups.com>
    References: <1183548133.495759.191390@d30g2000prg.googlegroups.com>
    	<468b8df8$0$90275$14726298@news.sunsite.dk>
    	<1183551857.077116.149310@e16g2000pri.googlegroups.com>
    Message-ID: <468b9c2c$0$90275$14726298@news.sunsite.dk>
    
    bullockbefriending bard skrev:
    > On Jul 4, 7:09 pm, Nis J?rgensen  wrote:
    >> bullockbefriending bard skrev:
    >> A quick solution, not extensively tested
    >>
    >> # base needs to be an of the python builtin  set
    >>
    >> def k_perm(base,k):    
    >>         for e in base:  
    >>                 if k == 1:
    >>                         yield [e]      
    >>                 else:
    >>                         for perm in k_perm(base-set([e]),k-1):
    >>                                 yield [e] + perm
    > 
    > thank you!. i'll give this a try. seems to do exactly what i need.
    > sorry about the ambiguity in my example. i chose 3 from 3 merely to
    > keep the size of the example case small, without thinking enough about
    > how it might cause confusion.
    
    I managed to simplify it a little:
    
    def k_perm(base,k):
    	if k == 0:
    		yield []
    	else:
    		for e in base:	
    			for perm in k_perm(base-set([e]),k-1):
    				yield [e] + perm
    
    
    
    Nis
    
    
    From rainwatching at gmail.com  Sun Jul  1 15:30:07 2007
    From: rainwatching at gmail.com (=?ISO-8859-1?Q?S=F6nmez_Kartal?=)
    Date: Sun, 1 Jul 2007 22:30:07 +0300
    Subject: The best platform and editor for Python
    In-Reply-To: <1183317054.513102.127950@q69g2000hsb.googlegroups.com>
    References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com>
    Message-ID: <79a025780707011230p42ce70deg1dfe1b8084006b78@mail.gmail.com>
    
    Hello,
    
    Emacs is the best for anything for me. Some people prefers Eclipse
    with PyDev extension.
    
    Build some real world applications with Python. Pick what do you need
    from SourceForge or similar one then write it. If it is something you
    need then you probably will make it more special then you found and
    this will take you to the more coding and more...
    
    By the way, thanks for winning Magny Cours grand prix Kimi... :-P
    
    On 7/1/07, kimiraikkonen  wrote:
    > Hi,
    > For experienced with Pyhton users, which developing software and
    > enviroment would you suggest for Pyhton programming? Compiler+Editor
    > +Debugger.
    >
    > Also what are your suggestions for beginners of Pyhton programming?
    >
    >
    > Thank you.
    >
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >
    
    
    From the.mindstorm.mailinglist at gmail.com  Fri Jul 20 15:08:57 2007
    From: the.mindstorm.mailinglist at gmail.com (Alex Popescu)
    Date: Fri, 20 Jul 2007 19:08:57 +0000 (UTC)
    Subject: Pythonic way for missing dict keys
    Message-ID: 
    
    Hi all!
    
    I am pretty sure this has been asked a couple of times, but I don't seem 
    to find it on the archives (Google seems to have a couple of problems 
    lately).
    
    I am wondering what is the most pythonic way of dealing with missing 
    keys and default values.
    
    According to my readings one can take the following approaches:
    
    1/ check before (this has a specific name and acronym that I haven't 
    learnt yet by heart)
    
    if not my_dict.has_key(key):
      my_obj = myobject()
      my_dict[key] = my_obj
    else:
      my_obj = my_dict[key]
    
    2/ try and react on error (this has also a specific name, but...)
    
    try:
      my_obj = my_dict[key]
    except AttributeError:
      my_obj = myobject()
      my_dict[key] = my_obj
    
    3/ dict.get usage:
    
    my_obj = my_dict.get(key, myobject())
    
    I am wondering which one is the most recommended way? get usage seems 
    the clearest, but the only problem I see is that I think myobject() is 
    evaluated at call time, and so if the initialization is expensive you 
    will probably see surprises.
    
    thanks in advance,
    ./alex
    --
    .w( the_mindstorm )p.
    
    
    
    From the.mindstorm.mailinglist at gmail.com  Wed Jul 18 05:36:49 2007
    From: the.mindstorm.mailinglist at gmail.com (Alex Popescu)
    Date: Wed, 18 Jul 2007 02:36:49 -0700
    Subject: how to find available classes in a file ?
    In-Reply-To: 
    References: <2e302$469bf38f$d443bb3a$30036@news.speedlinq.nl>
    	<1184627599.597658.267380@g4g2000hsf.googlegroups.com>
    	
    Message-ID: <1184751409.287759.200600@e9g2000prf.googlegroups.com>
    
    On Jul 17, 4:41 am, "Gabriel Genellina" 
    wrote:
    > En Mon, 16 Jul 2007 20:13:19 -0300, Alex Popescu  
    >  escribi?:
    >
    > > On Jul 17, 1:44 am, Stef Mientki 
    > > wrote:
    > >> I want to have a (dynamically) list of all classes defined in a py-file.
    > >> Is there a way of getting this list, without manually parsing the file ?
    >
    > > I have written something that does something like this, but I am not
    > > sure it is the pythonic way.
    > > Bascially I am loading the module and then using dir() on the module
    > > object I am looking for
    > > attribute of the type classobj (for old style classes) and type type
    > > (for new style classes).
    >
    > There is also the pyclbr standard module  
    >  that does not load the  
    > module (just reparses enough of it to get the info needed). So a broken  
    > import, or any other initialization error, won't hurt.
    >
    > > I also heard of the inspect module, but I haven't checked it yet.
    >
    > inspect.getmembers(the_module, inspect.isclass) would do. But this  
    > requires the module to be importable.
    >
    > --
    > Gabriel Genellina
    
    I think I have figured out a difference between how my dir() based
    implementation works
    and the inspect.getmembers(module, inspect.isclass) works. In my
    implementation only the
    classes defined in the module are considered, while the inspect
    functionality returns also the
    imported classes. Am I seeing wrong results on this? (cause the
    documentation is not very clear
    about the inspect part).
    
    ./alex
    --
    .w( the_mindstorm )p.
    
    
    
    
    From crobc at BOGUS.sbcglobal.net  Tue Jul 10 22:55:10 2007
    From: crobc at BOGUS.sbcglobal.net (CC)
    Date: Tue, 10 Jul 2007 19:55:10 -0700
    Subject: Should I use Python for these programs?
    In-Reply-To: 
    References: 
    	
    Message-ID: 
    
    Hendrik van Rooyen wrote:
    >  "CC"  wrote:[edit]
    >>1.  Develop a simple GUI program to run on Linux and Windows which can 
    >>send parameters and small blocks of data to an embedded microcontroller 
    >>device via RS-232 or USB.  Also display simple data (probably single 
    >>numbers) sent from the device.
    > 
    > If you spend a bit of money on a Lantronix Xport, you can use ethernet,
    > and then the linux/windows problems goes away - as sockets seem to 
    > "just work"
    
    Yeah, that's neato.  Trouble is, I work at a national lab, which is 
    where some of these apps will be developed.  They have a big problem 
    with ethernet devices.  Basically, it's almost impossible to use 
    ethernet on other than PCs, on the official LAN.
    
    I will have to look into this further though, as higher data rate stuff 
    is a problem with serial.  Although I could do 10Mbps RS-422 I suppose.
     >>[edit]
    >>I am also confused by the plethora of Python GUI extensions, though 
    >>Tkinter seems like a likely candidate.  I am uncertain if I will have 
    >>difficulty learning how to use this if I don't know Tcl/Tk.
    > 
    > No - there are excellent examples and docs available on the web.
    > Unless you are doing something very fancy, you dont "need" to know Tcl.
    > 
    > The development cycle is fast, and if you get stuck you can get help
    > here - this is a super group of people (said he modestly...   :- )  )
    
    Yeah, that's really great.  Our in-house programmer uses wxPython, I've 
    discovered, so that's a strong push in that direction.  Though he isn't 
    totally unfamiliar with TkInter too.
    
    >>Do you think Python is the right language for these projects?
    > 
    > Yes - I am in the process of finishing an Injection Moulding Machine 
    > Controller, with the GUI in tkinter (cos its in the standard library),
    > with some crude animation of the machine functions - and it all "just works"
    
    Thanks for the input.
    
    I am not seeing anything to indicate that Python isn't the direction in 
    which I should head.
    
    Good day!
    
    
    -- 
    _____________________
    Christopher R. Carlen
    crobc at bogus-remove-me.sbcglobal.net
    SuSE 9.1 Linux 2.6.5
    
    
    From orlenko at gmail.com  Wed Jul  4 01:32:22 2007
    From: orlenko at gmail.com (Volodya)
    Date: Wed, 04 Jul 2007 05:32:22 -0000
    Subject: using boost to extend python with c++
    In-Reply-To: 
    References: 
    Message-ID: <1183527142.007320.27080@j4g2000prf.googlegroups.com>
    
    Please see http://lists.boost.org/boost-build/2007/05/16666.php -- the
    solution is to add "using python ;" to tools/build/v2/user-config.jam.
    
    
    
    From brian at rkspeed-rugby.dk  Sat Jul 28 04:54:37 2007
    From: brian at rkspeed-rugby.dk (Brian Elmegaard)
    Date: Sat, 28 Jul 2007 07:54:37 -0100
    Subject: Compile python with Mingw
    References: 
    	
    Message-ID: 
    
    iwinux  writes:
    
    > To build python with mingw, there is a common way.
    > First you should install msys, which can be downloaded from mingw's website.
    > Run msys and type 'cd /path/to/source'.
    > Then type "./configure & make & make install".
    > And you will get a python built with mingw.
    
    It would be nice if this was the situation. I just tested without
    success. Do you say that the instructions in e.g. the first three hits
    on http://www.google.com/search?q=python+mingw are no longer relevant?
    
    
    
    -- 
    Brian (remove the sport for mail)
    http://www.et.web.mek.dtu.dk/Staff/be/be.html
    http://www.rugbyklubben-speed.dk
    
    
    From aleax at mac.com  Mon Jul 16 23:48:31 2007
    From: aleax at mac.com (Alex Martelli)
    Date: Mon, 16 Jul 2007 20:48:31 -0700
    Subject: Accessing Python variables in an extension module
    References: <1184553584.757696.92630@g4g2000hsf.googlegroups.com>
    	<1i1b7zw.64m7g071sk32N%aleax@mac.com>
    	<1184591293.938223.105800@o61g2000hsh.googlegroups.com>
    	<1i1c33r.1tle2a728vehlN%aleax@mac.com>
    	<1184609767.983621.151500@o61g2000hsh.googlegroups.com>
    Message-ID: <1i1cyy7.tgyr961pog5plN%aleax@mac.com>
    
    MD  wrote:
    
    > Hi Alex,
    >   Thanks for the answer. Are there any C defines (for e.g. STRING,
    > BOOLEAN) corresponding to each Python type?
    
    No, I know of no such "defines" -- what good would they do?
    
    
    Alex
    
    
    From nagle at animats.com  Tue Jul  3 02:15:44 2007
    From: nagle at animats.com (John Nagle)
    Date: Mon, 02 Jul 2007 23:15:44 -0700
    Subject: PEP 3107 and stronger typing (note: probably a newbie question)
    In-Reply-To: <1i0n0tr.ve0o791347ugyN%aleax@mac.com>
    References: 
    	<1182369568.941307.316260@p77g2000hsh.googlegroups.com>
    	
    	<5dveb4F360un0U1@mid.individual.net>
    	
    	<467a9209$0$22165$426a74cc@news.free.fr>
    	<1182858785.886469.93060@n60g2000hse.googlegroups.com>
    	<46824d8d$0$2324$426a74cc@news.free.fr>
    	
    	<4682eddc$0$23164$426a74cc@news.free.fr>
    	<5ehokpF38ov3jU2@mid.individual.net>
    	<4683d5cd$0$8993$426a74cc@news.free.fr>
    	<7xps3e3g9x.fsf@ruckus.brouhaha.com>
    	<468565a0$0$3686$426a74cc@news.free.fr>
    	<7xhcopj10g.fsf@ruckus.brouhaha.com>
    	<46863ea7$0$970$426a34cc@news.free.fr>
    	<1i0ikru.1uccqtm1efnzn3N%aleax@mac.com>
    	
    	<1i0n0tr.ve0o791347ugyN%aleax@mac.com>
    Message-ID: 
    
    Alex Martelli wrote:
    > Donn Cave  wrote:
    > 
    > 
    >>In article <1i0ikru.1uccqtm1efnzn3N%aleax at mac.com>,
    >> aleax at mac.com (Alex Martelli) wrote:
    >>
    >>
    >>>"Dynamic typing is recommended", they conclude, "when programs must be
    >>>as flexible as possible".  I recommend reading the Agile Manifesto to
    >>>understand why maximal flexibility is crucial in most real-world 
    >>>application programming -- and therefore why, in said real world rather
    >>>than in the more academic circles Dr. Van Roy and Dr. Hadidi move in,
    >>>dynamic typing is generally preferable, and not such a tiny issue as
    >>>they make the difference to be.
    >>
    >>I guess there may be more than one kind of flexibility.  The language
    >>I fool around with sometimes that has strong static typing is Haskell.
    >>Though a relatively elementary Haskell programmer (the learning curve
    >>with this language is something you would have to experience to believe),
    > 
    > 
    > I do have (some of:-) that experience, and am reasonably at ease in
    > Haskell (except when it comes to coding monads, which I confess I still
    > have trouble wrapping my head around).
    > 
    > 
    >>I feel that the type checking actually helps me program faster.
    >>The compiler's check for structural correctness is after all for my
    >>benefit, and expedites development and maintenance of code, in my
    >>limited experience.  The more extensive my changes, the more useful
    >>the type checking is - I'm much more casual about significant code
    >>revision when writing in Haskell, somewhat more casual when writing
    >>in C, and worried when writing Python.
    > 
    > 
    > Eckel's and Martin's well-known essays on why good testing can replace
    > strict static type checking:
    > 
    > 
    
         He's all over the place in that article.  He really isn't talking
    about strong typing at all.  What he does make a case
    for is dispatch by name without inheritance, or "duck typing".
    But that, in fact, is a form of strong type checking.  The effect is
    as if "object" had an abstract function for every member function
    in the whole program.  (And, in fact, in Python you pay exactly the
    dispatch cost that would take.)
    
         The problem is that in both C++ and Java, the first round
    of the type system was botched.  C++ originally had neither
    generics nor checked downcasting (a la "dynamic_cast").
    Java originally lacked generics.  Both languages added those
    as bolt-ons, and it shows.
    
         But, again, this really isn't a Python issue.
    
    				John Nagle
    
    
    From sjmachin at lexicon.net  Tue Jul  3 07:47:10 2007
    From: sjmachin at lexicon.net (John Machin)
    Date: Tue, 03 Jul 2007 04:47:10 -0700
    Subject: 15 Exercises to Know A Programming Language
    In-Reply-To: <1183456696.168214.114900@o61g2000hsh.googlegroups.com>
    References: <1183456696.168214.114900@o61g2000hsh.googlegroups.com>
    Message-ID: <1183463230.092640.102720@j4g2000prf.googlegroups.com>
    
    On Jul 3, 7:58 pm, Martin  wrote:
    > I am trying to improve my Python skills through some exercises.
    > Currently I am working on Larry's "15 exercises to know a programming
    > language " (http://www.knowing.net/
    > PermaLink,guid,f3b9ba36-848e-43f8-9caa-232ec216192d.aspx). The first
    > exercise is this:
    >
    > "Write a program that takes as its first argument one of the words
    > 'sum,' 'product,' 'mean,' or 'sqrt'  and for further arguments a
    > series of numbers. The program applies the appropriate function to
    > the series."
    >
    > My solution so far is this:
    >
    > http://dpaste.com/13469/
    >
    > I would really like some feedback. Is this a good solution? is it
    > efficient? robust? what could be improved? any not looking for a
    > revised solution, hints on what to improve are also very welcome.
    >
    > Martin
    
    sum is a builtin function in Python 2.3 and later. You could do
    something like this:
    
    try:
        sum
    except NameError:
        def sum(args):
            return reduce(operator.add, args)
    
    Tested with 2.5 back to 2.1, and 1.5.2 :-)
    
    
    
    From rustompmody at gmail.com  Fri Jul 20 00:09:13 2007
    From: rustompmody at gmail.com (Rustom Mody)
    Date: Fri, 20 Jul 2007 09:39:13 +0530
    Subject: Pickled objects over the network
    Message-ID: 
    
    Irmen de Jong wrote
    > In what way would Pyro be overkill where Yaml (also a module that you need
    > to install separately) wouldn't be?
    
    Sure they are the same to install and sure pyro can do the job (pyro
    is a nice package).
    
    But I got the impression that the questioner wanted to do the
    networking stuff himself at a low level (using sockets) and the data
    management using some available library -- pickle.
    
    Since pickle has problems
    -- does not interface well with networking
    -- security issues
    -- has an xml option that according to the docs is an order of magnitude slower
    
    I thought I would point out yaml (with safe-load) which sits somewhere
    inbetween the xml-pickle and the default pickle.
    
    I should also mention here that I find yaml is much more known and
    used in the ruby and perl world than in the python world.  This is
    unfortunate considering that both ruby and perl have a traditional
    syntax (begin end, { } etc ).  On the other hand, python and yaml have
    similar modern syntactic structures -- structure follows indentation
    -- and are therefore well matched to each other.
    
    So in summary the 'competition' is not between yaml and pyro -- pyro
    could easily have a pickle-using-yaml option -- but between yaml and
    xml.
    
    
    From dave at boost-consulting.com  Tue Jul  3 18:51:45 2007
    From: dave at boost-consulting.com (David Abrahams)
    Date: Tue, 03 Jul 2007 18:51:45 -0400
    Subject: import mysteries
    References: 
    	<87wsxwvj9g.fsf@benfinney.id.au>
    Message-ID: <876451nlry.fsf@grogan.peloton>
    
    
    on Thu Jun 21 2007, Ben Finney  wrote:
    
    > David Abrahams  writes:
    >
    >> I'm pretty comfortable with Python, but recently I'm constantly
    >> finding mysterious issues with import.  For example, looking at
    >>
    >>   http://genshi.edgewall.org/browser/trunk/genshi/filters/transform.py
    >>
    >> the examples use the symbol 'HTML' but it's not defined locally, it's
    >> not explicitly imported, and there's no import *.  Yet doctest will
    >> test this module and it passes with flying colors.  It turns out HTML
    >> is defined in genshi.input.  How do I know that?  I grepped for it.
    >> How does it become available to this module?
    >
    > That's a mystery to me too. I can't see by looking at the module where
    > this 'HTML' name comes from, and as you say there is no import of
    > 'genshi.input'.
    >
    > Whatever the explanation, it's a violation of one of the strengths of
    > Python: namespaces. Names that appear in the current namespace (as
    > happens with 'from foo import *', and as seems to be happening here)
    > are bad programming style, for exactly the reason that they make the
    > code more difficult to understand.
    
    Sometimes that's true, but I disagree with it as a general rule.  Some
    bindings are idiomatic, in widespread use throughout a project, and
    would look dumb and make the code too verbose and hard-to-understand
    if qualified (especially if fully qualified).
    
    The practice may make it harder to understand when something goes wrong, but
    that's a separate issue.
    
    -- 
    Dave Abrahams
    Boost Consulting
    http://www.boost-consulting.com
    
    The Astoria Seminar ==> http://www.astoriaseminar.com
    
    
    
    From bignose+hates-spam at benfinney.id.au  Thu Jul 12 08:53:17 2007
    From: bignose+hates-spam at benfinney.id.au (Ben Finney)
    Date: Thu, 12 Jul 2007 22:53:17 +1000
    Subject: bool behavior in Python 3000?
    References:  
    	
    	<5ficp9F3cram2U2@mid.individual.net>
    	
    	<469472f4$0$1293$9b622d9e@news.freenet.de>
    	
    	
    	
    Message-ID: <87hco9kcle.fsf@benfinney.id.au>
    
    "Terry Reedy"  writes:
    
    > In Guido's opinion (and mine, but his counts 100x), the positive
    > benefits of the current implementation are greater than the net
    > positive benefits of a 'pure' type.  See
    >
    > http://www.python.org/dev/peps/pep-0285/
    
    I assume you're referring to:
    
        6) Should bool inherit from int?
    
        => Yes.
    
           In an ideal world, bool might be better implemented as a
           separate integer type that knows how to perform mixed-mode
           arithmetic.  However, inheriting bool from int eases the
           implementation enormously [...further explanation...]
    
    I accept Guido's explanation in the PEP, that the implementation is
    made much easier, as an explanation of why bool inherits from int. I
    haven't seen people here expressing that they want the opposite.
    
    To my mind the more fundamental issue is this one:
    
        4) Should we strive to eliminate non-Boolean operations on bools
           in the future, through suitable warnings, so that for example
           True+1 would eventually (in Python 3000) be illegal?
    
        => No.
    
           There's a small but vocal minority that would prefer to see
           "textbook" bools that don't support arithmetic operations at
           all, but most reviewers agree with me that bools should always
           allow arithmetic operations.
    
    Frustratingly, unlike the above point about inheritance, the PEP gives
    no explanation of why the answer to this is "No". All we get is "most
    reviewers agree", with no explanation of *why*.
    
    So, I'm left with the points already made in this thread as to why the
    answer should be "yes", and no source online for an official
    explanation of the "no".
    
    -- 
     \          "I don't like country music, but I don't mean to denigrate |
      `\          those who do. And for the people who like country music, |
    _o__)                     denigrate means 'put down'."  -- Bob Newhart |
    Ben Finney
    
    
    From bdesth.quelquechose at free.quelquepart.fr  Tue Jul 10 23:04:18 2007
    From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers)
    Date: Wed, 11 Jul 2007 05:04:18 +0200
    Subject: xml yml and dependency hell
    In-Reply-To: 
    References: 
    Message-ID: <4693d7f9$0$29737$426a74cc@news.free.fr>
    
    Rustom Mody a ?crit :
    > yaml by its indent-orientation is quite pythonic.  In comparison xml
    > is cumbersome and laborious.
    > 
    > Strangely ruby supports yaml out of the box but python requires a
    > third party package PyYAML.
    > 
    > Now this may not seem like a big deal for us -- installing pyYAML
    > takes all of one minute -- but it may not be so to others as I
    > recently learned.
    > 
    > I conducted a python training for a corporate in which I showed among
    > other things that yaml is much neater than xml.  They agreed that it
    > was neat but were reluctant to consider it because it adds dependency
    > headaches at a later point with their customers.
    > 
    > So is it likely that yaml will make it to the standard python library
    > at some point??
    
    "dependency headaches" ? AFAICT from the project's site, pyYAML is a 
    pure Python package, and the only requirement mentioned is Python 2.3. 
    Compared to some products often in use in "corporate" environment, I 
    wouldn't call this a "dependency headaches".
    
    Not that I disagree with the idea of including pyYAML in the standard 
    lib - this would be in pahse with the "batteries included" philosophie 
    IMHO - but then, what about python-json ? FWIW, JSON being another 
    pretty good alternative to XML, and probably more used than YAML, thanks 
    to the Ajax/Web2.0 madness.
    
    But anyway, the inclusion of a package in the standard lib is a somehow 
    formalized process (cf pep 0002 [1]), supposed to be initiated by the 
    package's maintainers. So if you want this to happen for pyYAML, you'll 
      first have to talk about it with the project's leaders.
    
    [1] http://python.org/dev/peps/pep-0002/
    
    
    From george.sakkis at gmail.com  Thu Jul  5 23:13:57 2007
    From: george.sakkis at gmail.com (George Sakkis)
    Date: Fri, 06 Jul 2007 03:13:57 -0000
    Subject: PEP 3107 and stronger typing (note: probably a newbie question)
    In-Reply-To: 
    References: <1182858785.886469.93060@n60g2000hse.googlegroups.com>
    	<46824d8d$0$2324$426a74cc@news.free.fr>
    	
    	<4682eddc$0$23164$426a74cc@news.free.fr>
    	<5ehokpF38ov3jU2@mid.individual.net>
    	<4683d5cd$0$8993$426a74cc@news.free.fr>
    	<7xps3e3g9x.fsf@ruckus.brouhaha.com>
    	<468565a0$0$3686$426a74cc@news.free.fr>
    	<7xhcopj10g.fsf@ruckus.brouhaha.com>
    	<46863ea7$0$970$426a34cc@news.free.fr>
    	<1i0ikru.1uccqtm1efnzn3N%aleax@mac.com>
    	
    	<1i0n0tr.ve0o791347ugyN%aleax@mac.com>
    	<7xd4za1086.fsf@ruckus.brouhaha.com>
    	<5f0mhuF3b0stbU1@mid.individual.net>
    	<7xd4z837e2.fsf@ruckus.brouhaha.com>
    	<468b7426$0$9063$426a34cc@news.free.fr>
    	<7x4pkkun56.fsf@ruckus.brouhaha.com>
    	<1183575597.272150.152200@w5g2000hsg.googlegroups.com>
    	
    Message-ID: <1183691637.051351.304700@k79g2000hse.googlegroups.com>
    
    On Jul 5, 3:24 pm, Donn Cave  wrote:
    > In article <1183575597.272150.152... at w5g2000hsg.googlegroups.com>,
    >  Paul Boddie  wrote:
    >
    > > However, it's interesting to consider the work that sometimes needs to
    > > go in to specify data structures in some languages - thinking of ML
    > > and friends, as opposed to Java and friends. The campaign for optional
    > > static typing in Python rapidly became bogged down in this matter,
    > > fearing that any resulting specification for type information might
    > > not be the right combination of flexible and powerful to fit in with
    > > the rest of the language, and that's how we really ended up with PEP
    > > 3107: make the semantics vague and pretend it has nothing to do with
    > > types, thus avoiding the issue completely.
    >
    > I missed the campaign for optional static typing, must have been
    > waged in the developer list.  Unless it was not much more than
    > some on-line musings from GvR a year or two ago.  I don't see
    > how it could ever get anywhere without offending a lot of the
    > Python crowd, however well designed, so I can see why someone
    > might try to sneak it past by pretending it has nothing to do
    > with types.  But he didn't -- look at the examples, I think he
    > rather overstates the potential for static typing applications.
    
    The key point is that this is left to 3rd party libraries; the
    language won't know anything more about static typing than it does
    now. FWIW, there is already a typechecking module [1] providing a
    syntax as friendly as it gets without function annotations. If the
    number of its downloads from the Cheeshop is any indication of static
    typing's popularity among Pythonistas, I doubt that PEP 3107 will give
    significant momentum to any non-standard module anytime soon.
    
    George
    
    
    [1] http://oakwinter.com/code/typecheck/
    
    
    
    From martin at v.loewis.de  Thu Jul  5 02:30:05 2007
    From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=)
    Date: Thu, 05 Jul 2007 08:30:05 +0200
    Subject: login http://cheeseshop.python.org/pypi broken ?
    In-Reply-To: <1183606025.475352.230270@k79g2000hse.googlegroups.com>
    References: <1183606025.475352.230270@k79g2000hse.googlegroups.com>
    Message-ID: <468C8FED.3000801@v.loewis.de>
    
    gert schrieb:
    > tried reseting password but i can not login anymore to upload my new
    > source code ?
    
    Please try again. It was a misconfiguration which should be fixed now.
    
    Regards,
    Martin
    
    
    From sjmachin at lexicon.net  Tue Jul 17 18:29:58 2007
    From: sjmachin at lexicon.net (John Machin)
    Date: Wed, 18 Jul 2007 08:29:58 +1000
    Subject: Interpreting non-ascii characters.
    In-Reply-To: 
    References: 
    Message-ID: <469d42e6@news.eftel.com.au>
    
    On 18/07/2007 4:11 AM, ddtl wrote:
    > Hello everybody,
    > 
    > I want to create a script which reads files in a
    > current directory and renames them according to some
    > scheme. The file names are in Russian - sometimes 
    > the names encoded as win-1251, sometimes as koi8-r etc. 
    
    You have a file system with 8-bit file names with no indication of 
    'codepage' or 'encoding', either globally or per file? Which operating 
    system are you using?
    
    > I want to read in file name and convert it to list for 
    > further processing.
    
    Read file name from a text file? Or do you mean using e.g. glob.glob() 
    or os.listdir()
    
    What do you mean by "convert it to list"? Do you mean 'foo.txt' -> ['f', 
    'o', ....etc]??? Why?
    
    >  The problem is that Python treats 
    > non-ascii characters as multibyte characters - for 
    > example, hex code for "Small Character A" in koi8-r is 
    > 0xc1, but Python interprets it as a sequence of 
    > \xd0, \xb1 bytes.
    
    Python is very unlikely to do that all by itself. Please show us the 
    script or whatever evidence you have. I strongly suggest that 
    immediately after "reading" a file name, you do
         print repr(file_name)
    NOT
         print file_name
    so that you can see *exactly* what you've got.
    
    Are you sure about the \xb1??? Consider this:
    
     >>> '\xc1'.decode('koi8-r')
    u'\u0430'
     >>> '\xc1'.decode('koi8-r').encode('utf8')
    '\xd0\xb0'
     >>>
    
    Also:
     >>> import sys; sys.stdout.encoding
    'cp850' # Win XP Pro, command prompt
     >>>
    What do you get when you do that?
    
    > 
    > What can I do so that Python interprets non-ascii 
    > characters correctly?
    
    Know how your non-ascii characters are encoded. Tell Python what to do 
    with them.
    
    Read this:
    http://www.amk.ca/python/howto/unicode
    
    Hope this helps,
    John
    
    
    From gh at ghaering.de  Tue Jul 10 11:33:10 2007
    From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=)
    Date: Tue, 10 Jul 2007 17:33:10 +0200
    Subject: How to check if file is in use?
    In-Reply-To: <1184081115.465263.215830@q75g2000hsh.googlegroups.com>
    References: <1184081115.465263.215830@q75g2000hsh.googlegroups.com>
    Message-ID: <5fhn5nF39vf60U1@mid.uni-berlin.de>
    
    loial wrote:
    > Is there anyway in pythn to check whether a file is being used/written
    > to by another process, e.g like the fuser command?
    
    No, you'll have to use platform-specific methods (like calling fuser 
    etc. with the subprocess module).
    
    -- Gerhard
    
    
    From axjacob at comcast.net  Mon Jul  9 14:23:53 2007
    From: axjacob at comcast.net (axjacob at comcast.net)
    Date: Mon, 09 Jul 2007 18:23:53 +0000
    Subject: Class file location
    Message-ID: <070920071823.4178.46927D39000DDCBF0000105222007510900D010C0E06A10407020E@comcast.net>
    
    
    My mistake. It is Jython.
    
     -------------- Original message ----------------------
    From: Bjoern Schliessmann 
    > axjacob at comcast.net wrote:
    > > Is there a way to define a different directory for the generated
    > > .class(*$py.class) files than the current directory where the
    > > python scripts are located and executed from?
    > 
    > Excuse me, since when does python generate .class files?
    > 
    > Regards,
    > 
    > 
    > Bj?rn
    > 
    > -- 
    > BOFH excuse #439:
    > 
    > Hot Java has gone cold
    > 
    > -- 
    > http://mail.python.org/mailman/listinfo/python-list
    
    
    
    From lgxror at gmail.com  Fri Jul 13 03:21:07 2007
    From: lgxror at gmail.com (lgx)
    Date: Fri, 13 Jul 2007 07:21:07 -0000
    Subject: Question about PyDict_SetItemString
    Message-ID: <1184311267.876950.150040@e16g2000pri.googlegroups.com>
    
    Does PyDict_SetItemString(pDict,"key",PyString_FromString("value"))
    cause memory leak?
    
    >From Google results, I find some source code write like that. But some
    code write like below:
    
    obj =  PyString_FromString("value");
    PyDict_SetItemString(pDict,"key",obj);
    Py_DECREF(obj);
    
    So, which one is correct?
    
    
    
    From Eric_Dexter at msn.com  Mon Jul  9 07:27:59 2007
    From: Eric_Dexter at msn.com (Eric_Dexter at msn.com)
    Date: Mon, 09 Jul 2007 04:27:59 -0700
    Subject: trouble controlling vim with subprocess on windows machine
    In-Reply-To: 
    References: <1183970186.663847.4380@o61g2000hsh.googlegroups.com>
    	
    Message-ID: <1183980479.328397.241300@q75g2000hsh.googlegroups.com>
    
    On Jul 9, 5:30 am, Nick Craig-Wood  wrote:
    > Eric_Dex... at msn.com  wrote:
    > >       I am having trouble contolling vim with subprocess on a windows
    > >  machine.  It appears that vim comes up on the machine all right and it
    > >  sometimes looks like it is doing the searchs what I am asking it to do
    > >  but when I am asking it to load a file it doesn't do anything.  Is
    > >  there something I need to do to push the data through the pipe??  Here
    > >  is a couple different ways I am trying to do it.
    >
    > For controlling an interactive program subprocess isn't the right
    > tool.  Subprocess only really does one way communication - it isn't
    > good at conversations.  I'd suggest pexpect but it doesn't work on
    > windows.
    >
    > You appear to be doing stuff with csound.  There are several python
    > modules out there which interface with csound - did you investigate
    > those?
    >
    > --
    > Nick Craig-Wood  --http://www.craig-wood.com/nick
    
    The book (as kramer would say)
    
    https://sourceforge.net/projects/dex-tracker
    
    I would think that the purpose for stdin is input and stdout is
    output..  otherwise why have stdin??  The pyexpect does look like what
    I am after  but it isn't windows..  And did I mention I am willing to
    cheat I have a large number of unix tools that are converted over (but
    not cigwin) and will even be willing to generate a script file if I
    can get it to vim when it starts up...  whatever it takes regardless
    of how ugly looking it is.
    
    I did notice expect
    
    http://expect.nist.gov/#windows
    http://bmrc.berkeley.edu/people/chaffee/tcltk.html
    
    I am not sure what to do to call the tcl stuff from python though.
    
    
    
    From grahn+nntp at snipabacken.dyndns.org  Tue Jul  3 06:03:45 2007
    From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn)
    Date: 3 Jul 2007 10:03:45 GMT
    Subject: Python and ARexx (was Re: Tiny/small/minimalist Python?)
    References: <1183332951.122782.212720@o11g2000prd.googlegroups.com>
    	<7xved3satm.fsf@ruckus.brouhaha.com>
    	<1183389420.175712.59460@z28g2000prd.googlegroups.com>
    	<7xmyyeizf8.fsf@ruckus.brouhaha.com>
    	<468997c7$0$327$e4fe514c@news.xs4all.nl>
    	
    Message-ID: 
    
    On Tue, 03 Jul 2007 05:25:28 GMT, Dennis Lee Bieber  wrote:
    > On Tue, 03 Jul 2007 02:26:43 +0200, Irmen de Jong
    >  declaimed the following in comp.lang.python:
    >
    >> Back in the days my port of Python to the Commodore Amiga machine ran
    >> quite comfortably on a 50 mhz CPU with 4 Mb of RAM. (ok ok it was
    ...
    
    > And your's was likely more powerful than mine... I only had 2MB and no MMU
    > 1.5.2 was great (and even more fun combined with ARexx)
    
    How does Python combine with ARexx?  Can you control applications
    which provide an ARexx interface?
    
    I stopped using my Amiga 4000/030 in 1996 or so, long before I
    realized C isn't always the best choice for getting things done. I
    messed around a bit with ARexx though, and while I found it neat to be
    able to script an application from the inside or from the outside
    using ARexx, I didn't really care for the language itself -- too
    primitive for anything but the tiniest programs.
    
    /Jorgen
    
    -- 
      // Jorgen Grahn   R'lyeh wgah'nagl fhtagn!
    
    
    From infocat at earthlink.net  Tue Jul 10 00:38:34 2007
    From: infocat at earthlink.net (Frank Swarbrick)
    Date: Mon, 09 Jul 2007 22:38:34 -0600
    Subject: socket.makefile() buggy?
    In-Reply-To: <1183970531.241008.295940@z28g2000prd.googlegroups.com>
    References: <1183892789.434028.15370@x35g2000prf.googlegroups.com>
    	
    	<1183970531.241008.295940@z28g2000prd.googlegroups.com>
    Message-ID: <5fggq9F3bk2rrU1@mid.individual.net>
    
    ahlongxp wrote:
    > On Jul 8, 9:54 pm, Steve Holden  wrote:
    >> That's a pretty pejorative subject line for someone who's been
    >> programming Python [guessing by the date of your first post] for about a
    >> month.
    >>
    > I have to admit it that I'm quite  a newbie programmer.
    >> Perhaps "Incomprehensible behavior from socket.makefile()", or "I have
    >> written a buggy network application"? That would at least show that you
    >> are considering the possibility you yourself are the cause of the
    >> problem ;-)
    >>
    > Thanks. I'll be more careful about my words.
    > but I did show some possibility myself is the cause of the problem.
    > Is there any chance you missed the "?" and "guess" at the same time.
    > 
    >> Python has been around for a long time, so you should ask yourself how
    >> likely it is that you would be the first to discover such a fundamental
    >> flaw?
    > very low but not zero.
    > Miracle happens.
    > 
    >> I'd be very surprised if someone doesn't point you at an article
    >> on "how to ask smart questions", but I will content myself with that
    >> oblique reference.
    >>
    >>
    > The big problem is that, I didn't know such a person like you before.
    > It's my misfortune.
    > 
    > 
    >> The big problem here seems to be that your server is closing the socket
    >> after reading 99 bytes, but the client is actually sending 120. If you
    >> change the "99" in the server to "120" you will see that the client
    >> works when it uses the makefile().read(). I can't be bothered to debug
    >> the exact reason why the 21 bytes of buffered data doesn't cause a
    >> problem with the recv() version, but I wouldn't regard the error you are
    >> getting as a bug in Python, rather as a bug in your application.
    >>
    > I don't know the underlying details of networking.
    > But with recv()  version I can get things done as expected while
    > makefile()
    > version can't.
    > I guess it's not that unreasonable to make a guess like I did.
    >> The underlying cause of all this appears to be your failure to
    >> understand that network protocols should ideally allow the endpoints to
    >> determine when a complete message has been transmitted, and to consume
    >> all transmitted data.
    >>
    >> You can't just ignore some or all of a client request and expect it not
    >> to cause problems.
    > Back to the problem, I make it working  by adding a sleep(0.5) just
    > before the
    > server closes the connection.
    > Actually this is Hendrik van Rooyen's idea.
    > And luckily I got a another lesson
    > http://groups.google.com/group/comp.lang.python/browse_thread/thread/9c5ad2608f4c80d5/4302772dfe27d8f1#4302772dfe27d8f1
    
    It would be nice to know just exactly what you are trying to achieve. 
    Sure, adding the sleep(0.5) works, but I think that is just a 
    work-around and doesn't really fix the underlying problem.  The 
    underlying problem, of course, being that the server is closing the 
    connection while the client is still trying to send data.
    
    Seems to me what you really want to do is either have the send and the 
    recv in different threads, or use non-blocking sockets and select.  Or 
    maybe you don't even need to use select necessarily.  Seems like you 
    could use non-blocking sockets and then attempt a recv after each send, 
    in order to see if the response is ready.  You want to use a 
    non-blocking socket so that if there's no response ready the recv will 
    not block waiting for one.  Maybe after your last send you'd want to put 
    it back in blocking mode prior to doing the final recv.  Or something 
    that that!  :-)
    
    Hope that gives you a start, or at least some better questions to ask.
    
    Frank
    
    
    From tdelaney at avaya.com  Wed Jul  4 19:08:18 2007
    From: tdelaney at avaya.com (Delaney, Timothy (Tim))
    Date: Thu, 5 Jul 2007 07:08:18 +0800
    Subject: Plugging a pseudo-memory leak
    In-Reply-To: <1183514371.042373.162020@k29g2000hsd.googlegroups.com>
    Message-ID: 
    
    Adam Atlas wrote:
    
    > I have a program that seemed to be leaking memory, but after
    > debugging, it seemed it just wasn't getting around to collecting the
    > objects in question often enough. The objects are very long-lived, so
    > they probably end up in generation 2, and don't get collected for a
    > long time. Is there any way I can force collection of these objects? I
    > know in Python 2.5 there's gc.collect(2), but I want to keep it
    > compatible with previous versions of Python.
    
    Best way is to not create cycles. See if you can change some strong
    references to weakrefs.
    
    Tim Delaney
    
    
    From ladaan at iptel.org  Tue Jul 17 04:59:36 2007
    From: ladaan at iptel.org (Ladislav Andel)
    Date: Tue, 17 Jul 2007 10:59:36 +0200
    Subject: lists and dictionaries
    In-Reply-To: <1184249680.684670.290650@k79g2000hse.googlegroups.com>
    References: 
    	<1184249680.684670.290650@k79g2000hse.googlegroups.com>
    Message-ID: <469C84F8.40500@iptel.org>
    
    Hi,
    could you actually help me further?
    I thought it will quite easy but I've been programming in python just 
    for a month.
    I need to add extra items in new list.
    So here is example:
    
    I have a list of dictionaries.
    e.g.
    [{'index': 0, 'ip_addr': '1.2.3.4', 'server-name':'Asterisk', 'transport': 'udp', 'service_domain': 'dp0.example.com'},
    {'index': 1, 'ip_addr': '5.6.7.8', 'server-name':'Asterisk', 'transport': 'udp', 'service_domain': 'dp1.example.com'},
    {'index': 0, 'ip_addr': '1.2.3.4', 'server-name': 'Yes', 'transport': 'tcp', 'service_domain': 'dp0.example.com'},
    {'index': 1, 'ip_addr': '5.6.7.8', 'server-name': 'Yes', 'transport': 'tcp', 'service_domain': 'dp1.example.com'}]
    
    The server-name within tcp test is not known because I just open connection at port where the server should run and if succeeded then server-name = Yes. In newlist should be the server name Asterisk though.
    
    how could I make a new list of dictionaries which would look like:
    [{'transports': ['udp','tcp'], 'service_domain': 'dp0.example.com', 'ip_addr': '1.2.3.4', 'server-name':'Asterisk'},
    {'transports': ['udp','tcp'], 'service_domain': 'dp1.example.com', 'ip_addr': '5.6.7.8', 'server-name':'Asterisk'}]
    
    I was trying to implement it to existing code but I'm not really 
    successful so far.
    
    Thank you for your help.
    
    Lada
    
    Bart Ogryczak wrote:
    > On 11 jul, 21:08, Ladislav Andel  wrote:
    >   
    >> Hi,
    >> I have a list of dictionaries.
    >> e.g.
    >> [{'index': 0, 'transport': 'udp', 'service_domain': 'dp0.example.com'},
    >> {'index': 1, 'transport': 'udp', 'service_domain': 'dp1.example.com'},
    >> {'index': 0, 'transport': 'tcp', 'service_domain': 'dp0.example.com'},
    >> {'index': 1, 'transport': 'tcp', 'service_domain': 'dp1.example.com'}]
    >>
    >> how could I make a new list of dictionaries which would look like:
    >> [{'transports': ['udp','tcp'], 'service_domain': 'dp0.example.com'},
    >> {'transports': ['udp','tcp'], 'service_domain': 'dp1.example.com'}]
    >>
    >> Could you help me, please?
    >>     
    >
    > doms = {}
    > for entry in oldList:
    >     doms.setdefault(entry['service_domain'],
    > []).append(entry['transport'])
    > newList = [{'transports': t, 'service_domain': d} for d,t in
    > doms.iteritems()]
    >
    >
    >   
    
    
    
    From steve at holdenweb.com  Wed Jul  4 08:34:32 2007
    From: steve at holdenweb.com (Steve Holden)
    Date: Wed, 04 Jul 2007 08:34:32 -0400
    Subject: issues with htmlparser.getpos
    In-Reply-To: <1183548847.515341.293540@q69g2000hsb.googlegroups.com>
    References: <1183548847.515341.293540@q69g2000hsb.googlegroups.com>
    Message-ID: 
    
    dysmas wrote:
    > Hi,
    > 
    > 
    > Im having an issue with HTMLParser, the getpos() funtion sometimes
    > returns things like :
    > 
    > (1, 1247)
    > (1, 2114)
    > (1, 2168)
    > (1, 2228)
    > (1, 2295)
    > (1, 2382)
    > (1, 2441)
    > (1, 2963)
    > (1, 3040)
    > 
    > i guess this is because the HTMLParser has not correctly parsed the
    > newline characters in the string fed to it... is there a workaround
    > for this, without checking the string every time i feed it some data?
    > 
    Have you verified that these results aren't correct? There is no 
    requirements for newlines in HTML, and some computer-generated pages 
    don't bother to insert 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 http  Tue Jul 24 05:02:17 2007
    From: http (Paul Rubin)
    Date: 24 Jul 2007 02:02:17 -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>
    Message-ID: <7x8x96fa3q.fsf@ruckus.brouhaha.com>
    
    NicolasG  writes:
    > 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.
    
    Why would you want to become a programmer?  Programmers smell bad,
    they have no social life, they get treated like crap by everyone.
    They can get paid pretty well but then they spend all the money on
    useless electronic junk so they still live like bums.  There is only
    one reason to be a programmer, which is that the drive to program
    burns in you like a fire.  But in that case don't ask how to become a
    programmer, because you are already one, so welcome to the ranks ;-).
    
    
    From greg at cosc.canterbury.ac.nz  Tue Jul 10 05:17:54 2007
    From: greg at cosc.canterbury.ac.nz (greg)
    Date: Tue, 10 Jul 2007 21:17:54 +1200
    Subject: object references/memory access
    In-Reply-To: 
    References: <7xfy48f486.fsf@ruckus.brouhaha.com>
    	<1183318690.661279.256900@n2g2000hse.googlegroups.com>
    	<1183407411.397142.304790@e16g2000pri.googlegroups.com>
    	
    	<1183417108.245203.158830@x35g2000prf.googlegroups.com>
    	<4689e535$0$23896$9b622d9e@news.freenet.de>
    	<1183488824.131448.62720@x35g2000prf.googlegroups.com>
    	
    	<5f32o8F3aeadqU1@mid.individual.net>
    	
    Message-ID: <5fh1cmF3ca9o3U1@mid.individual.net>
    
    Dennis Lee Bieber wrote:
    
    > 	If a process is known to be CPU bound, I think it is typical
    > practice to "nice" the process... Lowering its priority by direct
    > action.
    
    Yes, but one usually only bothers with this for long-running
    tasks. It's a nicety, not an absolute requirement.
    
    It seems like this would have been an even more important
    issue in the timesharing environments where unix originated.
    You wouldn't want everyone's text editors suddenly starting
    to take half a second to respond to keystrokes just because
    someone launched "cc -O4 foo.c" without nicing it.
    
    --
    Greg
    
    
    From mshiltonj at gmail.com  Sun Jul  8 14:38:34 2007
    From: mshiltonj at gmail.com (mshiltonj)
    Date: Sun, 08 Jul 2007 18:38:34 -0000
    Subject: In search of python idiom for accessing arbitrary fields at run
    	time
    In-Reply-To: 
    References: <1183918901.388300.220620@o61g2000hsh.googlegroups.com>
    	
    Message-ID: <1183919914.527416.253030@g4g2000hsf.googlegroups.com>
    
    On Jul 8, 2:31 pm, "OKB (not okblacke)"
     wrote:
    > mshiltonj wrote:
    > > In python, I'm doing something like this:
    >
    > >  def three_fields(self, field1, field2, field3):
    > >       for field in (field1, field2, field3):
    > >             value = eval('self.' + field) # this is the one I'm
    > > interested in
    > >             [...]
    >
    > > This seems to do what I expect it to do. I'm wondering if that's the
    > > preferred or standard way to do this in python. I wasn't sure how to
    > > tease the answer to this question out of Google.
    >
    >         I believe you are looking for the getattr function.
    >
    > --
    > --OKB (not okblacke)
    > Brendan Barnwell
    > "Do not follow where the path may lead.  Go, instead, where there is
    > no path, and leave a trail."
    >         --author unknown
    
    
    Doh. I figured it'd by FAQish. :-/  Thanks.
    
    
    
    From gagsl-py2 at yahoo.com.ar  Mon Jul  9 10:32:18 2007
    From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
    Date: Mon, 09 Jul 2007 11:32:18 -0300
    Subject: TypeError: can't multiply sequence to non-int
    References: <4692344A.80700@stilog.com>
    Message-ID: 
    
    En Mon, 09 Jul 2007 10:12:42 -0300, Snezhana   
    escribi?:
    
    ???
    
    Did you intend to post any question?
    The error is rather explicit: you can't say:
    "abc" * 5.2241
    [1,2,3] * "Hello"
    (4,"z") * None
    
    The right operand must be an integer:
    "abc" * 5 (gives "abcabcabcabcabc")
    [1,2,3] * 8 (gives a list with 24 numbers)
    (4,"z") * 2 (gives (4,"z",4,"z"))
    
    -- 
    Gabriel Genellina
    
    
    
    From jstroud at mbi.ucla.edu  Tue Jul 17 03:46:04 2007
    From: jstroud at mbi.ucla.edu (James Stroud)
    Date: Tue, 17 Jul 2007 00:46:04 -0700
    Subject: How to organize control access to source code ?
    In-Reply-To: <1184627782.951682.77870@n2g2000hse.googlegroups.com>
    References: <1184618776.798929.98960@57g2000hsv.googlegroups.com>
    	
    	<1184627782.951682.77870@n2g2000hse.googlegroups.com>
    Message-ID: 
    
    Succelus at gmail.com wrote:
    > On 16 juil, 21:10, Erik Jones  wrote:
    >> On Jul 16, 2007, at 3:46 PM, Succe... at gmail.com wrote:
    >>
    >>> Hello,
    >>> How can we organize development team with code source control policy,
    >>> that limit access to some portion of code ?
    >> The specifics largely depend on the system(s) you're working with
    >> but, basically (sic), you need to read up on filesystem level
    >> permissions.
    >>
    > 
    > Thanks for your response,
    > But I want to know if there is a process or best practices, to give
    > not the access to all of the project. in other words, must every
    > developer work on the entire copy of the project locally ?
    > 
    > Or to work just on his module and manage a process of integration, and
    > if there is any Agile practices for this problem.
    > 
    > 
    
    My Understanding of Corporate Software Practices Amounts To:
    
    Map out the whole project and divide it up, specifying the interface for 
    each "module"--formalized by explicit documentation. Then the individual 
    programmers program to the interfaces of said modules without worrying 
    about their implementation.
    
    PHBs can then use threats of shooting, stabbing, 
    slips-of-paper-strongly-worded-with-copies-to-upper-management, 
    pointing-and-laughing, or sometimes even plain-ole permissions settings 
    to make sure no one else peeks at anyone else's code. Catbert will 
    mediate negotiations with the union.
    
    James
    
    
    From exarkun at divmod.com  Wed Jul 18 05:52:48 2007
    From: exarkun at divmod.com (Jean-Paul Calderone)
    Date: Wed, 18 Jul 2007 05:52:48 -0400
    Subject: Pickled objects over the network
    In-Reply-To: <9c8d48280707171457p4448fdf3of40562bf62a18fc6@mail.gmail.com>
    Message-ID: <20070718095248.4947.1882106103.divmod.quotient.13020@ohm>
    
    On Tue, 17 Jul 2007 14:57:16 -0700, Walker Lindley  wrote:
    >I'm working on a distributed computing program and need to send Python
    >objects over a TCP socket. Specifically, the objects that I'm working with
    >subclass the builtin list type (I don't know whether or not that matters),
    >but also include other data fields. These objects are put into dictionaries
    >along with some other control information and the dictionaries are pickled
    >and sent across the network. I'm using the makefile() function in socket to
    >get a file descriptor for the socket and then calling pickle.dump with the
    >dictionary object and the socket file descriptor. I was originally using
    >pickle protocol 0, but then read about the possibility of buffering problems
    >and realized that protocol 0 was giving me strings about 1500 characters
    >long. After some testing, I settled on protocol 2 which manages to package
    >the data into about 400 characters.
    >
    >In any case, the client side of the program appears to send the data just
    >fine, at least as far as I can tell. On the server side, however, the data
    >takes a very long time to get there and then I get an error in the pickle
    >module:
    >Traceback (most recent call last):
    >  File "server.py", line 176, in 
    >    serv.runServer()
    >  File "server.py", line 99, in runServer
    >    recvPacket = pickle.load(clientFile)
    >  File "/usr/lib/python2.5/pickle.py", line 1370, in load
    >    return Unpickler(file).load()
    >  File "/usr/lib/python2.5/pickle.py", line 858, in load
    >    dispatch[key](self)
    >  File "/usr/lib/python2.5/pickle.py", line 1187, in load_appends
    >    mark = self.marker()
    >  File "/usr/lib/python2.5/pickle.py", line 874, in marker
    >    while stack[k] is not mark: k = k-1
    >IndexError: list index out of range
    >
    >Hopefully I'm doing something obviously wrong, but if anyone can help based
    >on that description or if you need to see the source, please let me know
    >(it's GPL'd). Thank you so much for any help.
    >
    
    The obvious thing you're doing wrong is using pickle over a network. ;)
    
      http://jcalderone.livejournal.com/15864.html
    
    Jean-Paul
    
    
    From kyosohma at gmail.com  Fri Jul 13 08:49:11 2007
    From: kyosohma at gmail.com (kyosohma at gmail.com)
    Date: Fri, 13 Jul 2007 05:49:11 -0700
    Subject: scripts into wxPython
    In-Reply-To: <1184330387.066920.109250@n60g2000hse.googlegroups.com>
    References: <1184330387.066920.109250@n60g2000hse.googlegroups.com>
    Message-ID: <1184330951.435828.277140@g4g2000hsf.googlegroups.com>
    
    On Jul 13, 7:39 am, justme  wrote:
    > Hello
    >
    > I've been happily scripting away for the last few years (Matlab, now
    > Python) and all has been fine. Now I find myself scripting up code for
    > clients, but they all want a nice GUI. I've had a tinker with wxPython
    > and it all seems standard enough but I was wondering if anyone has any
    > comments about how easy it is to shoehorn some fairly complex scripts
    > into a GUI so that non-scripters can use the code. I assume I'll need
    > to recode up all the input outputs?
    >
    > Any thoughts, or should I have started GUI programming right at the
    > outset!
    >
    > Cheers
    
    Yup! To get the inputs, you'll have to redo them in wxPython. But it's
    not a big deal. If you're outputs are print statements than you can
    just redirect stdout to a textctrl in wxPython and you won't need to
    do too much there. Most of the backend complex stuff won't need any
    changing or very little as long as it was written in a refactored /
    stand-alone fashion.
    
    Mike
    
    
    
    From horpner at yahoo.com  Fri Jul 27 08:35:39 2007
    From: horpner at yahoo.com (Neil Cerutti)
    Date: Fri, 27 Jul 2007 12:35:39 GMT
    Subject: <> vs !=
    References: <8a6b8e350707261228x234b7da0g17d43736e45e67ca@mail.gmail.com>
    	
    	<1185537316.344728.265130@r34g2000hsd.googlegroups.com>
    Message-ID: 
    
    On 2007-07-27, jeffmess at gmail.com  wrote:
    > I believe Guido doesn't like '<>' and decided to enforce !=
    > instead. Guess it's his language :).
    
    I like 'not ==', cf 'not in'. Sadly it's a syntax error. However,
    as a language designer, I'm not > Guido.
    
    -- 
    Neil Cerutti
    I don't know what to expect right now, but we as players have to do what we've
    got to do to make sure that the pot is spread equally. --Jim Jackson
    
    
    From josiah.carlson at sbcglobal.net  Sun Jul 15 21:47:47 2007
    From: josiah.carlson at sbcglobal.net (Josiah Carlson)
    Date: Mon, 16 Jul 2007 01:47:47 GMT
    Subject: Marshalling big objects
    In-Reply-To: 
    References: <20070714230421.213010@gmx.net>
    	
    Message-ID: <77Ami.46558$5j1.41313@newssvr21.news.prodigy.net>
    
    Gabriel Genellina wrote:
    > En Sat, 14 Jul 2007 20:04:21 -0300, Orlando D?hring  escribi?:
    > 
    >> I want to marshal objects:
    >>
    >> - http://docs.python.org/lib/module-marshal.html
    >> where I have problems with a bigger objects, e.g.
    > 
    > Any specific reason you use this module? As a general purpose 
    > serializer, use pickle (or cPickle) instead.
    
    For a really good reason why to use cPickle/pickle for large object 
    serialization is because the marshal module uses a very conservative 
    memory resize, so tends to be slow for large objects.
    
      - Josiah
    
    
    
    From vedrandekovic at v-programs.com  Tue Jul 31 06:01:08 2007
    From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com)
    Date: Tue, 31 Jul 2007 03:01:08 -0700
    Subject: simple string backspace question
    In-Reply-To: <1185875052.153091.23300@19g2000hsx.googlegroups.com>
    References: <1185875052.153091.23300@19g2000hsx.googlegroups.com>
    Message-ID: <1185876068.755101.316320@b79g2000hse.googlegroups.com>
    
    On 31 srp, 11:44, vedrandeko... at v-programs.com wrote:
    > Hello,
    >
    > I have one simple string, backspace character question.Here is my
    > example:
    >
    > >>> text="Hello\bworld"
    > >>> print text
    >
    > "HelloBSworld"
    >
    > Should this character "\b" (backspace) in this text return this:
    > "Helloworld"?
    >
    > Regards,
    > Vedran
    
    Hi,
    
    If you mean on operating system then unfortunately Windows XP.
    
    Regards,
    Vedran
    
    
    
    From Green.Horn.000 at gmail.com  Mon Jul 30 12:46:27 2007
    From: Green.Horn.000 at gmail.com (GreenH)
    Date: Mon, 30 Jul 2007 16:46:27 -0000
    Subject: pythonic parsing of URL
    In-Reply-To: 
    References: <1185592232.110391.69630@i13g2000prf.googlegroups.com>
    	
    Message-ID: <1185813987.649497.262810@j4g2000prf.googlegroups.com>
    
    On Jul 27, 10:04 pm, Steven D'Aprano
     wrote:
    > On Sat, 28 Jul 2007 03:10:32 +0000, GreenH wrote:
    > > I get some string as below from a library method (qt3
    > > QDropEvent.data()) I use.
    > > file:///C:/Documents%20and%20Settings/Username/My%20Documents/45-61-Abc%20fold-%20den.vru
    >
    > > I need file path on my system, for the above example:
    > > C:/Documents and Settings/Username/My Documents/45-61-Abc fold-
    > > den.vru
    >
    > > I am doing the below, it doesn't look pythonic,
    > > can someone suggest any elegant solution, which is not too cryptic to
    > > understand? yep, I do care about readability of the code to average
    > > python user :)
    >
    > Try this:
    >
    > import urlparse, sys
    > fileURLname = ("file:///C:/Documents%20and%20Settings/Username/"
    >     "My%20Documents/45-61-Abc%20fold-%20den.vru")
    > pathname = urlparse.urlparse(fileURLname)[2]
    > if sys.platform == "win32":
    >     import nturl2path
    >     clean = nturl2path.url2pathname(pathname)
    > else:
    >     import urllib
    >     clean = urllib.unquote(pathname)
    > print clean
    >
    > > --------------------
    > >  tmpTuple = urlparse.urlparse(fileURLname)
    >
    > > tmpString = tmpTuple[2].strip('/\\')
    >
    > > fileName = urllib.unquote(tmpString)
    >
    > > #For some reason the string contained in 'fileName' has some
    > > unprintable trailing characters, Any ideas on that?
    >
    > It works for me: No trailing characters at all, printable or otherwise.
    >
    > >>> len(fileName.split('.vru', 1)[1])
    >
    > 0
    >
    > --
    > Steven.
    
    Hi!
    Thanks for the reply. The unprintable character was null byte.
    
    -Greene.
    
    
    
    From paddy3118 at googlemail.com  Sat Jul 28 04:16:36 2007
    From: paddy3118 at googlemail.com (Paddy)
    Date: Sat, 28 Jul 2007 08:16:36 -0000
    Subject: removing items from a dictionary ?
    In-Reply-To: 
    References: 
    	<46a8f836$0$28175$9a622dc7@news.kpnplanet.nl>
    	
    Message-ID: <1185610596.202931.33130@19g2000hsx.googlegroups.com>
    
    On Jul 28, 1:43 am, Steven D'Aprano
     wrote:
    > On Thu, 26 Jul 2007 21:38:31 +0200, martyw wrote:
    > > Remoing elements from a dict is done with del, try this;
    > >  >>> d = {'a' : 1,'b' : 2}
    > >  >>> del d['a']
    > >  >>> print d
    > > {'b': 2}
    >
    > > maybe you can post a working snippet to demonstrate your problem
    >
    > Wow. This wins my award for the least helpful, while still being
    > technically correct, reply ever. Did you even read the Original Poster's
    > post? He already knows that you delete items from a dictionary with del,
    > and he posted code and the traceback he gets when he runs it.
    >
    > --
    > Steven.
    
    ... But lets also applaud the fact that MartyW wants to help.
    
    - Paddy.
    
    
    
    From gh at ghaering.de  Fri Jul  6 03:12:08 2007
    From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=)
    Date: Fri, 06 Jul 2007 09:12:08 +0200
    Subject: SMTP server w/o using Twisted framework
    In-Reply-To: <1183664445.020890.226520@c77g2000hse.googlegroups.com>
    References: <1183661809.613856.312100@57g2000hsv.googlegroups.com>
    	
    	<1183664445.020890.226520@c77g2000hse.googlegroups.com>
    Message-ID: <5f68a6F3adj19U1@mid.uni-berlin.de>
    
    _spitFIRE wrote:
    > [looking up DNS MX records]
    > Thanks for the pointer. However, as I said currently, I can't use
    > anything other than the standard libraries.
    
    Sure you can. You just need to get rid of the "only standard library" 
    requirement rule.
    
    That works best by showing the alternatives to whoever set that requirement:
    
    - use pyDNS
    - use an existing (probably non-Python) SMTP daemon
    - reimplement some parts of pyDNS yourself and develop a basic (crappy) 
    SMTP daemon yourself
    
    For doing the latter, you should budget at least one week.
    
    FWIW another reason why SMTP servers should retry on temporary failure 
    is that increasing use of Greylisting (*), which was precisely designed 
    to filter out mail from "crappy" servers, like botnets, and - well - 
    cheap custom written ones ;-)
    
    -- Gerhard
    
    
    (*) http://en.wikipedia.org/wiki/Greylisting - I use it myself
    
    
    From stefan.behnel-n05pAM at web.de  Tue Jul 24 14:46:19 2007
    From: stefan.behnel-n05pAM at web.de (Stefan Behnel)
    Date: Tue, 24 Jul 2007 20:46:19 +0200
    Subject: Any python module for Traversing HTML files
    In-Reply-To: <1185297135.542235.55290@r34g2000hsd.googlegroups.com>
    References: <1185297135.542235.55290@r34g2000hsd.googlegroups.com>
    Message-ID: <46A648FB.8040901@web.de>
    
    johnny wrote:
    > Any python module for navigating and selecting, parsing HTML files?
    
    Since you didn't name any specific requirements, consider taking the best one.
    "lxml.html" provides loads of goodies like Python iterators, XPath or CSS
    selection for navigation, or a clean() function for removing junk from HTML pages.
    
    The down-side is: there's no official release yet, you currently have to build
    it from SVN branch sources. But there will soon be an official alpha release
    of lxml 2.0 which will include it.
    
    http://codespeak.net/lxml/
    
    http://codespeak.net/svn/lxml/branch/html/
    
    Stefan
    
    
    From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Tue Jul 31 08:53:18 2007
    From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
    Date: Tue, 31 Jul 2007 14:53:18 +0200
    Subject: Why no maintained wrapper to Win32?
    In-Reply-To: 
    References: 
    	<46ab694e$0$17577$9b622d9e@news.freenet.de>
    	<59kna3p8r0cu2gk6hs5lbig8cjj8klatju@4ax.com>
    	<1185762820.496821.298530@19g2000hsx.googlegroups.com>
    	
    	<1185770944.301464.85060@b79g2000hse.googlegroups.com>
    	
    Message-ID: <46af30b8$0$24127$426a74cc@news.free.fr>
    
    Gilles Ganault a ?crit :
    > On Sun, 29 Jul 2007 21:49:04 -0700, sturlamolden
    >  wrote:
    >> Why inflict suffering on yourself with MFC when you can use wxPython
    >> or PyGTK?
    > 
    > Because I'd like to avoid having to pack several MB + having to
    > install the toolkit. Considering the size of the typical Python
    > script, it seemed overkill.
    > 
    >> Sure, you could use ctypes to make calls into user32.dll, gdi32.dll
    >> and kernel32.dll. Then you can program Python GUIs using the plain
    >> Win32 API, avoiding PyWin32's MFC or wxPython. But who would do such a
    >> thing?
    > 
    > So the PyWin32 interface doesn't make it easier to program Win32 GUI
    > apps?
    
    Did you ever tried writing a Win32 GUI app in C ?-)
    
    But you should re-read the above more carefully. What I do understand 
    from it is that PyWin32 adds support for the MFC toolkit (nb: didn't 
    check myself since I'm not concerned...).
    
    > It's just C that looks like Python?
    > 
    > Guess I have the answer as to no one seems to write GUI apps for
    > Windows natively :-)
    
    Fact is that either the app is a small, casual tool, and then Tkinter is 
    quite enough, or it's a real, fullblown app and then better to use a 
    decent (and, if possible, crossplatform) toolkit - like, you know, 
    wxWidgets !-)
    
    
    
    From S.Mientki-nospam at mailbox.kun.nl  Tue Jul 17 05:14:50 2007
    From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki)
    Date: Tue, 17 Jul 2007 11:14:50 +0200
    Subject: how to find available classes in a file ?
    In-Reply-To: 
    References: <2e302$469bf38f$d443bb3a$30036@news.speedlinq.nl>	<1184627599.597658.267380@g4g2000hsf.googlegroups.com>
    	
    Message-ID: 
    
    Gabriel Genellina wrote:
    > En Mon, 16 Jul 2007 20:13:19 -0300, Alex Popescu 
    >  escribi?:
    > 
    >> On Jul 17, 1:44 am, Stef Mientki 
    >> wrote:
    >>> I want to have a (dynamically) list of all classes defined in a py-file.
    >>> Is there a way of getting this list, without manually parsing the file ?
    >>
    >> I have written something that does something like this, but I am not
    >> sure it is the pythonic way.
    >> Bascially I am loading the module and then using dir() on the module
    >> object I am looking for
    >> attribute of the type classobj (for old style classes) and type type
    >> (for new style classes).
    > 
    > There is also the pyclbr standard module 
    >  that does not load the 
    > module (just reparses enough of it to get the info needed). So a broken 
    > import, or any other initialization error, won't hurt.
    
    thanks Gabriel, Alex and Ben.
    This is indeed a good working solution,
    because pyclbr also specifies in which module the class is definied.
    In the other suggestions, you also get the class definitions of imported modules.
    
    cheers,
    Stef Mientki
    
    
    From nytrokiss at gmail.com  Wed Jul 18 11:37:49 2007
    From: nytrokiss at gmail.com (James Matthews)
    Date: Wed, 18 Jul 2007 08:37:49 -0700
    Subject: wxPython and threads
    In-Reply-To: 
    References: <1184726489.112138.96350@z28g2000prd.googlegroups.com>
    	
    Message-ID: <8a6b8e350707180837v555eb01ao7e16711f7d521bbe@mail.gmail.com>
    
    Sounds like a race condition. is List Ctrl waiting for the gui to return?
    Maybe make the processing more then one thread!
    
    On 7/17/07, Stef Mientki  wrote:
    >
    > Benjamin wrote:
    > > I'm writing a search engine in Python with wxPython as the GUI. I have
    > > the actual searching preformed on a different thread from Gui thread.
    > > It sends it's results through a Queue to the results ListCtrl which
    > > adds a new item. This works fine or small searches, but when the
    > > results number in the hundreds, the GUI is frozen for the duration of
    > > the search. I suspect that so many search results are coming in that
    > > the GUI thread is too busy updating lists to respond to events. I've
    > > tried buffer the results so there's 20 results before they're sent to
    > > the GUI thread and buffer them so the results are sent every .1
    > > seconds. Nothing helps. Any advice would be great.
    > >
    > maybe you'ld better ask this question in the wxPython discussion group:
    >
    > wxPython-users at lists.wxwidgets.org
    >
    > cheers,
    > Stef
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >
    
    
    
    -- 
    http://www.goldwatches.com/watches.asp?Brand=14
    http://www.jewelerslounge.com
    -------------- next part --------------
    An HTML attachment was scrubbed...
    URL: 
    
    From evan at yelp.com  Sun Jul  1 12:51:20 2007
    From: evan at yelp.com (Evan Klitzke)
    Date: Sun, 1 Jul 2007 09:51:20 -0700
    Subject: Reversing a string
    In-Reply-To: 
    References: 
    	
    	<1182997438.541012.54100@o61g2000hsh.googlegroups.com>
    	
    	
    	
    Message-ID: 
    
    On 1 Jul 2007 11:09:40 GMT, Martin Durkin  wrote:
    > Duncan Booth  wrote in
    > news:Xns996067AFF71DDduncanbooth at 127.0.0.1:
    >
    > > Martin Durkin  wrote:
    > >
    > >>>>>> def rev(x):
    > >>>             mylist = []
    > >>>             for char in x:
    > >>>                  mylist.append(char)
    > >>>             mylist.reverse()
    > >>>             for letter in mylist:
    > >>>                  print letter
    > >>>
    > >>> However, compare the incredible difference in clarity and elegance
    > >>> between that and:
    > >>>
    > >>>> >>> print "\n".join("spam"[::-1])
    > >>>
    > >>
    > >> OK, maybe I'm missing the point here as I'm new to Python. The first
    > >> one seems clearer to me. What am I missing?
    > >>
    > > I think all you are missing is familarity with Python, but I too don't
    > > like one-liners simply for their own sake.
    > >
    >
    > I guess that's it. The first one reads more like a textbook example which
    > is about where I am at. Is there any speed benefit from the one liner?
    
    The one line is quite a bit faster:
    
    evan at thinkpad ~ $ python -m timeit 's = "onomatopoeia"; s = s.join(s[::-1])'
    100000 loops, best of 3: 6.24 usec per loop
    
    evan at thinkpad ~ $ python -m timeit '
    > def rev(x):
    >     mylist = []
    >     for char in x:
    >         mylist.append(char)
    >     mylist.reverse()
    >     return "".join(mylist)
    >
    > s = "onomatopoeia"
    > s = rev(s)'
    100000 loops, best of 3: 9.73 usec per loop
    
    -- 
    Evan Klitzke 
    
    
    From zyzhu2000 at gmail.com  Fri Jul 27 17:37:01 2007
    From: zyzhu2000 at gmail.com (beginner)
    Date: Fri, 27 Jul 2007 21:37:01 -0000
    Subject: Tkinter program with a usable interpreter console
    Message-ID: <1185572221.020114.192650@z24g2000prh.googlegroups.com>
    
    Hi everyone,
    
    I have a question about Tkinter programs. What I want is a GUI window
    along with an interpreter window, so that I can do things by clicking
    on the GUI or typing commands in the interpreter console. For example,
    I wish I can type in the console:
    
    >>> modify_my_key_data()
    >>> update_gui()
    
    and my gui is modified for me.
    
    The problem is that the Tkinter program ends with a .mainloop() call
    and it is not going to give back control to the command prompt. I feel
    it is almost like I need to implement the python shell myself. Is
    there any better way of doing this?
    
    Thanks,
    beginner
    
    
    
    From jeffober at gmail.com  Wed Jul 25 16:10:52 2007
    From: jeffober at gmail.com (Jeff)
    Date: Wed, 25 Jul 2007 20:10:52 -0000
    Subject: Why PHP is so much more popular for web-development
    In-Reply-To: <1185392048.737400.290050@j4g2000prf.googlegroups.com>
    References: <1185385374.866372.198520@x35g2000prf.googlegroups.com>
    	
    	<1185392048.737400.290050@j4g2000prf.googlegroups.com>
    Message-ID: <1185394252.064429.258950@d55g2000hsg.googlegroups.com>
    
    I'm an ex-PHP programmer (well, I still have to use some PHP at work,
    but I don't tell anyone that at parties) who now uses Python or Lisp
    wherever possible for web development.  I can tell you exactly why PHP
    is so popular: it acts as an extension of HTML and is syntactically
    similar to Perl.
    
    PHP mixes with HTML and removes the separation of model and view.  It
    has its roots in strictly procedural code (and its OO colors were
    obviously painted on later), which is simple for non-programmers or
    beginning programmers to understand.  When considered from the
    standpoint of a template language, it's a wonderful language.  When
    considered as a real programming environment, its limitations show.
    
    PHP began as a series of Perl scripts.  If you have ever looked at a
    huge PHP project, it looks just as unreadable as a huge Perl project.
    But there is a large number of programmers who began writing Perl-
    based CGI for the web, and PHP was a very natural next step for them.
    This is also a big reason why Ruby is popular among the same crowd
    (...I say as I duck the inevitable flame war I've just started).  Ruby
    takes a lot of concepts from Perl and tries to make them work in an OO
    framework (the ~ operator and the built in regex type, for instance).
    
    I started with PHP for both of those reasons.  Perl was becoming too
    much of a chore and PHP offered a solution without learning a new
    templating language: a way to embed perl code in the page itself.
    
    Of course, now I am in recovery and am proceeding well with my 12
    steps, thanks for asking.
    
    
    
    From steve at holdenweb.com  Sat Jul  7 21:30:54 2007
    From: steve at holdenweb.com (Steve Holden)
    Date: Sat, 07 Jul 2007 21:30:54 -0400
    Subject: Restarting a Python Application
    In-Reply-To: 
    References: <1183498045.092504.229250@m36g2000hse.googlegroups.com>	<94ccbe710707071511o3beee718wc12f15082b3c6e18@mail.gmail.com>
    	
    Message-ID: 
    
    Peter Decker wrote:
    > On 7/7/07, Kelvie Wong  wrote:
    >> Ugh.. this would be a repost for the OP, but I forgot to hit "reply to
    >> all" again.
    > 
    > 
    > Imagine if you wrote applications where the default behavior did not
    > do what was needed 99% of the time: how long do you think you'd be in
    > business?
    > 
    > The default behavior of replying to the original sender instead of the
    > list makes no sense. I've read the purist arguments against replying
    > to the list, but I subscribed to a *list*, not an individual sender.
    > 
    > I know that this post is pointless, since the people who run this list
    > seem to care more about abstract and misdirected notions of purity
    > than making things as useful and intelligent as possible, but after
    > seeing dozens of "please keep your reply on list" responses recently,
    > I had to vent.
    > 
    
    Well, I hope you 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 horpner at yahoo.com  Thu Jul  5 16:05:08 2007
    From: horpner at yahoo.com (Neil Cerutti)
    Date: Thu, 05 Jul 2007 20:05:08 GMT
    Subject: Re-raising exceptions with modified message
    References: 
    	
    	
    	
    	
    	
    	
    Message-ID: 
    
    On 2007-07-05, Christoph Zwerschke  wrote:
    > Neil Cerutti wrote:
    >> You may need the traceback module to get at the error message, if
    >> trying to read e.message can fail.
    >> 
    >> Something like this mess here: ;)
    >> 
    >>    ...
    >>    except Exception, e:
    >>      etype, evalue, etb = sys.exc_info()
    >>      ex = traceback.format_exception_only(etype, evalue)
    >>      message = ex[0].partition(':')[2].strip()
    >>      raise etype, message+". Sorry!", etb
    >> 
    >> Note that the above will break for SyntaxError (who's message
    >> contains more than one line) and any kind of exception that
    >> doesn't inherit from Exception.
    >
    > That's actually similar to what I was using in Kid already.
    >
    > The problem is that there are some Exceptions which cannot be
    > instantiated with a single string argument, such as
    > UnicodeDeocdeError. Please try the above with "unicode('\xe4')"
    > instead of the dots. Instead of re-raising the
    > UnicodeDecodeError, you will get a TypeError because of this
    > problem.
    
    Crud. After my third answer, I'll finally understand the
    question. Unfortunately, I only had two in me.
    
    -- 
    Neil Cerutti
    Low Self-Esteem Support Group will meet Thursday at 7 to 8:30 p.m. Please use
    the back door. --Church Bulletin Blooper
    
    
    From michele.simionato at gmail.com  Mon Jul 23 04:38:49 2007
    From: michele.simionato at gmail.com (Michele Simionato)
    Date: Mon, 23 Jul 2007 08:38:49 -0000
    Subject: decorators tutorials
    In-Reply-To: <1185178383.499234.299850@z24g2000prh.googlegroups.com>
    References: <1185178383.499234.299850@z24g2000prh.googlegroups.com>
    Message-ID: <1185179929.288117.17340@k79g2000hse.googlegroups.com>
    
    On Jul 23, 10:13 am, james_027  wrote:
    > Hi,
    >
    > I am learning python by learning django, and I stumble upon decorator
    > which is very cool, any beginners resources for python decorators,
    > although I can google it, I just want to get a good tutorial for this
    > topic.
    >
    > Thanks
    > james
    
    Look at the decorator page in the Python Wiki. There is also a paper
    by
    David Mertz on IBM DeveloperWorks. Finally, you may have a look at my
    own work http://www.phyast.pitt.edu/~micheles/python/documentation.html
    
           Michele Simionato
    
    
    
    From len-l at telus.net  Tue Jul  3 01:39:15 2007
    From: len-l at telus.net (Lenard Lindstrom)
    Date: Tue, 03 Jul 2007 05:39:15 GMT
    Subject: Python's "only one way to do it" philosophy isn't good?
    In-Reply-To: 
    References: 
    	 <7xejjzmk7u.fsf@ruckus.brouhaha.com>
    	 <7xy7i7xjl5.fsf@ruckus.brouhaha.com>
    	
    	
    	
    	
    	
    	
    	 
    	 
    	 <9uRhi.17027$xk5.14289@edtnps82>
    	 
    	
    Message-ID: <7ilii.25364$xk5.22153@edtnps82>
    
    Douglas Alan wrote:
    > Lenard Lindstrom  writes:
    > 
    >> But some things will make it into ISO Python.
    > 
    > Is there a movement afoot of which I'm unaware to make an ISO standard
    > for Python?
    > 
    
    Not that I know of. But it would seem any language that lasts long 
    enough will become ISO standard. I just meant that even though Python 
    has no formal standard there are documented promises that will not be 
    broken lightly by any implementation.
    
    ---
    Lenard Lindstrom
    
    
    
    From kyosohma at gmail.com  Thu Jul 19 09:04:26 2007
    From: kyosohma at gmail.com (kyosohma at gmail.com)
    Date: Thu, 19 Jul 2007 06:04:26 -0700
    Subject: wxPython, searching, and threads
    In-Reply-To: <1184776718.313539.92360@z28g2000prd.googlegroups.com>
    References: <1184776718.313539.92360@z28g2000prd.googlegroups.com>
    Message-ID: <1184850266.008641.287640@n2g2000hse.googlegroups.com>
    
    On Jul 18, 11:38 am, Benjamin  wrote:
    > Hello! I am writing a search engine with wxPython as the GUI. As the
    > search thread returns items, it adds them to a Queue which is picked
    > up by the main GUI thread calling itself recursively with
    > wx.CallAfter. These are then added to a ListCtrl. This works fine for
    > small searches, but with larger and longer searchs the GUI is clogged
    > and won't respond. I suspect (I may be wrong) that there are so many
    > results being sent to the ListCtrl that the event loop doesn't have
    > time to respond to events. I've tried buffering the results before
    > sending them to the GIU, but that doesn't help at all. Please advise.
    
    The standard wxPython user's group reply to a question like this is,
    check out http://wiki.wxpython.org/LongRunningTasks. I've used a
    variation of what's on this page to create a fairly complex installer
    than keeps a textctrl updated with its progress. Since the installer
    runs for almost an hour, I think this method works great.
    
    Admittedly, you work with threads, which is intimidating to some
    degree and if you use WMI, then you'll need to use some special
    commands to make it work in a thread.
    
    The wxPython mailing list is here: http://www.wxpython.org/maillist.php
    
    Hope that helps.
    
    Mike
    
    
    
    From bj_666 at gmx.net  Tue Jul 31 17:16:54 2007
    From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch)
    Date: 31 Jul 2007 21:16:54 GMT
    Subject: Extending Python by Adding Keywords & Data types
    References: <1185913739.879602.212950@w3g2000hsg.googlegroups.com>
    Message-ID: <5h9n66F3j641tU5@mid.uni-berlin.de>
    
    On Tue, 31 Jul 2007 20:28:59 +0000, Maximus Decimus wrote:
    
    > II want to add some more KEYWORDS and DATATYPES into the python script
    > apart from the existing ones.
    
    New data types are easy: Just implement the classes.
    
    Why do you need new keywords?  Can't the problem at hand be expressed in
    functions and classes/methods?
    
    Ciao,
    	Marc 'BlackJack' Rintsch
    
    
    From robert_rawlins at hotmail.com  Sun Jul 15 10:39:24 2007
    From: robert_rawlins at hotmail.com (Robert Rawlins)
    Date: Sun, 15 Jul 2007 14:39:24 +0000
    Subject: Dict Help
    Message-ID: 
    
    Hello Guys,
     
    I'm looking for some help expanding on a dictionary I've got and storing multiple values per key and the best way to do it. I'm guessing that I need to store a list inside the value of the dictionary, but I'm not quite sure how that can be achieved, and also how to check for values in that list.
     
    Here is a brief example of what I want to be able to build:
     
    Key                                          Value
    00:0F:DE:A8:AB:6F                     6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg,01DBB592-F7EB-B000-7F250FD8A2CE158F.gif,533EAE0F-B211-B2D8-4C2DB662CCECFBD7.3gp
    00:17:B0:A0:E7:09                     6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg,01DBB592-F7EB-B000-7F250FD8A2CE158F.gif
    00:1B:98:16:21:E4                     6C66F14B-FED6-D1A4-62EAAD881E9133F0.jpg
     
    Now I really need to have two functions, one of which appends a value to the list for a specified key, so I have the key and the new value as strings, I then want to locate that key and append the list with the new value.
     
    The second function I need, is to check for the existence of a value in the list of a particular key, again I have the key and the value and I want to do something like:
     
    if value in list of values for key:
           do something here...
     
    The final function that would be helpful to me would to be able to remove a value from the list for a specific key.
     
    I'm not sure if a list as the value in a dict is possible, or if its the best way to achieve this, It just made logic sense to me so thought I'd come and get your thoughts on this. If anyone has any better suggestions about how to attach mutiple values to a single key, I would love to hear it. Other than that I just need some code examples of those append/existence functions.
     
    Can anyone offer some help? Thanks guys,
     
    Rob
    _________________________________________________________________
    100?s of Music vouchers to be won with MSN Music
    https://www.musicmashup.co.uk/index.html
    -------------- next part --------------
    An HTML attachment was scrubbed...
    URL: 
    
    From gagsl-py2 at yahoo.com.ar  Wed Jul 25 21:05:15 2007
    From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
    Date: Wed, 25 Jul 2007 22:05:15 -0300
    Subject: How do I 'stat' online files?
    References: 
    	<1185284836.3370.11.camel@dot.uniqsys.com>
    	
    	<1185387079.4432.9.camel@dot.uniqsys.com>
    Message-ID: 
    
    En Wed, 25 Jul 2007 15:11:19 -0300, Carsten Haese   
    escribi?:
    
    > On Tue, 2007-07-24 at 22:23 -0300, Gabriel Genellina wrote:
    >> En Tue, 24 Jul 2007 10:47:16 -0300, Carsten Haese 
    >> escribi?:
    >>
    >> > On Tue, 2007-07-24 at 09:07 -0400, DB Daniel Brown wrote:
    >> >> I am working on a program that needs to stat files (gif, swf, xml,
    >> >> dirs, etc) from the web. I know how to stat a local file?
    >> >
    >> > That's because urlopen returns a file-like object, not a file. The  
    >> best
    >> > you can hope for is to inspect the headers that the web server  
    >> returns:
    >> >
    >> >>>> f = urllib.urlopen("http://www.python.org")
    >>
    >> This generates an HTTP GET request - transfering the contents too,
    >> innecesarily.
    >
    > Yes, but how much of that content will actually be transferred if I
    > don't call f.read?
    
    Transferred? The server perhaps has sent all of it, depending on its  
    configuration and available bandwidth. The first packets will be in your  
    TCP receiving buffers even if you never call f.read(). So be nice to the  
    origin server, the whole Internet, and our planet, and don't waste  
    bandwidth and energy in requesting things that you're going to throw away  
    anyway.
    
    > I doubt that my computer just downloaded 4 MB of stuff in 0.3 seconds.
    
    Probably not, but I'd use netstat or ntop to find out how much has  
    actually been downloaded.
    
    -- 
    Gabriel Genellina
    
    
    
    From http  Thu Jul 26 16:26:33 2007
    From: http (Paul Rubin)
    Date: 26 Jul 2007 13:26:33 -0700
    Subject: Why PHP is so much more popular for web-development
    References: <1185385374.866372.198520@x35g2000prf.googlegroups.com>
    	
    	<1185392048.737400.290050@j4g2000prf.googlegroups.com>
    	<13ahh6kosqqeba1@corp.supernews.com>
    	<7xlkd3m1si.fsf@ruckus.brouhaha.com>
    	
    Message-ID: <7xhcnq7vye.fsf@ruckus.brouhaha.com>
    
    Steve Holden  writes:
    > > That sounds trivial to ameliorate (at least somewhat) by putting your
    > > uploads in a directory whose name is known only to you (let's say it's
    > > a random 20-letter string).  The parent directory can be protected to
    > > not allow reading the subdirectory names.
    > 
    > But you have to admit that's "security by obscurity".
    
    I'm not completely sure it's security by obscurity if the system setup
    is careful.  The pathname is like a password and maybe it can be
    proteced from exposure to the same degree that other file system
    contents are protected.  This would not pass review for protecting
    launch codes, but neither most things done on even serious commercial
    web sites.
    
    
    From gagsl-py2 at yahoo.com.ar  Mon Jul  9 19:27:06 2007
    From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
    Date: Mon, 09 Jul 2007 20:27:06 -0300
    Subject: execute script in certain directory
    References: 
    	<1184001247.332648.100520@x35g2000prf.googlegroups.com>
    Message-ID: 
    
    En Mon, 09 Jul 2007 14:14:07 -0300, vasudevram   
    escribi?:
    
    > On Jul 9, 8:31 pm, brad  wrote:
    >> When I use idle or a shell to execute a python script, the script
    >> executes in the directory it is currently in (in this case, my desktop).
    >> However, when using GNOME and right clicking the py script and selecting
    >> 'open with python', the execution occurs in my home directory, not my
    >> desktop.
    >
    > Add these lines to the top of your script:
    >
    > import os
    > os.chdir(rundir)
    
    I usually don't do that, because it invalidates any filename arguments the  
    program may have.
    Instead, I use an explicit directory when I want it. For example, to open  
    a .dat file located in the same directory as the module using it:
    
    # top of the module
    dat_path = os.path.dirname(os.path.abspath(__file__))
    
    # when opening the file
    f = open(os.path.join(dat_path, "filename.dat"))
    
    -- 
    Gabriel Genellina
    
    
    
    From zentraders at gmail.com  Fri Jul 27 12:31:25 2007
    From: zentraders at gmail.com (Zentrader)
    Date: Fri, 27 Jul 2007 09:31:25 -0700
    Subject: a simple string question
    In-Reply-To: <1185549793.114644.62170@k79g2000hse.googlegroups.com>
    References: <1185549793.114644.62170@k79g2000hse.googlegroups.com>
    Message-ID: <1185553885.236602.241400@m37g2000prh.googlegroups.com>
    
    On Jul 27, 8:23 am, vedrandeko... at v-programs.com wrote:
    > Hello,
    >
    > I have one question about string.I am trying to make an function to
    > analyze line  of some text, this is my example: "HELLO;HELLO2:WORLD:",
    >  if that function in this text find ";" and ":" ( in this example will
    > find both)
    >
    > e.g  that function must return this:
    >
    > "HELLO;\nHELLO2:\n\t\t\t\t\t\t\tWORLD:"
    >
    > Regards,
    > Vedran
    
    You can use split twice
    print text.split( ":" )
    and then split the returned list items on ";".
    You could also use text.find( ":" ), but that would be pretty much the
    same thing only harder.  Also, you can step through the string one
    character at a time and compare each character.  Finally, you can use
    an re, (regular expression), but if you are still learning how to
    parse strings, I don't think you want to get into re's.
    
    
    
    From attn.steven.kuo at gmail.com  Mon Jul 16 10:15:40 2007
    From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com)
    Date: Mon, 16 Jul 2007 14:15:40 -0000
    Subject: questions about functions inside a function
    In-Reply-To: 
    References: 
    Message-ID: <1184595340.499507.66720@o11g2000prd.googlegroups.com>
    
    On Jul 16, 4:49 am, "fdu.xia... at gmail.com" 
    wrote:
    
    (snipped)
    
    >
    > What I want is, the value of i should be bounded to the anonymous function.
    > And the output should like this:
    >
    > for f in a:
    >      print f()
    > 0
    > 1
    > 4
    > 9
    >
    > How to achieve this?
    >
    > Thanks a lot!
    
    
    
    The functools module, in Python 2.5 allows:
    
    >>> import functools
    >>> square = lambda i: i ** 2
    >>> anon = [functools.partial(square, i) for i in range(4)]
    >>> for f in anon:
    ...     print f()
    ...
    
    --
    Hope this helps,
    Steven
    
    
    
    From shafik23 at gmail.com  Wed Jul 11 15:18:53 2007
    From: shafik23 at gmail.com (Shafik)
    Date: Wed, 11 Jul 2007 19:18:53 -0000
    Subject: Tuple vs List: Whats the difference?
    In-Reply-To: 
    References: <1184177195.569916.184770@22g2000hsm.googlegroups.com>
    	
    Message-ID: <1184181533.555101.317410@n2g2000hse.googlegroups.com>
    
    On Jul 11, 12:05 pm, Alexander Schmolck  wrote:
    > Shafik  writes:
    > > Hello folks,
    >
    > > I am an experienced programmer, but very new to python (2 days). I
    > > wanted to ask: what exactly is the difference between a tuple and a
    > > list? I'm sure there are some, but I can't seem to find a situation
    > > where I can use one but not the other.
    >
    > Try mutating the tuple or using the list as a hashkey.
    >
    > 'as
    
    Cool thanks guys.
    
    --Shafik
    
    
    
    
    From lew at lewscanon.nospam  Sat Jul  7 18:12:40 2007
    From: lew at lewscanon.nospam (Lew)
    Date: Sat, 07 Jul 2007 18:12:40 -0400
    Subject: The Modernization of Emacs: terminology buffer and keybinding
    In-Reply-To: <1183841277.333384.188950@g4g2000hsf.googlegroups.com>
    References: <1182093200.598418.218620@e9g2000prf.googlegroups.com>
    	<1182272495.990807.99110@a26g2000pre.googlegroups.com>
    	<87tzt3ihev.fsf@kobe.laptop> 
    	<1182370216.961241.6960@n60g2000hse.googlegroups.com>
    	<85zm2ufjpb.fsf@lola.goethe.zz>
    	<1182372592.803332.288260@u2g2000hsc.googlegroups.com>
    	<1182373919.262388.100740@c77g2000hse.googlegroups.com>
    	<85r6o6fhkb.fsf@lola.goethe.zz>
    	<1182375045.626510.188170@m36g2000hse.googlegroups.com>
    	<85myyufgwj.fsf@lola.goethe.zz>
    	<1182375528.985142.293900@q69g2000hsb.googlegroups.com>
    	
    	<1182545268.055596.228700@i38g2000prf.googlegroups.com>
    	
    	<1183841277.333384.188950@g4g2000hsf.googlegroups.com>
    Message-ID: 
    
    Twisted wrote:
    Edward Dodge wrote:
    >> So -- what magical computer app illuminates the entire room and shows
    >> you how to use everything at the flip of a switch?  This brilliant
    >> discovery would put Sam's, O'Reilly, the for-Dummies series, and
    >> virtually every other computer book publisher out of business in weeks.
    >> Naturally, this would include the publishers of books on "easy-to-use"
    >> Microsoft products.
    > 
    > I don't know, but it sure as hell isn't emacs.
    
    The reason you don't know, and Edward Dodge's point, is that there is no such 
    app, whether emacs or not.
    
    -- 
    Lew
    
    
    From splifingate at gmail.com  Sun Jul 29 15:48:06 2007
    From: splifingate at gmail.com (ah)
    Date: Sun, 29 Jul 2007 15:48:06 -0400
    Subject: What does this thread have to do with classical music,
    In-Reply-To: <250720071834457296%erfc@caballista.org>
    References: <7nnh7350b5h25ghocra72b23mmsnnkj8bh@4ax.com>
    	<040720071254144566%erfc@caballista.org>
    	<468cf97b$0$97266$892e7fe2@authen.yellow.readfreenews.net>
    	<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>
    Message-ID: <46aceaa5$0$13281$8f2e0ebb@news.shared-secrets.com>
    
    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.
    
    
    From marduk at nbk.hopto.org  Sun Jul 22 17:28:30 2007
    From: marduk at nbk.hopto.org (marduk)
    Date: Sun, 22 Jul 2007 16:28:30 -0500
    Subject: space / nonspace
    In-Reply-To: 
    References: 
    Message-ID: <1185139710.3067.6.camel@blackwidow.nbk>
    
    On Sun, 2007-07-22 at 22:33 +0200, Peter Kleiweg wrote:
    > >>> import re
    >     >>> s = u'a b\u00A0c d'
    >     >>> s.split()
    >     [u'a', u'b', u'c', u'd']
    >     >>> re.findall(r'\S+', s)
    >     [u'a', u'b\xa0c', u'd']  
    > 
    
    If you want the Unicode interpretation of \S+, etc, you pass the
    re.UNICODE flag:
    
            >>> re.findall(r'\S+', s,re.UNICODE)
            [u'a', u'b', u'c', u'd']
    
    See http://docs.python.org/lib/node46.html
    
    > 
    > This isn't documented either:
    > 
    >     >>> s = ' b c '
    >     >>> s.split()
    >     ['b', 'c']
    >     >>> s.split(' ')
    >     ['', 'b', 'c', '']
    
    I believe the following documents it accurately:
    http://docs.python.org/lib/string-methods.html
    
            If sep is not specified or is None, a different splitting
            algorithm is applied. First, whitespace characters (spaces,
            tabs, newlines, returns, and formfeeds) are stripped from both
            ends. Then, words are separated by arbitrary length strings of
            whitespace characters. Consecutive whitespace delimiters are
            treated as a single delimiter ("'1 2 3'.split()" returns "['1',
            '2', '3']"). Splitting an empty string or a string consisting of
            just whitespace returns an empty list.
    
    
    
    From steve at holdenweb.com  Mon Jul 30 11:16:01 2007
    From: steve at holdenweb.com (Steve Holden)
    Date: Mon, 30 Jul 2007 11:16:01 -0400
    Subject: How to write GUI and event separately in wxPython??
    In-Reply-To: <5h5upbF3hmufcU5@mid.uni-berlin.de>
    References: <1185777254.925902.204500@z28g2000prd.googlegroups.com>	<5h5kmiF3hmufcU3@mid.uni-berlin.de>	
    	<5h5upbF3hmufcU5@mid.uni-berlin.de>
    Message-ID: 
    
    Marc 'BlackJack' Rintsch wrote:
    > On Mon, 30 Jul 2007 06:32:55 -0400, Steve Holden wrote:
    > 
    >>  >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)]
    >> True
    > 
    > First I thought: Why the unnecessary list comprehension but to my surprise:
    > 
    > In [33]: xrange(42) == xrange(42)
    > Out[33]: False
    > 
    > That's strange.
    > 
    Not so strange really. The two xrange objects are different (though I 
    confess I haven't looked to see how they implement comparisons), but 
    iterating over them produces the same 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 john.jusayan at gmail.com  Thu Jul 19 18:25:19 2007
    From: john.jusayan at gmail.com (jrbj)
    Date: Thu, 19 Jul 2007 22:25:19 -0000
    Subject: Itertools question: how to call a function n times?
    In-Reply-To: 
    References: 
    Message-ID: <1184883919.038945.143090@x40g2000prg.googlegroups.com>
    
    On Jul 19, 8:35 am, Matthew Wilson  wrote:
    > I want to write a function that each time it gets called, it returns a
    > random choice of 1 to 5 words from a list of words.
    >
    > I can write this easily using for loops and random.choice(wordlist) and
    > random.randint(1, 5).
    >
    > But I want to know how to do this using itertools, since I don't like
    > manually doing stuff like:
    >
    >     phrase = list()
    >     for i in random.randint(1, 5):
    >
    >         phrase.append(random.choice(wordlist))
    
    All the previous suggestions in this thread are good. If you *must*
    use itertools, you can use the itertools.repeat function to return an
    object x many times:
    
    phrase = [somewords(wordlist) for somewords in
                  itertools.repeat(random.choice, random.randint(1, 5))]
    
    
    Hope it helps,
    John
    
    
    
    From wbrehaut at mcsnet.ca  Sat Jul 14 13:39:36 2007
    From: wbrehaut at mcsnet.ca (Wayne Brehaut)
    Date: Sat, 14 Jul 2007 11:39:36 -0600
    Subject: Can a low-level programmer learn OOP?
    References:  
    	
    Message-ID: 
    
    On Fri, 13 Jul 2007 20:37:04 -0400, Steve Holden 
    wrote:
    
    >Aahz wrote:
    >> In article ,
    >> Chris Carlen   wrote:
    >>>From what I've read of OOP, I don't get it.  
    >> 
    >> For that matter, even using OOP a bit with C++ and Perl, I didn't get it
    >> until I learned Python.
    >> 
    >>> The problem for me is that I've programmed extensively in C and .asm on 
    >>> PC DOS way back in 1988.  
    >> 
    >> Newbie.  ;-)
    >> 
    >> (I started with BASIC in 1976.)
    >> 
    >Newbie ;-)
    >
    >(I started with Algol 60 in 1967).
    
    Newbie ;-)
    
    (I started with Royal McBee LGP 30 machine language (hex input) in
    1958, and their ACT IV assembler later! Then FORTRAN IV in 1965. By
    1967 I too was using (Burroughs) Algol-60, and 10 years later upgraded
    to (DEC-10) Simula-67.)
    
    Going---going---
    
    >>> Form 2:  Use Python and PySerial and TkInter or wxWidgets.
    >>>
    >>> Pro:  Cross-platform goal will likely be achieved fully.  Have a 
    >>> programmer nearby with extensive experience who can help.
    >>> Con:  Must learn new language and library.  Must possibly learn a 
    >>> completely new way of thinking (OOP) not just a new language syntax. 
    >>> This might be difficult.
    >> 
    >> My experience is that learning GUI programming is difficult.  Moreover,
    >> GUI programming in C involves a lot of boilerplate that can be automated
    >> more easily with Python.  So I think this will be a better solution.
    >> 
    >I used to write in C for the SunView platform (back in the days when the 
    >GUI was integrated into the kernel as the only way to get acceptable 
    >speed on the display). From what I remember, "Hello World" took about 40 
    >lines.
    >
    >The immense (relatively speaking: this was 1985) size of the libraries 
    >required was one of the primary justifications for implementing shared 
    >libraries.
    >
    >> Note very very carefully that Python does not require an OOP style of
    >> programming, but it will almost certainly be the case that you just
    >> naturally start using OOP techniques as you learn Python.
    >
    >That's very true. I still use a lot of (perhaps too much) procedural 
    >coding, but driving the object-oriented libraries is a great way for a 
    >noob to get started in OOP.
    >
    >regards
    >  Steve
    
    
    From cathy at nachofoto.com  Tue Jul  3 02:58:31 2007
    From: cathy at nachofoto.com (Cathy Murphy)
    Date: Mon, 2 Jul 2007 23:58:31 -0700
    Subject: Python compilation ??
    In-Reply-To: 
    References: 
    	
    	
    Message-ID: 
    
    Ahh!! lots of thoughts!!
    
    Thanks guys!!
    
    -- 
    Cathy
    www.nachofoto.com
    
    On 7/2/07, John Nagle  wrote:
    >
    > Evan Klitzke wrote:
    > > On 7/2/07, Cathy Murphy  wrote:
    > >
    > >> Is python a compiler language or interpreted language. If it is
    > >> interpreter
    > >> , then why do we have to compile it?
    > >
    > >
    > > It's an interpreted language. It is compiled into bytecode (not
    > > machine code) the first time a script is run to speed up subsequent
    > > executions of a script.
    >
    >   CPython compiles to an intermediate form, rather than
    > all the way to machine code, and executes the intermediate form,
    > which is basically a tree, with an interpreter written in C.
    >
    >   ShedSkin Python compiles to C++, then all the way to machine code.
    > Some CPython features have to be disallowed, but there's a huge
    > performance gain.
    >
    >   Jython compiles to Java byte code, which is then compiled to
    > machine code by a just-in-time compiler.
    >
    >   Iron Python compiles to Microsoft's byte code as used by their
    > ".NET" common language runtime.  This is then compiled to machine
    > code by a just-in-time compiler.
    >
    >                                John Nagle
    > --
    > http://mail.python.org/mailman/listinfo/python-list
    >
    -------------- next part --------------
    An HTML attachment was scrubbed...
    URL: 
    
    From westymatt at gmail.com  Mon Jul 23 08:23:01 2007
    From: westymatt at gmail.com (westymatt)
    Date: Mon, 23 Jul 2007 12:23:01 -0000
    Subject: Catching a key press
    In-Reply-To: <1185182869.893136.139870@k79g2000hse.googlegroups.com>
    References: <1185173730.345615.284940@q75g2000hsh.googlegroups.com>
    	<1185174340.795377.13800@r34g2000hsd.googlegroups.com>
    	<1185182869.893136.139870@k79g2000hse.googlegroups.com>
    Message-ID: <1185193381.092023.182050@g4g2000hsf.googlegroups.com>
    
    linux primarily still a little lost in how to implementent this,
    however I understand what you are saying.
    
    
    
    From paddy3118 at googlemail.com  Sun Jul 15 15:57:35 2007
    From: paddy3118 at googlemail.com (Paddy)
    Date: Sun, 15 Jul 2007 12:57:35 -0700
    Subject: Can a low-level programmer learn OOP?
    In-Reply-To: 
    References: 
    Message-ID: <1184529455.016302.251530@n60g2000hse.googlegroups.com>
    
    On Jul 13, 5:06 pm, Chris Carlen 
    wrote:
    > Hi:
    > Christopher
    
    >
    > Problem:
    >
    > 1.  How to most easily learn to write simple PC GUI programs that will
    > send data to remote embedded devices via serial comms, and perhaps
    > incorporate some basic (x,y) type graphics display and manipulation
    > (simple drawing program).  Data may result from user GUI input, or from
    > parsing a text config file.  Solution need not be efficient in machine
    > resource utilization.  Emphasis is on quickness with which programmer
    > can learn and implement solution.
    
    Have you also tried looking for a cross-platform GUI program that has
    a
    scripting interface that you might adapt? If found then the extra
    scripting needs may be reduced.
    
    - Paddy.
    
    
    
    From nospam at nospam.com  Sun Jul 22 00:56:32 2007
    From: nospam at nospam.com (Gilles Ganault)
    Date: Sun, 22 Jul 2007 06:56:32 +0200
    Subject: [2.5] Regex doesn't support MULTILINE?
    References: 
    	
    Message-ID: 
    
    On Sat, 21 Jul 2007 22:18:56 -0400, Carsten Haese
     wrote:
    >That's your problem right there. RE is not the right tool for that job.
    >Use an actual HTML parser such as BeautifulSoup
    
    Thanks a lot for the tip. I tried it, and it does look interesting,
    although I've been unsuccessful using a regex with BS to find all
    occurences of the pattern.
    
    Incidently, as far as using Re alone is concerned, it appears that
    re.MULTILINE isn't enough to get Re to include newlines: re.DOTLINE
    must be added.
    
    Problem is, when I add re.DOTLINE, the search takes less than a second
    for a 500KB file... and about 1mn30 for a file that's 1MB, with both
    files holding similar contents.
    
    Why such a huge difference in performance?
    
    ========= Using Re =============
    import re
    import time
    
    pattern = "(\d+:\d+).*?"
    
    pages = ["500KB.html","1MB.html"]
    
    #Veeeeeeeeeeery slow when parsing 1MB file !
    p = re.compile(pattern,re.IGNORECASE|re.MULTILINE|re.DOTALL)
    #p = re.compile(pattern,re.IGNORECASE|re.MULTILINE)
    
    for page in pages:
    	f = open(page, "r") 
    	response = f.read() 
    	f.close()
    
    	start = time.strftime("%H:%M:%S", time.localtime(time.time()))
    	print "before findall @ " + start
    	packed = p.findall(response)
    	if packed:
    		for item in packed:
    			print item
    ===========================
    
    Thank you.
    
    
    From hniksic at xemacs.org  Wed Jul 18 06:55:01 2007
    From: hniksic at xemacs.org (Hrvoje Niksic)
    Date: Wed, 18 Jul 2007 12:55:01 +0200
    Subject: Semantics of file.close()
    References: <1184628945.314844.53300@k79g2000hse.googlegroups.com>
    	
    	<87veciem6f.fsf@mulj.homelinux.net>
    	
    Message-ID: <87ejj656d6.fsf@mulj.homelinux.net>
    
    "Evan Klitzke"  writes:
    
    >> But the writes are buffered, and close causes the buffer to be
    >> flushed.  file.close can throw an exception just like fclose, but
    >> it will still ensure that the file is closed.
    >
    > Is this buffering being done by Python or the kernel?
    
    It is done in the user space, by the C stdio library which Python
    currently uses for IO.
    
    
    From http  Mon Jul  2 11:43:39 2007
    From: http (Paul Rubin)
    Date: 02 Jul 2007 08:43:39 -0700
    Subject: Tiny/small/minimalist Python?
    References: <1183332951.122782.212720@o11g2000prd.googlegroups.com>
    	<7xved3satm.fsf@ruckus.brouhaha.com>
    	<1183389420.175712.59460@z28g2000prd.googlegroups.com>
    Message-ID: <7xmyyeizf8.fsf@ruckus.brouhaha.com>
    
    rtk  writes:
    > FYI.. I wanted a simple version of Python to run on an ancient DEC
    > Alpha box.  I got VMS Python 2.5 up and running but it is too slow to
    > use.  It takes *minutes* to get the interpreter prompt after typing
    > 'python'! 
    
    Something is wrong.  Maybe it's trying to DNS itself and timing out,
    or something like that.
    
    
    From dak at gnu.org  Sun Jul  8 02:11:41 2007
    From: dak at gnu.org (David Kastrup)
    Date: Sun, 08 Jul 2007 08:11:41 +0200
    Subject: The Modernization of Emacs: terminology buffer and keybinding
    References: <1182093200.598418.218620@e9g2000prf.googlegroups.com>
    	<1182272495.990807.99110@a26g2000pre.googlegroups.com>
    	<87tzt3ihev.fsf@kobe.laptop> 
    	<1182370216.961241.6960@n60g2000hse.googlegroups.com>
    	<85zm2ufjpb.fsf@lola.goethe.zz>
    	<1182372592.803332.288260@u2g2000hsc.googlegroups.com>
    	<1182373919.262388.100740@c77g2000hse.googlegroups.com>
    	<85r6o6fhkb.fsf@lola.goethe.zz>
    	<1182375045.626510.188170@m36g2000hse.googlegroups.com>
    	<85myyufgwj.fsf@lola.goethe.zz>
    	<1182375528.985142.293900@q69g2000hsb.googlegroups.com>
    	
    	<1182545268.055596.228700@i38g2000prf.googlegroups.com>
    	
    	<1183841277.333384.188950@g4g2000hsf.googlegroups.com>
    	
    	<1183856442.027967.272530@g4g2000hsf.googlegroups.com>
    Message-ID: <853azza0gy.fsf@lola.goethe.zz>
    
    Twisted  writes:
    
    > On Jul 7, 6:12 pm, Lew  wrote:
    >> Twisted wrote:
    >> Edward Dodge wrote:
    >> >> So -- what magical computer app illuminates the entire room and shows
    >> >> you how to use everything at the flip of a switch?  This brilliant
    >> >> discovery would put Sam's, O'Reilly, the for-Dummies series, and
    >> >> virtually every other computer book publisher out of business in weeks.
    >> >> Naturally, this would include the publishers of books on "easy-to-use"
    >> >> Microsoft products.
    >>
    >> > I don't know, but it sure as hell isn't emacs.
    >>
    >> The reason you don't know, and Edward Dodge's point, is that there is no such
    >> app, whether emacs or not.
    >
    > Translation: since perfection is unattainable, we shouldn't even try,
    > and just foist upon our poor users whatever awkward and hard-to-learn
    > interface pops into our heads first?
    
    I recommend you just shut up _until_ you have checked out a recent
    version of Emacs.  You just have no clue what you are talking about
    and are still stuck in the eighties.
    
    Emacs has an obvious "Help" toolbar button in the standard place, it
    has a "Help" menu in the standard place, it reacts to presses of F1 by
    delivering help, it has tooltips all over the mode line and for pretty
    much every menu entry (and the menus are plenty and well-sorted for
    doing the most-frequent tasks).
    
    In addition, the quality of those help items is far above average.
    But you would not know since you prefer babbling about some passing
    decade-old experience.  If you had invested half of the time using
    Emacs you have invested for complaining about it, you'd at least have
    a chance not to look like the totally pompous clueless idiot you do
    now.
    
    -- 
    David Kastrup, Kriemhildstr. 15, 44793 Bochum
    
    
    From http  Tue Jul 17 23:01:27 2007
    From: http (Paul Rubin)
    Date: 17 Jul 2007 20:01:27 -0700
    Subject: Semantics of file.close()
    References: <1184628945.314844.53300@k79g2000hse.googlegroups.com>
    	
    	<87veciem6f.fsf@mulj.homelinux.net>
    	
    Message-ID: <7xd4yqs9dk.fsf@ruckus.brouhaha.com>
    
    "Evan Klitzke"  writes:
    > Is this buffering being done by Python or the kernel?
    
    I think this refers to buffering done in the C stdio library, which
    Python uses.
    
    
    From http  Thu Jul 26 17:02:46 2007
    From: http (Paul Rubin)
    Date: 26 Jul 2007 14:02:46 -0700
    Subject: removing items from a dictionary ?
    References: <46A8EFF5.4060600@mailbox.kun.nl>
    	
    	
    Message-ID: <7xabtikhe1.fsf@ruckus.brouhaha.com>
    
    Stef Mientki  writes:
    > >     for net in Nets.keys():
    > >     # Nets.iterkeys() would avoid building the list
    > >     # but that runs the same risks as your original
    > >         if net.upper() in  in Eagle_Power_Nets :
    > >             del Nets[net]
    > >
    > thanks Steve,
    > that does the job.
    
    Depending on the relative sizes of those dicts, maybe
    you want to try rebuilding instead of deleting.  Untested:
    
        Nets = dict((k,v) for k,v in Nets.itervalues() 
                          if k.upper() not in Eagle_Power_Nets)
    
    
    From chrispwd at gmail.com  Wed Jul 25 21:32:52 2007
    From: chrispwd at gmail.com (chrispwd at gmail.com)
    Date: Wed, 25 Jul 2007 18:32:52 -0700
    Subject: Reading files, splitting on a delimiter and newlines.
    In-Reply-To: <1185407770.462158.57490@z24g2000prh.googlegroups.com>
    References: <1185378363.166434.172190@r34g2000hsd.googlegroups.com>
    	<1185407770.462158.57490@z24g2000prh.googlegroups.com>
    Message-ID: <1185413572.490248.173460@o61g2000hsh.googlegroups.com>
    
    On Jul 25, 7:56 pm, "attn.steven.... at gmail.com"
     wrote:
    > On Jul 25, 8:46 am, chris... at gmail.com wrote:
    >
    >
    >
    > > Hello,
    >
    > > I have a situation where I have a file that contains text similar to:
    >
    > > myValue1 = contents of value1
    > > myValue2 = contents of value2 but
    > >                         with a new line here
    > > myValue3 = contents of value3
    >
    > > My first approach was to open the file, use readlines to split the
    > > lines on the "=" delimiter into a key/value pair (to be stored in a
    > > dict).
    >
    > > After processing a couple files I noticed its possible that a newline
    > > can be present in the value as shown in myValue2.
    >
    > > In this case its not an option to say remove the newlines if its a
    > > "multi line" value as the value data needs to stay intact.
    >
    > > I'm a bit confused as how to go about getting this to work.
    >
    > > Any suggestions on an approach would be greatly appreciated!
    >
    > Check the length of the list returned from split; this allows
    > your to append to the previously extracted value if need be.
    >
    > import StringIO
    > import pprint
    >
    > buf = """\
    > myValue1 = contents of value1
    > myValue2 = contents of value2 but
    >                    with a new line here
    > myValue3 = contents of value3
    > """
    >
    > mockfile = StringIO.StringIO(buf)
    >
    > record=dict()
    >
    > for line in mockfile:
    >     kvpair = line.split('=', 2)
    >     if len(kvpair) == 2:
    >         key, value = kvpair
    >         record[key] = value
    >     else:
    >         record[key] += line
    >
    > pprint.pprint(record)
    >
    > # lstrip() to remove newlines if needed ...
    >
    > --
    > Hope this helps,
    > Steven
    
    Great thank you! That was the logic I was looking for.
    
    
    
    From martin.clausen at gmail.com  Tue Jul  3 06:47:42 2007
    From: martin.clausen at gmail.com (Martin)
    Date: Tue, 03 Jul 2007 10:47:42 -0000
    Subject: 15 Exercises to Know A Programming Language
    In-Reply-To: <5eumhhF39v66mU2@mid.uni-berlin.de>
    References: <1183456696.168214.114900@o61g2000hsh.googlegroups.com>
    	<5eumhhF39v66mU2@mid.uni-berlin.de>
    Message-ID: <1183459662.072934.215470@k79g2000hse.googlegroups.com>
    
    On Jul 3, 12:25 pm, Marc 'BlackJack' Rintsch  wrote:
    > On Tue, 03 Jul 2007 09:58:16 +0000, Martin wrote:
    > > "Write a program that takes as its first argument one of the words
    > > 'sum,' 'product,' 'mean,' or 'sqrt'  and for further arguments a
    > > series of numbers. The program applies the appropriate function to
    > > the series."
    >
    > > My solution so far is this:
    >
    > >http://dpaste.com/13469/
    >
    > > I would really like some feedback. Is this a good solution? is it
    > > efficient? robust? what could be improved? any not looking for a
    > > revised solution, hints on what to improve are also very welcome.
    >
    > Don't use `eval()` if it is not absolutely necessary.  Especially if the
    > input comes from a user it's a security hole.  `float()` is the function
    > to use here.
    >
    > `mean()` does not work as you try to divide a list by a number.
    >
    > Ciao,
    >         Marc 'BlackJack' Rintsch
    
    Thanks for the feedback. I have posted a revised version here (http://
    dpaste.com/13474/) where mean works. The reason I use eval is I want
    it to work for complex numbers too, but I guess i could check for the
    presence of a "j" in the arguments instead.
    
    Martin
    
    
    
    From bignose+hates-spam at benfinney.id.au  Sun Jul  8 01:00:10 2007
    From: bignose+hates-spam at benfinney.id.au (Ben Finney)
    Date: Sun, 08 Jul 2007 15:00:10 +1000
    Subject: Broken MUA interactions (was: Restarting a Python Application)
    References: <1183498045.092504.229250@m36g2000hse.googlegroups.com>
    	<94ccbe710707071511o3beee718wc12f15082b3c6e18@mail.gmail.com>
    	
    Message-ID: <87vecvmqw5.fsf_-_@benfinney.id.au>
    
    "Peter Decker"  writes:
    
    > Imagine if you wrote applications where the default behavior did not
    > do what was needed 99% of the time: how long do you think you'd be
    > in business?
    
    You seem to be complaining about the functionality of your mail user
    agent (MUA) software. The mailing list processor is doing its job
    fine.
    
    There are at least two "compose a reply" functions supported by every
    MUA. Use the one that does what you want in each instance.
    
    If you use the "Reply to individual sender" function, that's what you
    get.
    
    If you use the "Reply to all" function, that's what you get.
    
    If you use the "Reply to the list" function, that's what you get.
    
    > The default behavior of replying to the original sender instead of
    > the list makes no sense.
    
    The mailing list software provides your MUA with all the information
    it needs to do what you want: the 'From' address as set by the
    original poster, the 'Reply-To' address as set by the original poster,
    the 'To' and 'Cc' addresses as set by the original poster, and the
    'List-Post' address as set by the mailing list software. All of these
    are standard message header fields with well-defined functions, and
    can be used as-is to do what you need.
    
    If your MUA isn't using this information correctly, the solution is to
    fix the MUA (by choosing a better one or encouraging the maker of your
    existing one to fix it), not to munge those fields to accomodate your
    broken MUA.
    
    -- 
     \         "Dyslexia means never having to say that you're ysror."  -- |
      `\                                                         Anonymous |
    _o__)                                                                  |
    Ben Finney
    
    
    From tdelaney at avaya.com  Wed Jul  4 19:15:11 2007
    From: tdelaney at avaya.com (Delaney, Timothy (Tim))
    Date: Thu, 5 Jul 2007 07:15:11 +0800
    Subject: deleated bios?
    In-Reply-To: <1183584286.963465.324820@n60g2000hse.googlegroups.com>
    Message-ID: 
    
    acprkit wrote:
    
    > Hi
    > 
    > I have an ibm thinkpad x23, and shut it down about an hour ago. When I
    > went to
    > reboot , all the lights come on then they go off and only the light
    > with the z in a circle stays on. The screen stays blank and the hard
    > drive spins. Could I have deleated the bios when I added memory
    > (shocked the motherboard?)
    
    http://www.catb.org/~esr/faqs/smart-questions.html#forum
    
    Tim Delaney
    
    
    From aaron.watters at gmail.com  Wed Jul 11 09:52:48 2007
    From: aaron.watters at gmail.com (aaron.watters at gmail.com)
    Date: Wed, 11 Jul 2007 06:52:48 -0700
    Subject: bool behavior in Python 3000?
    In-Reply-To: <1184139458.063988.63510@w3g2000hsg.googlegroups.com>
    References: 
    	
    	
    	
    	
    	<7xodijdd8r.fsf@ruckus.brouhaha.com>
    	
    	<1184139458.063988.63510@w3g2000hsg.googlegroups.com>
    Message-ID: <1184161968.964987.125190@d55g2000hsg.googlegroups.com>
    
    On Jul 11, 3:37 am, Rob Wolfe  wrote:
    >
    > But `bools` are usefull in some contexts. Consider this:
    >
    > >>> 1 == 1
    > True
    > >>> cmp(1, 1)
    > 0
    > >>> 1 == 2
    > False
    > >>> cmp(1, 2)
    >
    > -1
    >
    > At first look you can see that `cmp` does not return boolean value
    > what not for all newbies is so obvious.
    
    Excellent point!  And as long as we have them I
    agree with Alan that the boolean data type should
    implement real boolean algebra with respect to +, *, and ~,
    for example supporting operator precedence appropriately
    (versus using and, or, not) and also correctly
    implementing DeMorgan's laws and other property's of
    boolean algebra
    
       ~(a*b) == ~a + ~b
    
    etcetera.
    
    1+True is bad practice and should be an error.
    
    Anything else is false advertising
    (and the java community has the patent on that
    methodology :c) ).
    
      -- Aaron Watters
    
    ===
    Why does a giraffe have such a long neck?
    Because its head is so far from its body!
    
    
    
    From gerard.blais at gmail.com  Fri Jul  6 14:20:06 2007
    From: gerard.blais at gmail.com (Gerry)
    Date: Fri, 06 Jul 2007 18:20:06 -0000
    Subject: file reading anomaly
    In-Reply-To: <1183740495.413999.133660@g13g2000hsf.googlegroups.com>
    References: <1183740495.413999.133660@g13g2000hsf.googlegroups.com>
    Message-ID: <1183746006.340425.96840@c77g2000hse.googlegroups.com>
    
    Update:
    
       The PC seems to not be a factor (same problem exist on two PCs).
    
       The entire script does some computation and writes depstats.txt.
    The code snippet below attempts to read depstats.txt and write another
    file.  When the code below is run stand-alone, it succeeds.  When run
    in-line as part of the program that wrote depstats.txt, there are
    three possible outcomes:
    
    it stops reading after 4096 bytes (not counting \r's); no error
    messages
    it stops reading after 8192 bytes (not counting \r's); no error
    messages
    or it succeeds.
    
    The first two are much more likely.
    
    Trying buffersize parameters of -1, 0, 1, 1000, 8192, 16384 in the
    open call for m all had no apparent effect.
    
    Any ideas what could possibly be wrong earlier to cause this?
    
    
    m           = open("depstats.txt",    "r", 20000)
    n           = open("newds.txt",       "w")
    
    linesout    = 0
    bytes       = 0
    
    for line in m:
        bytes   += len(line)
        print   len(line), len(line.split()), bytes
        t       = line.split()
        if len(t) < 13:
            print "not enough fields, only", len(t)
            print t
            sys.exit()
        while len(t) < 43:
            t.append(0)
        t.append("F2")
        t           = [str(x) for x in t]
        print       >> n, " ".join(t)
        linesout    += 1
    
    print "linesout", linesout
    
    m.close()
    n.close()
    
    
    
    On Jul 6, 12:48 pm, Gerry  wrote:
    > Python 2.5, Windows XP.
    >
    > I have a 48-line text file written by a Windows python script,
    >
    > I try to read it as follows:
    >
    > f       = open ("depstats.txt", "r", 0)
    
    > for index, line in enumerate(f):
    >     print index, len(line), len(line.split())
    > f.close()
    >
    > On one PC, this runs without any problem.
    >
    > On another, it appears to succeed (no run-time errors) but does not
    > read all the lines.  If I print the lines and sum of the line lengths
    > so far inside the loop, the program can be seen to have only read the
    > first N bytes, where N is either 4096, or 8192.
    >
    > Any ideas?
    >
    > Thanks,
    >
    > Gerry
    
    
    
    
    
    
    From steve at holdenweb.com  Fri Jul 13 22:25:31 2007
    From: steve at holdenweb.com (Steve Holden)
    Date: Fri, 13 Jul 2007 22:25:31 -0400
    Subject: MaildirMessage
    In-Reply-To: <87vecniw4u.fsf@benfinney.id.au>
    References: <1184287592.509355.310110@g4g2000hsf.googlegroups.com>		<874pk8kedo.fsf@benfinney.id.au>	
    	<87vecniw4u.fsf@benfinney.id.au>
    Message-ID: 
    
    Ben Finney wrote:
    > Steve Holden  writes:
    > 
    >> Ben Finney wrote:
    >>> Which is a bug in the 'email.message' module, in my view. If it's
    >>> attempting to support a mapping protocol, it should allow
    >>> iteration the same way standard Python mappings do: by iterating
    >>> over the keys.
    >> Stop assuming that everyone sees requirements the same as you - the
    >> author of the email module has long years of experience, and has
    >> provided an excellent and overall usable piece of software.
    > 
    > I don't see that this fact (which I agree is the case) in any way
    > makes the code immune from bugs, nor from the discussion of the
    > possibility.
    > 
    >> Criticisms such as yours are easy (we can all experess our opinions,
    >> to which we are all entitled), but mere expression of an opinion
    >> isn't going to change anything.
    > 
    > It can, though, lead to a discussion about whether it *is* a bug or
    > not.
    > 
    > Care to contribute something other than the lashing you put into your
    > message?
    > 
    Apart from the lashing (lashing? I take it you've never visited 
    comp.lang.perl regularly) I think Gabriel said it well enough: there 
    just doesn't seem to be a compelling case that "iteration over a 
    message" should do what you apparently expected it to.
    
    What do you actually think
    
    ...     for m in msg:
    ...             print m
    
    should do? Why do you believe that what you think it should do would be 
    a natural choice?
    
    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 johnmasters at oxtedonline.net  Tue Jul 17 17:47:33 2007
    From: johnmasters at oxtedonline.net (John K Masters)
    Date: Tue, 17 Jul 2007 22:47:33 +0100
    Subject: sqlite tuples
    In-Reply-To: <1184707856.3400.8.camel@dot.uniqsys.com>
    References: <20070717204903.GA3890@spookie1.spookiegate>
    	<1184707856.3400.8.camel@dot.uniqsys.com>
    Message-ID: <20070717214733.GA27047@spookie1.spookiegate>
    
    On 17:30 Tue 17 Jul     , Carsten Haese wrote:
    > On Tue, 2007-07-17 at 21:49 +0100, John K Masters wrote:
    > > I am fairly new to Python and am trying to get to grips with pysqlite2.
    > > >From what I have read data is returned as a list of tuples when using
    > > SELECT via connection.cursor.  But I have not, despite frantic googling,
    > > found how to INSERT a list of tuples into a sqlite table. If I convert
    > > the tuple to a string and concatenate it to the 'INSERT INTO table etc.'
    > > string then it works, but only if all the tuple values are strings and
    > > then only if all the table fields are of type TEXT.
    > > 
    > > Is it possible to, and if so how can one, insert a list of tuples into a
    > > sqlite table?
    > 
    > Assuming that each tuple is the same length and goes into the same table
    > and columns, something like this will do the trick:
    > 
    > sql = "insert into tablename(column1,column2,column3) values(?,?,?)"
    > cursor.executemany(sql, list_of_tuples)
    > 
    > If you don't know the number of columns at design time, you'll need to
    > fill the values(...) clause on the fly with the correct number of
    > question marks, and you'll have to build the list of column names
    > somehow, too, but the basic idea is the same.
    > 
    > HTH,
    > 
    Thanks, I'll try that tomorrow. Number of columns are known and static;
    I'm extracting the data from a report generated by an old DOS program. I
    had been converting it to CSV and plugging it into Open Office Calc but
    it is now getting beyond that and I need to do a bit more with the data.
    
    Regards, John
    -- 
    War is God's way of teaching Americans geography
    Ambrose Bierce (1842 - 1914)
    
    
    From rustompmody at gmail.com  Sun Jul  1 00:25:04 2007
    From: rustompmody at gmail.com (Rustom Mody)
    Date: Sun, 1 Jul 2007 09:55:04 +0530
    Subject: How to uninstall packages
    Message-ID: 
    
    Recently I had trouble with the sqlite package under my debian etch
    box as follows:
    
    I first installed the debian package python-pysqlite1.1 using
    synaptic. Since this seemed too old for other packages (sqlalchemy) I
    downloaded the sources  pysqlite-2.3.4.tar.gz and ran setup install.
    
    This gave the problem that _sqlite was not found.
    
    And now the apt system started complaining that it could not uninstall
    it because of some new files.
    
    I finally (seem to have :-) ) got it to work by going into
    /usr/lib/python2.4/site-packages/ and deleting the pysqlite directory
    and reinstalling using apt.
    
    However this is an unsatisfactory solution because I do not know what
    else I should delete
    
    So now my question:  How does one uninstall  *cleanly*
    
    1> a package installed using setup.py install
    2> a package installed with easy_install
    
    Thanks
    
    
    From jstroud at mbi.ucla.edu  Tue Jul 24 15:47:43 2007
    From: jstroud at mbi.ucla.edu (James Stroud)
    Date: Tue, 24 Jul 2007 12:47:43 -0700
    Subject: Cleaning up a string
    Message-ID: 
    
    Hello all,
    
    I dashed off the following function to clean a string in a little 
    program I wrote:
    
    def cleanup(astr, changes):
       for f,t in changes:
         atr = astr.replace(f, t)
       return astr
    
    where changes would be a tuple, for example:
    
    changes = (
                  ('%', '\%'),
                  ('$', '\$'),
                  ('-', '_')
               )
    
    
    If these were were single replacements (like the last), string.translate 
    would be the way to go. As it is, however, the above seems fairly 
    inefficient as it potentially creates a new string at each round. Does 
    some function or library exist for these types of transformations that 
    works more like string.translate or is the above the best one can hope 
    to do without writing some C? I'm guessing that "if s in astr" type 
    optimizations are already done in the replace() method, so that is not 
    really what I'm getting after.
    
    James
    
    -- 
    James Stroud
    UCLA-DOE Institute for Genomics and Proteomics
    Box 951570
    Los Angeles, CA 90095
    
    http://www.jamesstroud.com/
    
    
    From dennis.varghese at wipro.com  Fri Jul 20 11:20:23 2007
    From: dennis.varghese at wipro.com (pycraze)
    Date: Fri, 20 Jul 2007 08:20:23 -0700
    Subject: Need Help
    Message-ID: <1184944823.752076.93230@e16g2000pri.googlegroups.com>
    
    Hi ,
    
           I am currently working on NTLM (Windows NT Lan Manager) APS
    (Authentication Proxy Server ) . NTLM is MS own proprietary protocol
    that will allow successful authentication for only MS browsers .
    
          NTLM APS was successfully cracked by Rosmanov and i am working
    on NTLM APS python package version 0.98 .  I am currently on it to
    port to C language .
    
          I have a specific issue on the authentication technique which
    this APS uses . NTLM APS python package ver 0.98 uses two major types
    of authentication process
    
    1) DES
    2) MD4 .
    
         The author has clearly stated that he has adopted both the above
    python implementations from Python Cryptology Toolkit ( py-crypto)
    version 2.0.1 . I started to use the DES C implementation of py-crypto
    so that i can have an equivalent DES python implementation without
    breaking a sweat . ;-)
    
         But both the implementation was totally different . I am getting
    different hashed outputs . I compared each byte value of password from
    python DES implementation and C implementation , both were not same .
    
        Is anyone out there, can tell me why they are different .
        Also i found that the key generation is different between them and
    i suspect because of this the outputs are different ? So can this be
    that the C implementation of DES in py-crypto had bugs and that it had
    been corrected by Rozmanov and implemented in python ?
    
        Also will there be any difference in implementing DES b/w python
    and C language ?
    
    Thanks,
    
    Dennis
    
    
    
    From bdesth.quelquechose at free.quelquepart.fr  Sun Jul 22 02:17:09 2007
    From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers)
    Date: Sun, 22 Jul 2007 08:17:09 +0200
    Subject: Why PHP is so much more popular for web-development
    In-Reply-To: <1185392048.737400.290050@j4g2000prf.googlegroups.com>
    References: <1185385374.866372.198520@x35g2000prf.googlegroups.com>
    	
    	<1185392048.737400.290050@j4g2000prf.googlegroups.com>
    Message-ID: <46a7b908$0$32130$426a34cc@news.free.fr>
    
    walterbyrd a ?crit :
    > On Jul 25, 12:40 pm, Carsten Haese  wrote:
    > 
    > 
    >>What exactly could Python learn from PHP?
    > 
    > 
    > Remember, I'm a noob, I'm not trolling.
    > 
    > When I posted "Python" I meant the Python web-developement world. In
    > particular, python frameworks, like CherryPy, have requirements that
    > are not realistic for most shared hosting plans.
    > 
    > Maybe I'm wrong, but I often get the idea that those  who develop
    > python frameworks don't give a thought to the realities of shared
    > hosting. They seem to think that everybody has complete control over
    > the server. Things are very different in the PHP universe.
    
    Fact is that most of the Python developpers working in this domain are 
    doing it in a professional context - which usually implies dedicated 
    servers, or at least professional-quality hosting. To make a long story 
    short, most of Python-based web development solutions compete with Java, 
    not with PHP.
    
    > To use codeignitor as an example, again. On the "why  codeignitor"
    > part of the welcome page you will find:
    > 
    > ---
    > CodeIgniter is right for you if...
    > * You need broad compatibility with standard hosting accounts that run
    > a variety of PHP versions and configurations.
    > * You want a framework that requires nearly zero configuration.
    > * You want a framework that does not require you to use the command
    > line.
    > ---
    > 
    > I don't seem to see Python frameworks using those sorts of selling
    > points. 
    
    Hopefully not - except perhaps for the second point. Being a 
    professional web developer implies a knowledge that is far beyond what 
    one can expect of the typical PHP user.
    
    > Posting as a noob, who is struggling to get django configured
    > on dreamhost, I gotta tell 'ya: those selling points look awfully
    > attractive.
    
    Posting as a web developer, I dont give a damn about points #1 and #3. 
    wrt/ point #2, I expect my tools to be configurable, but with sensible 
    defaults.
    
    > The point is: PHP framework makers are very considerate of the
    > realities of shared hosting.
    
    You mean: of grand-public, low-price shared hosting.
    
    And yes, that's true: most PHP frameworks are for non-programmers.
    
    > Python framework makers don't seem to
    > give it a thought.
    
    They do. But the issue here is that most low-budget share-hosting 
    providers just don't give a damn about Python anyway (at best you'll 
    have cgi with a prehistoric Python version), so there's just no reason 
    to try to be competitive here. Either you are a casual user with 101 web 
    development skills trying to set up your personal home page (ever 
    wondered what PHP stands for ?), and then PHP is quite enough for you, 
    or you are doing professional-quality web development, and then you know 
    how to use a unix command line, configure your system and choose the 
    appropriate hosting solution (FWIW, small dedicated server are nowadays 
    dirt cheap).
    
    > Just maybe, that's something that Python could
    > learn from PHP.
    
    I don't think so.
    
    
    
    
    From andreww at datanet.ab.ca  Wed Jul 11 10:00:18 2007
    From: andreww at datanet.ab.ca (Andrew Warkentin)
    Date: Wed, 11 Jul 2007 07:00:18 -0700
    Subject: Best architecture for proxy?
    In-Reply-To: 
    References: <1184076639.815417.48390@g4g2000hsf.googlegroups.com>
    	<5ficu5F3cram2U4@mid.individual.net>
    	
    Message-ID: <1184162418.341166.160580@n60g2000hse.googlegroups.com>
    
    On Jul 10, 8:19 pm, Steve Holden  wrote:
    > Bjoern Schliessmann wrote:
    > > Andrew Warkentin wrote:
    >
    > >> I am going to write a general-purpose modular proxy in Python. It
    > >> will consist of a simple core and several modules for things like
    > >> filtering and caching. I am not sure whether it is better to use
    > >> multithreading, or to use an event-driven networking library like
    > >> Twisted or Medusa/ Asyncore. Which would be the better
    > >> architecture to use?
    >
    > > I'd definitely use an event-driven approach with Twisted.
    >
    > > Generally, multithreading is less performant than multiplexing. High
    > > performance servers mostly use a combination of both, though.
    >
    > Converselt I'd recommend Medusa - not necessarily because it's "better",
    > but becuase I know it better. There's also a nice general-purpose proxy
    > program (though I'd be surprised if Twisted didn't also have one).
    >
    >
    Would an event-driven proxy be able to handle multiple connections
    with large numbers of possibly CPU-bound filters? I use The
    Proxomitron (and would like to write my own proxy that can use the
    same filter sets, but follows the Unix philosophy) and some of the
    filters appear to be CPU-bound, because they cause The Proxomitron to
    hog the CPU (although that might just be a Proxomitron design flaw or
    something). Wouldn't CPU-bound filters only allow one connection to be
    filtered at a time? On the Medusa site, it said that an event-driven
    architecture only works for I/O-bound programs.
    
    
    
    From rcdailey at gmail.com  Fri Jul  6 15:38:58 2007
    From: rcdailey at gmail.com (Robert Dailey)
    Date: Fri, 06 Jul 2007 19:38:58 -0000
    Subject: ImportError: "No Module named xxx"
    In-Reply-To: <1183750316.740239.257010@m36g2000hse.googlegroups.com>
    References: <1183750316.740239.257010@m36g2000hse.googlegroups.com>
    Message-ID: <1183750738.308894.261750@c77g2000hse.googlegroups.com>
    
    Never mind, I found the problem. I was doing:
    
    python -m compile.py
    
    I really should have been doing:
    
    python compile.py
    
    
    The description of -m is confusing in the documentation, what does it
    really do?
    
    
    
    From see_website at mindprod.com.invalid  Sun Jul  1 15:10:34 2007
    From: see_website at mindprod.com.invalid (Roedy Green)
    Date: Sun, 01 Jul 2007 19:10:34 GMT
    Subject: Portable general timestamp format, not 2038-limited
    References: <1182544384.709759.235300@o11g2000prd.googlegroups.com>
    	
    	
    	<20070625133843.9e25d0ab.steveo@eircom.net>
    	<82b5l4-tvh.ln1@zoogz.gregorie.org>
    	<7xbqf3lc7i.fsf@ruckus.brouhaha.com>
    	
    	
    Message-ID: <3vuf835e6m0dccrhipolnebpuugpni75fp@4ax.com>
    
    On Sun, 01 Jul 2007 17:47:36 +0100, Martin Gregorie
     wrote, quoted or indirectly quoted
    someone who said :
    
    >GPS time is UTC time and I'd assume the same is true for Loran.
    
    not according to this site that has clocks running on all three.
    They are out slightly.
    
    
    http://www.leapsecond.com/java/gpsclock.htm
    --
    Roedy Green Canadian Mind Products
    The Java Glossary
    http://mindprod.com
    
    
    From anton.vredegoor at gmail.com  Thu Jul  5 15:39:07 2007
    From: anton.vredegoor at gmail.com (Anton Vredegoor)
    Date: Thu, 5 Jul 2007 21:39:07 +0200
    Subject: need help with converting c function to python function
    References: <1183656728.610086.178080@k79g2000hse.googlegroups.com>
    Message-ID: 
    
    In article <1183656728.610086.178080 at k79g2000hse.googlegroups.com>, 
    nephish at gmail.com says...
    
    > i have a c function from some modbus documentation that i need to
    > translate into python.
    > 
    > it looks like this:
    > 
    > 
    > unsigned short CRC16(puchMsg, usDataLen)
    > unsigned char *puchMsg ;
    > unsigned short usDataLen ;
    > {
    >    unsigned char uchCRCHi = 0xFF ;
    >    unsigned char uchCRCLo = 0xFF ;
    >    unsigned uIndex ;
    >    while (usDataLen--)
    >        {
    >        uIndex = uchCRCHi ^ *puchMsgg++ ;
    >        uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex} ;
    >        uchCRCLo = auchCRCLo[uIndex] ;
    >        }
    >    return (uchCRCHi << 8 | uchCRCLo) ;
    > }
    > 
    > some of it i can make out, but i can't seem to figgure out
    > this part ' auchCRCHi[uIndex};
    > it looks like a typo, because there is a closing } that does not match
    > the opening [.
    > 
    > 
    > here is what i have so far, but is not giving me the right values
    > 
    >  def crc16(data):
    >      crc_hi = 0xff
    >      crc_lo = 0xff
    >      for x in data:
    >          crc_index = crc_hi ^ x
    >          crc_hi = crc_lo ^ (crc_hi | crc_index)
    >          crc_lo = crc_lo | crc_index
    >      return (crc_hi << 8 | crc_lo)
    > 
    > whaddya think?
    
    Use lateral thinking. CRC usually means some standard data checking 
    algorithm. If you google for crc16 you will find various python 
    implementations. Off hand I would first try this one because he seems to 
    have been thinking about it:
    
    http://mail.python.org/pipermail/python-list/2005-September/342097.html
    
    But I don't really know what it is you are looking for, cyclic 
    redundancy check?
    
    http://en.wikipedia.org/wiki/Cyclic_redundancy_check
    
    A.
    
    
    From deets at nospam.web.de  Mon Jul  9 03:49:39 2007
    From: deets at nospam.web.de (Diez B. Roggisch)
    Date: Mon, 09 Jul 2007 09:49:39 +0200
    Subject: Decorating instance methods
    In-Reply-To: 
    References: 
    Message-ID: <5fe7klF39pd9dU1@mid.uni-berlin.de>
    
    Alexander Draeger schrieb:
    > Hello everybody,
    > 
    > I'm very interesting in using the decorator concept, but I can't
    > convert it in useful things. I have read many about decorators and
    > have seen a lot of examples, but I search a possibility, to decorate
    > methods of classes with reference to the instances. For example:
    > 
    > I have a class A:
    > 
    > class A(object):
    >    def __init__(self, name):
    >        self.name=name
    > 
    >    @logging
    >    def hello(self, name):
    >        print 'Hello World.'
    > 
    > 
    > 
    >  >>>a=A('Ernie')
    >  >>>b=A('Bert')
    >  >>>a.hello()
    > Entering a method. [Ernie]
    > Hello World.
    > 
    >  >>>b.hello()
    > Entering a method. [Bert]
    > Hello World.
    > 
    > 
    > How should I implement the function logging, when I want to use the
    > variable self.name for the logging message?
    
    
    def logging(m):
         def _w(self, *args, **kwargs):
             print "name:", self.name
             returm m(self, *args, **kwargs)
         return _w
    
    
    Diez
    
    
    From jjl at pobox.com  Mon Jul 16 15:17:40 2007
    From: jjl at pobox.com (John J Lee)
    Date: Mon, 16 Jul 2007 20:17:40 +0100 (BST)
    Subject: urllib to cache 301 redirections?
    In-Reply-To: <20070716190319.GA7184@gmail.com>
    References: 
    	<87wsxds6sq.fsf@pobox.com> <20070716190319.GA7184@gmail.com>
    Message-ID: 
    
    On Tue, 17 Jul 2007, O.R.Senthil Kumaran wrote:
    [...]
    > I spent a little time thinking about a solution and figured out that the
    > following changes to HTTPRedirectHandler, might be helpful in implementing
    > this.
    [...]
    
    Did you post it on the Python SF patch tracker?
    
    If not, please do, and point us at it.  I'll comment there.
    
    
    John
    
    
    
    From rcdailey at gmail.com  Mon Jul 16 13:40:14 2007
    From: rcdailey at gmail.com (Robert Dailey)
    Date: Mon, 16 Jul 2007 17:40:14 -0000
    Subject: The ** operator ambiguous?
    Message-ID: <1184607614.904143.219330@w3g2000hsg.googlegroups.com>
    
    I noticed that the ** operator is used as the power operator, however
    I've seen it used when passing variables into a function. For example,
    I was researching a way to combine dictionaries. I found that if you
    do this:
    
    a = {"t1":"a", "t2":"b"}
    b = {"t3":"c"}
    dict( a, **b )
    
    
    This combines the two dictionaries. However, I have no idea what the
    ** operator is here. I know that when you specify ** as a parameter in
    a function definition, it represents a dictionary of parameters passed
    in. However, in this example it is NOT being used in a function
    definition. It is being used when passing variables into a function.
    Can someone explain what this means? I looked in the documentation but
    I couldn't find anything.
    
    
    
    From wildemar at freakmail.de  Thu Jul  5 18:00:40 2007
    From: wildemar at freakmail.de (Wildemar Wildenburger)
    Date: Fri, 06 Jul 2007 00:00:40 +0200
    Subject: list.append not working?
    In-Reply-To: 
    References: <1183651138.209079.37620@q75g2000hsh.googlegroups.com>
    	
    Message-ID: <468D6A08.9080209@freakmail.de>
    
    Abhishek Jain wrote:
    > with every iteration your previous values are overwritten ('md' is a 
    > dictionary) so thats why your are observing this ouput..
    >
    > check  if the following patch solves your problem
    >
    > for entity in temp:
    >             md['module']= entity.addr.get('module')
    >             md['id']=entity.addr.get('id')
    >             md['type']=entity.addr.get('type')
    >             #print md
    >             mbusentities.append(md)
    >             md = {}
    >             #print mbusentities
    >
    >
    > Regards
    > Abhi
    This will work, but may I suggest putting the md = {} line at the 
    *beginning* of the loop?
    I find seeing it at the end HIGHLY confusing. Declaring it in the 
    beginning makes sense, because you declare/initialize, then use it. But 
    using and *then* initializing it for the next iteration is kind of 
    quirky, because it breaks the logical encapsulation I would like to see 
    in *one* loop iteration.
    
    /W
    
    
    From nick at craig-wood.com  Thu Jul 12 14:30:04 2007
    From: nick at craig-wood.com (Nick Craig-Wood)
    Date: Thu, 12 Jul 2007 13:30:04 -0500
    Subject: os.wait() losing child?
    References:  
    	<4694903B.8000105@cosc.canterbury.ac.nz>
    	
    	
    	
    	
    	<87fy3tg5zn.fsf@mulj.homelinux.net>
    Message-ID: 
    
    Hrvoje Niksic  wrote:
    >  Nick Craig-Wood  writes:
    > 
    > >>  I think your polling way works; it seems there no other way around this 
    > >>  problem other than polling or extending Popen class.
    > >
    > > I think polling is probably the right way of doing it...
    > 
    >  It requires the program to wake up every 0.1s to poll for freshly
    >  exited subprocesses.  That doesn't consume excess CPU cycles, but it
    >  does prevent the kernel from swapping it out when there is nothing to
    >  do.  Sleeping in os.wait allows the operating system to know exactly
    >  what the process is waiting for, and to move it out of the way until
    >  those conditions are met.  (Pedants would also notice that polling
    >  introduces on average 0.1/2 seconds delay between the subprocess dying
    >  and the parent reaping it.)
    
    Sure!
    
    You could get rid of this by sleeping until a SIGCHLD arrived maybe.
    
    >  In general, a program that waits for something should do so in a
    >  single call to the OS.  OP's usage of os.wait was exactly correct.
    
    Disagree for the reason below.
    
    > > Internally subprocess uses os.waitpid(pid) just waiting for its own
    > > specific pids.  IMHO this is the right way of doing it other than
    > > os.wait() which waits for any pids.  os.wait() can reap children
    > > that you weren't expecting (say some library uses os.system())...
    > 
    >  system calls waitpid immediately after the fork.
    
    os.system probably wasn't the best example, but you take my point I
    think!
    
    >  This can still be a problem for applications that call wait in a
    >  dedicated thread, but the program can always ignore the processes
    >  it doesn't know anything about.
    
    Ignoring them isn't good enough because it means that the bit of code
    which was waiting for that process to die with os.getpid() will never
    get called, causing a deadlock in that bit of code.
    
    What is really required is a select() like interface to wait which
    takes more than one pid.  I don't think there is such a thing though,
    so polling is your next best option.
    
    -- 
    Nick Craig-Wood  -- http://www.craig-wood.com/nick
    
    
    From bkjones at gmail.com  Wed Jul 25 14:55:28 2007
    From: bkjones at gmail.com (Brian Jones)
    Date: Wed, 25 Jul 2007 14:55:28 -0400
    Subject: Why PHP is so much more popular for web-development
    In-Reply-To: <46A7942D.4030904@holdenweb.com>
    References: <1185385374.866372.198520@x35g2000prf.googlegroups.com>
    	<46A7942D.4030904@holdenweb.com>
    Message-ID: <46A79CA0.8020101@gmail.com>
    
    
    
    Steve Holden wrote:
    > walterbyrd wrote:
    >   
    >> "Once you start down the Dark path, forever will it dominate your
    >> desiny. Consume you, it will."
    >> - Yoda
    >>
    >> I'm fairly new to web-development, and I'm trying out different
    >> technologies. Some people wonder why PHP is so popular, when the
    >> language is flawed in so many ways. To me, it's obvious: it's because
    >> it's much easier to get started with PHP, and once somebody gets
    >> started with a particular language, that person is likely to stay with
    >> that language.
    >>
    >> Before you can even get started with Python web-development, you have
    >> to understand this entire alphabit soup of: CGI, FASTCGI, MOD_PYTHON,
    >> FLUP, WSGI, PASTE, etc. For me, configuring fastcgi has been the most
    >> difficult part of getting django to work. PHP developers don't have to
    >> bother with anything like that. With PHP, you just throw some code in
    >> the middle of your html file.
    >>     
    I'm primarily a sysadmin, and I provide web hosting-like services to a 
    community of developers who all want to do their own thing. An obvious, 
    clean way to do this has, so far, eluded me. Of course I could shove a 
    framework down the throats of my users, but if given the choice between 
    picking up a language, or picking up a language, and an accompanying 
    framework, which may or may not meet their needs, I think they'd pick 
    the former. In fact, in 6 years, we've never had anyone say "boy I wish 
    our web servers supported python". They've all been happily using PHP.
    
    I'm in a relatively small shop. But think about an ISP. If you need to 
    support thousands of users who all have their own agendas, how exactly 
    do you support that with Python? This is not a rhetorical question - I'd 
    really like to know :)
    
    In short, I don't think it's the language, but deploying it in a web 
    context that makes it less popular. If it were simpler, more ISPs might 
    do it, more users would find what they need with Python instead of PHP, 
    and it would become a more popular web language, IMHO.
    
    > The latter behavior is typical of programmers. The former is typical of 
    > typical users. There are many people producing web sites who I wouldn't 
    > let within yards of any of my code. but it's some kind of tribute to PHP 
    > that it manages to satisfy so many of them. This doesn't mean that 
    > grafting PHP features into Python mindlessly will improve the language.
    >   
    I don't think anyone is saying the *language* itself needs improving. I 
    think there needs to be a cleaner, simpler, more practical way to deploy 
    Python as a generic web language instead of being forced to deploy it in 
    the context of some other framework. No ISP wants to impose the implied 
    limitations on their users, and the users would prefer not to have to 
    learn a framework.
    
    Also, I just want to point out that in my discussions with other people 
    who consider themselves primarily Python coders, there are plenty of 
    them who still turn to PHP for web development. I got into Python for 
    systems programming (sysadmin tasks and network programming). If I need 
    to do web-based work, I'm likely to still use PHP because I have no idea 
    how to deploy/maintain/support Python on the systems end of the 
    equation. I'd love to be cured of that notion.
    
    brian.
    > The Python approach is a scalpel, which can easily cut your fingers off. 
    > The PHP approach is a shovel, which will do for many everyday tasks.
    >
    > regards
    >   Steve
    >   
    
    -- 
    Brian K. Jones
    Python Magazine  http://www.pythonmagazine.com
    My Blog          http://m0j0.wordpress.com 
    jonesy at pythonmagazine dot com
    
    
    
    From orsenthil at users.sourceforge.net  Tue Jul  3 15:26:18 2007
    From: orsenthil at users.sourceforge.net (O.R.Senthil Kumaran)
    Date: Wed, 4 Jul 2007 00:56:18 +0530
    Subject: mysteries of urllib/urllib2
    In-Reply-To: <1183475672.295922.47600@e9g2000prf.googlegroups.com>
    References: <1183470239.153444.244700@j4g2000prf.googlegroups.com>
    	<1183472702.932557.108600@n2g2000hse.googlegroups.com>
    	<1183475672.295922.47600@e9g2000prf.googlegroups.com>
    Message-ID: <20070703192618.GB3789@gmail.com>
    
    * Adrian Smith  [2007-07-03 08:14:32]:
    
    > some access. Apparently there's a way to change the user-agent string
    > by subclassing urllib's URLopener class, but that's beyond my comfort
    > zone at present.
    
    Read the urllib2 how-to located at ActiveState Documentation pages.
    That gives the concise snippets as how you will set the USER-AGENT string.
    
    import urllib
    import urllib2
    
    url = 'http://www.someserver.com/cgi-bin/register.cgi'
    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    values = {'name' : 'Michael Foord',
              'location' : 'Northampton',
              'language' : 'Python' }
    headers = { 'User-Agent' : user_agent }
    
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data, headers)
    response = urllib2.urlopen(req)
    the_page = response.read()
    
    
    -- 
    O.R.Senthil Kumaran
    http://uthcode.sarovar.org
    
    
    From ajsavige at yahoo.com.au  Sun Jul 29 02:36:49 2007
    From: ajsavige at yahoo.com.au (Andrew Savige)
    Date: Sun, 29 Jul 2007 16:36:49 +1000 (EST)
    Subject: Split a string based on change of character
    In-Reply-To: <1185687096.830640.319110@z28g2000prd.googlegroups.com>
    Message-ID: <753831.76994.qm@web56410.mail.re3.yahoo.com>
    
    --- "attn.steven.kuo at gmail.com"  wrote:
    > Using itertools:
    > 
    > import itertools
    > 
    > s = 'ABBBCC'
    > print [''.join(grp) for key, grp in itertools.groupby(s)]
    
    Nice.
    
    > Using re:
    > 
    > import re
    > 
    > pat = re.compile(r'((\w)\2*)')
    > print [t[0] for t in re.findall(pat, s)]
    
    Also nice. Especially nice that it only returns the outer parens. :-)
    
    > By the way, your pattern seems to work in perl:
    > 
    > $ perl -le '$, = " "; print split(/(?<=(.))(?!\1)/, "ABBBCC");'
    > A A BBB B CC C
    > 
    > Was that the type of regular expressions you were expecting?
    
    Yes. Here's a simpler example without any backreferences:
    
    s = re.split(r'(?<=\d)(?=\D)', '1B2D3')
    
    That works in Perl but not in Python.
    Is it that "chaining" assertions together like this is not supported in Python
    re?
    Or is that the case only in the split function?
    
    Thanks,
    /-\
    
    
    
          ____________________________________________________________________________________
    Yahoo!7 Mail has just got even bigger and better with unlimited storage on all webmail accounts. 
    http://au.docs.yahoo.com/mail/unlimitedstorage.html
    
    
    From fukazawa at gmail.com  Mon Jul  2 06:22:32 2007
    From: fukazawa at gmail.com (Andy)
    Date: Mon, 02 Jul 2007 10:22:32 -0000
    Subject: String formatting for complex writing systems
    In-Reply-To: <1182939287.897840.60490@m37g2000prh.googlegroups.com>
    References: <1182928852.730131.323210@a26g2000pre.googlegroups.com>
    	<1182939000.080429.136180@x35g2000prf.googlegroups.com>
    	<1182939287.897840.60490@m37g2000prh.googlegroups.com>
    Message-ID: <1183371752.613942.192970@d30g2000prg.googlegroups.com>
    
    Thanks guys!
    
    I've used the HTML and the unicodedata suggestions, each on a
    different report.  These worked nicely!
    
    Andy
    
    
    
    From nagle at animats.com  Mon Jul 16 15:34:00 2007
    From: nagle at animats.com (John Nagle)
    Date: Mon, 16 Jul 2007 12:34:00 -0700
    Subject: urllib to cache 301 redirections?
    In-Reply-To: 
    References: 	<87wsxds6sq.fsf@pobox.com>
    	
    Message-ID: 
    
    O.R.Senthil Kumaran wrote:
    > Thank you for the reply, Mr. John and I apologize for a very late response
    > from my end.
    > 
    > * John J. Lee  [2007-07-06 18:53:09]:
    > 
    > 
    >>"O.R.Senthil Kumaran"  writes:
    >>
    >>
    >>>Hi,
    >>>There is an Open Tracker item against urllib2 library python.org/sf/735515
    >>
    >>>I am not completely getting what "cache - redirection" implies and what should
    >>>be done with the urllib2 module. Any pointers?
    >>
    >>When a 301 redirect occurs after a request for URL U, via
    >>urllib2.urlopen(U), urllib2 should remember the result of that
    >>redirection, viz a second URL, V.  Then, when another
    >>urllib2.urlopen(U) takes place, urllib2 should send an HTTP request
    >>for V, not U.  urllib2 does not currently do this.  (Obviously the
    >>cache -- that is, the dictionary or whatever that stores the mapping
    >>from URLs U to V -- should not be maintained by function urlopen
    >>itself.  Perhaps it should live on the redirect handler.)
    >>
    > 
    > 
    > I spent a little time thinking about a solution and figured out that the
    > following changes to HTTPRedirectHandler, might be helpful in implementing
    > this.
    > 
    > Class HTTPRedirectHandler(BaseHandler):
    >     # ... omitted ...
    >     # Initialize a dictionary to hold cache.
    > 
    >     def __init__(self):
    >         self.cache = {}
    > 
    > 
    >     # Handles 301 errors separately in a different function which maintains a
    >     # maintains cache.
    > 
    >     def http_error_301(self, req, fp, code, msg, headers):
    > 
    >         if req in self.cache:
    >             # Look for loop, if a particular url appears in both key and value
    >             # then there is loop and return HTTPError
    >             if len(set(self.cache.keys()) & set(self.cache.values())) > 0:
    >                 raise HTTPError(req.get_full_url(), code, self.inf_msg + msg +
    >                         headers, fp)
    >             return self.cache[req]
    > 
    >         self.cache[req] = self.http_error_302(req,fp,code,msg, headers)
    >         return self.cache[req]
    > 
    > 
    > John, let me know your comments on this approach.
    > I have not tested this code in real scenario yet with a 301 redirect.
    > If its okay, I shall test it and submit a patch for the tracker item.
    
        That assumes you're reusing the same object to reopen another URL.
    
        Is this thread-safe?
    
        That's also an inefficient way to test for an empty dictionary.
    
    					John Nagle
    
    
    From doug at alum.mit.edu  Tue Jul 10 13:47:38 2007
    From: doug at alum.mit.edu (Douglas Alan)
    Date: Tue, 10 Jul 2007 13:47:38 -0400
    Subject: The best platform and editor for Python
    References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com>
    	<1183380558.135204.83790@e16g2000pri.googlegroups.com>
    	<1183398645.511107.258700@n2g2000hse.googlegroups.com>
    	
    	<1183630730.251890.238900@m36g2000hse.googlegroups.com>
    	<1183646799.400176.144570@k79g2000hse.googlegroups.com>
    	<1183655933.475488.157270@m36g2000hse.googlegroups.com>
    	<1183670009.035673.256680@w5g2000hsg.googlegroups.com>
    	<1i0so61.10qnto712c7dhpN%aleax@mac.com>
    Message-ID: 
    
    aleax at mac.com (Alex Martelli) writes:
    
    > Kay Schluehr  wrote:
    
    >> half of the community is happy with Emacs and the other half wants to
    >> program in a VS-like environment, neither consensus nor progress has
    
    > Calling all vi/vim users (and we'll heartily appreciate the support
    > of TextMate fans, BBEdit ones, etc, etc) -- we're at risk being
    > defined out of existence, since we're neither happy with Emacs
    
    That's because the Emacs users are the only ones who matter.
    
    |>oug
    
    
    From erik at myemma.com  Mon Jul 16 01:18:35 2007
    From: erik at myemma.com (Erik Jones)
    Date: Mon, 16 Jul 2007 00:18:35 -0500
    Subject: How to determine which method was used in an inheritance
    	heirarchy?
    In-Reply-To: <1184559788.712146.238190@q75g2000hsh.googlegroups.com>
    References: 
    	<1184559788.712146.238190@q75g2000hsh.googlegroups.com>
    Message-ID: <4AEC6A0D-2FE7-4C7A-9A08-2AF92110550C@myemma.com>
    
    
    On Jul 15, 2007, at 11:23 PM, Michele Simionato wrote:
    
    > On Jul 16, 5:51 am, Erik Jones  wrote:
    >> Say you're given a call event frame for a method call.  How can you
    >> tell if the code being executed came from a super class of the object
    >> or class the method was called on?
    >>
    >> Erik Jones
    >
    > You look if the method was defined in self.__class__.__dict__.
    >
    >        Michele Simionato
    
    That doesn't seem to cover calling super class __init__ methods.
    
    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 michele.simionato at gmail.com  Thu Jul  5 10:01:52 2007
    From: michele.simionato at gmail.com (Michele Simionato)
    Date: Thu, 05 Jul 2007 14:01:52 -0000
    Subject: MethodType/FunctionType and decorators
    In-Reply-To: <1183641471.753457.269030@m36g2000hse.googlegroups.com>
    References: <1183589529.198694.109440@m36g2000hse.googlegroups.com>
    	<1183591053.434640.119550@o61g2000hsh.googlegroups.com>
    	<1i0qoq9.u1fu2g63fkmxN%aleax@mac.com>
    	<1183623479.913816.301230@g4g2000hsf.googlegroups.com>
    	<1183626989.983470.94950@o61g2000hsh.googlegroups.com>
    	
    	<1183641471.753457.269030@m36g2000hse.googlegroups.com>
    Message-ID: <1183644112.049339.159460@c77g2000hse.googlegroups.com>
    
    On Jul 5, 3:17 pm, Alex Popescu 
    wrote:
    > The true story is that
    > while working on Groovy (I am a committer on this dynlang meant to run
    > on the Java VM:http://groovy.codehaus.org) and reading some Python
    > materials, my interest grew exponentially. And now I have decided to
    > see how other succesfull java project I have co-created (TestNG:http://testng.org) would look like in Python (this giving me the
    > opportunity to explore Python in more depth).
    >
    
    If you are interested in testing, you should give a look at 1)
    doctest; 2) py.test
    (Python unittest framework should be old hat to you and not worth
    looking at).
    
         Michele Simionato
    
    
    
    From bruno.42.desthuilliers at wtf.websiteburo.oops.com  Tue Jul 31 08:46:00 2007
    From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers)
    Date: Tue, 31 Jul 2007 14:46:00 +0200
    Subject: Why no maintained wrapper to Win32?
    In-Reply-To: <5h1qa3luht8q30vaad0fbn4cpfsddgmt17@4ax.com>
    References: 
    	<46ab694e$0$17577$9b622d9e@news.freenet.de>
    	<59kna3p8r0cu2gk6hs5lbig8cjj8klatju@4ax.com>
    	<46ac1a43$0$7536$9b622d9e@news.freenet.de>
    	<5h1qa3luht8q30vaad0fbn4cpfsddgmt17@4ax.com>
    Message-ID: <46af2f00$0$9218$426a74cc@news.free.fr>
    
    Gilles Ganault a ?crit :
    > On Sun, 29 Jul 2007 06:40:35 +0200, "Martin v. L?wis"
    >  wrote:
    >> Why do you say that the Win32 API lacks documentation? I find the
    >> documentation at msdn.microsoft.com to be quite useful.
    > 
    > No, I meant documentation on how to write Win32 apps using PyWin.
    > 
    >> Yes, there haven't been many changes to Win32 in recent years (there
    >> haven't been many system releases in the first place). Most additions
    >> did not concern GUI programming, which is what you were after, and
    >> even those that are recent additions are rather rarely needed, so
    >> you likely won't miss them.
    > 
    > Makes sense. Do  you know of good places to hang around when looking
    > for information on writing Win32-based GUI apps in Pythons
    
    For the Win32 part, there's a dedicated newsgroup in the comp.* 
    hierarchy (sorry, can't remember the exact name, but you shouldn't have 
    problems finding it).
    
    For the Python part, I'd say you're at the right place.
    
    
    From vodela.sai at gmail.com  Wed Jul 18 20:25:53 2007
    From: vodela.sai at gmail.com (Rohan)
    Date: Thu, 19 Jul 2007 00:25:53 -0000
    Subject: Issue with CSV
    Message-ID: <1184804753.810201.72150@x40g2000prg.googlegroups.com>
    
    Hello,
    I'm working on a script which collects some data and puts into a csv
    file which could be exported to excel.
    so far so good, I'm able to do what I described.
    When I run the script for the second time after a certain period of
    time the results should appear next to the results of the last run,
    I'm unable to make a new column when the script is run after the first
    time.
    Ideally I would like to have an output which looks like this.
    1/20       1/27
    we.py    we.py
    gh.py    gj.py   <- Indicating tht the file has changed
    fg.py    fg.py
    
    Please help me out.
    Thanks
    
    
    
    From vania.smirk at gmail.com  Tue Jul  3 23:46:01 2007
    From: vania.smirk at gmail.com (VSmirk)
    Date: Wed, 04 Jul 2007 03:46:01 -0000
    Subject: Python compilation ??
    In-Reply-To: <5f0fo7F39tfbtU1@mid.individual.net>
    References: 
    	
    	
    	<5f0fo7F39tfbtU1@mid.individual.net>
    Message-ID: <1183520761.720839.174330@c77g2000hse.googlegroups.com>
    
    On Jul 3, 10:42 pm, Frank Swarbrick  wrote:
    > John Nagle wrote:
    > > Evan Klitzke wrote:
    > >> On 7/2/07, Cathy Murphy  wrote:
    >
    > >>> Is python a compiler language or interpreted language. If it is
    > >>> interpreter
    > >>> , then why do we have to compile it?
    >
    > >   Iron Python compiles to Microsoft's byte code as used by their
    > > ".NET" common language runtime.  This is then compiled to machine
    > > code by a just-in-time compiler.
    >
    > Does Iron Python compile to free-standing executables, or is there an
    > Iron Python interpreter that is always necessary?
    >
    > Frank
    
    Here's what I understand:
    
    As with Java, which compiles to ByteCode which only runs with the Java
    Virtual Machine, IronPython compiles to MSIL code, which will run on
    any machine which has the .Net framework installed.
    
    However, MS set up .Net so it appears in the file system as a .exe,
    so, IronPython should be in experience no different from any other
    application.  The trick is to handle whether or not the user has the
    correct (or any) .Net framework, which is easily solved by adding an
    installer project which will install required files.
    
    This answer is not based on my personal experience with IronPython,
    which I haven't personally played with much yet, but is based on my
    day-job experience with C# and VB.Net, both of which compile to MSIL
    code and work as I describe, and with Python after hours and my
    knowledge of how Jython and IronPython work in theory.
    
    I would be very interested in learning if IronPython is not
    implemented as I describe.
    
    VSmirk
    
    
    
    From grante at visi.com  Mon Jul  9 23:26:27 2007
    From: grante at visi.com (Grant Edwards)
    Date: Tue, 10 Jul 2007 03:26:27 -0000
    Subject: Should I use Python for these programs?
    References: 
    Message-ID: <1395v33mpci3p5c@corp.supernews.com>
    
    On 2007-07-10, CC  wrote:
    
    > I wish to accomplish a few PC programming tasks, and am
    > considering to learn Python:
    >
    > 1. Develop a simple GUI program to run on Linux and Windows
    >    which can send parameters and small blocks of data to an
    >    embedded microcontroller device via RS-232 or USB.  Also
    >    display simple data (probably single numbers) sent from the
    >    device.
    >
    >    Note, if it is USB, then the client will be implemented by
    >    me using FTDI chips that appear to the PC as a serial port.
    
    I do a lot of that sort of thing using Python.  I'd probably
    recommend using pyserial and wxWidgets.  Both are
    cross-platform.
    
    http://pyserial.sourceforge.net/
    http://www.wxpython.org/
    
    In any case, both "normal" PC serial ports and USB-serial ports
    looks the same to a Linux app.  Windows support for stuff like
    that wasn't so good last time I tried, but it's supposed to work.
    
    > 2. Develop a simple vector drawing program that will allow one
    >    to freehand draw a sketch composed of a few lines, or
    >    perhaps render text in a vector form.  Then sample the
    >    lines with a certain (user configurable) spacing, and use
    >    the mouse to move the sample points along the lines to
    >    tweak the sample locations if desired.  Then output a file
    >    of X,Y coordinates for the samples.
    >
    >    What is this crazy thing for?  It's to develop simple
    >    lasershow vector frames.  I am also designing a DSP-based
    >    lasershow output device, so the same capabilities of
    >    delivering a data payload over serial/USB to a target
    >    device will be needed here as well.
    
    Most of the graphics I do with Python is with Gnuplot (not
    really appropriate for what you want to do.
    wxWidgets/Floatcanvas might be worth looking into.
    
    > I would prefer to be able to write a program that is cross-platform 
    > between Linux and Windows.  I realize this might be especially 
    > problematic with the serial comms.
    
    Not at all.  Cross-platform serial stuff is easy.
    
    > I am also confused by the plethora of Python GUI extensions,
    > though Tkinter seems like a likely candidate.  I am uncertain
    > if I will have difficulty learning how to use this if I don't
    > know Tcl/Tk.
    
    
    Tk's canvas widget is pretty powerful, and you don't need to
    know Tcl -- it's all hidden behind a veneer of Python.
    
    > Do you think Python is the right language for these projects?
    
    It's what I use for stuff like that.
    
    -- 
    Grant Edwards                   grante             Yow!  MERYL STREEP is my
                                      at               obstetrician!
                                   visi.com            
    
    
    From iladijas at gmail.com  Tue Jul 10 14:32:05 2007
    From: iladijas at gmail.com (fynali)
    Date: Tue, 10 Jul 2007 11:32:05 -0700
    Subject: win32com ppt embedded object
    In-Reply-To: 
    References: 
    Message-ID: <1184092325.482807.233490@22g2000hsm.googlegroups.com>
    
    On Jul 10, 8:40 pm, Lance Hoffmeyer  wrote:
    > Hey all,
    >
    > I am trying to create some python code to edit embedded ppt slides and need some help.
    >
    > import win32com.client
    > from win32com.client import constants
    > import re
    > import codecs,win32com.client
    > import time
    > import datetime
    > import win32com.client.dynamic
    > ######################################################
    > ############ VARIOUS VARIABLES TO SET ################
    > path = "C:\temp/"
    > ######################################################
    > ######################################################
    >
    > PPT=win32com.client.Dispatch("PowerPoint.Application")
    > WB=PPT.Presentations.Open(path + "File.ppt")
    > PPT.Visible=1
    > PPTSLIDE= 29
    >
    > for Z in WB.Slides(29).Shapes:
    >         if (Z.Type== 7):
    >                 ZZ=Z.OLEFormat.Object
    >                 WSHEET = ZZ.Worksheets(1)
    >                 WSHEET.Range("A1").Value = .50
    >                 WSHEET.Range("A1").NumberFormat="0%"
    >
    > Gives error:
    >
    > Traceback (most recent call last):
    >   File "P:\Burke\TRACKERS\Ortho-McNeil\04 2007, 04-10 WAVE 4\Automation\Document1.py", line 23, in ?
    >     WSHEET = ZZ.Worksheets(1)
    >   File "C:\Program Files\Python\lib\site-packages\win32com\client\dynamic.py", line 489, in __getattr__
    >     raise AttributeError, "%s.%s" % (self._username_, attr)
    > AttributeError: .Worksheets
    >
    > Tool completed with exit code 1
    >
    > Why is ZZ unknown and how to I correct this?
    >
    > Thanks in advance,
    >
    > Lance
    
    
    """
    How do I know which methods and properties are available?
    Good question. This is hard! You need to use the documentation with
    the products, or possibly a COM browser. Note however that COM
    browsers typically rely on these objects registering themselves in
    certain ways, and many objects to not do this. You are just expected
    to know.
    
    The Python COM browser
    PythonCOM comes with a basic COM browser that may show you the
    information you need. Note that this package requires Pythonwin (ie,
    the MFC GUI environment) to be installed for this to work.
    
    There are far better COM browsers available - I tend to use the one
    that comes with MSVC, or this one!
    
    To run the browser, simply select it from the Pythonwin Tools menu, or
    double-click on the file win32com\client\combrowse.py
    
    """
    
    --
    s|a fynali
    
    
    
    From max at alcyone.com  Sun Jul  1 01:55:03 2007
    From: max at alcyone.com (Erik Max Francis)
    Date: Sat, 30 Jun 2007 22:55:03 -0700
    Subject: unicode
    In-Reply-To: <1183267580.178435.265640@o61g2000hsh.googlegroups.com>
    References: <1183267580.178435.265640@o61g2000hsh.googlegroups.com>
    Message-ID: 
    
    7stud wrote:
    
    > Based on this example and the error:
    > 
    > -----
    > u_str = u"abc\u9999"
    > print u_str
    > 
    > UnicodeEncodeError: 'ascii' codec can't encode character u'\u9999' in
    > position 3: ordinal not in range(128)
    > ------
    > 
    > it looks like when I try to display the string, the ascii decoder
    > parses each character in the string and fails when it can't convert a
    > numerical code that is higher than 127 to a character, i.e. the
    > character \u9999.
    
    If you try to print a Unicode string, then Python will attempt to first 
    encode it using the default encoding for that file.  Here, it's apparent 
    the default encoding is 'ascii', so it attempts to encode it into ASCII, 
    which it can't do, hence the exception.  The error is no different from 
    this:
    
     >>> u_str = u'abc\u9999'
     >>> u_str.encode('ascii')
    Traceback (most recent call last):
       File "", line 1, in ?
    UnicodeEncodeError: 'ascii' codec can't encode character u'\u9999' in 
    position 3: ordinal not in range(128)
    
    > In the following example, I use encode() to convert a unicode string
    > to a regular string:
    > 
    > -----
    > u_str = u"abc\u9999"
    > reg_str = u_str.encode("utf-8")
    > print repr(reg_str)
    > -----
    > 
    > and the output is:
    > 
    > 'abc\xe9\xa6\x99'
    > 
    > 1) Why aren't the characters 'a', 'b', and 'c' in hex notation?  It
    > looks like python must be using the ascii decoder to parse the
    > characters in the string again--with the result being python converts
    > only the 1 byte numerical codes to characters. 2) Why didn't that
    > cause an error like above for the 3 byte character?
    
    Since you've already encoded the Unicode object as a normal string, 
    Python isn't trying to do any implicit encoding.  As for why 'abc' 
    appears in plain text, that's just the way repr works:
    
     >>> s = 'a'
     >>> print repr(s)
    'a'
     >>> t = '\x99'
     >>> print repr(t)
    '\x99'
    
    repr is attempting to show the string in the most readable fashion.  If 
    the character is printable, then it just shows it as itself.  If it's 
    unprintable, then it shows it in hex string escape notation.
    
    > Then if I try this:
    > 
    > ---
    > u_str = u"abc\u9999"
    > reg_str = u_str.encode("utf-8")
    > print reg_str
    > ---
    > 
    > I get the output:
    > 
    > abc
    > 
    > Here it looks like python isn't using the ascii decoder anymore.  2)
    > What determines which decoder python uses?
    
    Again, that's because by already encoding it as a string, Python isn't 
    doing any implicit encoding.  So it prints the raw string, which happens 
    to be UTF-8, and which your terminal obviously supports, so you see the 
    proper character.
    
    -- 
    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
       Let us not seek the Republican answer or the Democratic answer but
        the right answer. -- John F. Kennedy
    
    
    From paddy3118 at googlemail.com  Thu Jul  5 01:47:53 2007
    From: paddy3118 at googlemail.com (Paddy)
    Date: Thu, 05 Jul 2007 05:47:53 -0000
    Subject: need a variation algorithm for Lists in Dictionaries
    In-Reply-To: 
    References: 
    Message-ID: <1183614473.811659.109060@m36g2000hse.googlegroups.com>
    
    On Jul 5, 3:58 am, "Marc Stuart"  wrote:
    > Hi, I am trying to create a function, where I pass a dictionary with a
    > lits of strings, and try to return a
    > a list of strings, for all variations, any ideas ?
    > Thanks
    >
    > def getAllVariants(someDict):
    >         keys = someDict.keys()
    >         for x in keys:
    >                         print len(someDict[x])
    >
    > x = {1:['a','b'],2:['b','c'],3:['d','e','f','g']}
    > getAllVariants(x)
    >
    > """ I need to get a list of strings that render all possible variants,
    > this is what my output should be based on the
    > x dictionary:
    > abd
    > abe
    > abf
    > acd
    > ace
    > acf
    > acg
    > bbd
    > bbe
    > bbf
    > bcd
    > bce
    > bcf
    > bcg
    >
    > """
    
    Here's two possibilities:
      http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502199
      http://jace.seacrow.com/archive/2007/02/15/generating-combinations-in-python
    
    - Paddy.
    
    
    
    From stesch at no-spoon.de  Sat Jul 28 12:12:32 2007
    From: stesch at no-spoon.de (Stefan Scholl)
    Date: Sat, 28 Jul 2007 18:12:32 +0200
    Subject: Any reason why cStringIO in 2.5 behaves different from 2.4?
    References: <0T49cam5I2g6Nv8%stesch@parsec.no-spoon.de>
    	<46A86C70.8040707@web.de>
    	<0T49cms0I356Nv8%stesch@parsec.no-spoon.de> <46A8919B.10906@web.de>
    	<0T49cr71I3edNv8%stesch@parsec.no-spoon.de>
    	<46A8AA57.4010802@web.de>
    	<0T49dll7I4ilNv8%stesch@parsec.no-spoon.de>
    	
    	<0T49ei9cI6hhNv8%stesch@parsec.no-spoon.de>
    	
    Message-ID: <0T49iehiIt1hNv8%stesch@parsec.no-spoon.de>
    
    Chris Mellon  wrote:
    > On 7/26/07, Stefan Scholl  wrote:
    >> Chris Mellon  wrote:
    >> > XML is not a string. It's a specific type of bytestream. If you want
    >> > to work with XML, then generate well-formed XML in the correct
    >> > encoding. There's no reason you should have an XML document (as
    >> > opposed to values extracted from that document) in unicode objects at
    >> > all.
    >>
    >> The affected method in xml.sax is called parseString()
    > 
    > The imprecision of the english language has caused greater problems
    > than this. Since you've now had everything clarified for you, and the
    > imprecision is resolved, I'm sure that this won't be a problem again.
    
    
    Right. I now know that xml.sax's parseString() has undocumented
    implementation dependent behavior. That there are libraries (not
    included with Python) which can parse Unicode strings. And that
    the reason to change cStringIO's behavior is acceptable.
    
    But the style of the answers makes me wonder if I should report
    the bug in xml.sax (or its documentation) or just ignore it.
    
    
    -- 
    Web (en): http://www.no-spoon.de/ -*- Web (de): http://www.frell.de/
    
    
    From manasd at gmail.com  Sat Jul  7 18:28:43 2007
    From: manasd at gmail.com (MD)
    Date: Sat, 07 Jul 2007 15:28:43 -0700
    Subject: Tests for Python Database API
    Message-ID: <1183847323.892963.32310@57g2000hsv.googlegroups.com>
    
    Hi,
    
       Are there any tests that will help me ensure that my Python
    database driver conforms to the Database API v2.0 specification?
    
    Thanks in advance.
    
    Regards,
    -MD
    
    
    
    From tleeuwenburg at gmail.com  Wed Jul  4 00:10:37 2007
    From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com)
    Date: Wed, 04 Jul 2007 04:10:37 -0000
    Subject: ActivePython
    In-Reply-To: <1i0p0l1.152ee0mcffr6aN%aleax@mac.com>
    References: <5f0g54F396io7U1@mid.individual.net>
    	<1i0p0l1.152ee0mcffr6aN%aleax@mac.com>
    Message-ID: <1183522237.693582.210770@i38g2000prf.googlegroups.com>
    
    On Jul 4, 2:03 pm, a... at mac.com (Alex Martelli) wrote:
    > Frank Swarbrick  wrote:
    > > Why might one choose to use ActivePython instead of using the free CPython?
    >
    > I believe ActivePython is also free, and it's packaged up differently
    > (with more 3rd party modules accompanying it than the standard Python
    > distribution), which might make it attractive to some.  Also, I believe
    > ActivePython is also available as a pre-built binary for some platforms
    > for which CPython is only distributed as sources (e.g., Solaris), and
    > again this difference may be seen as favorable by some.
    >
    > Alex
    
    Well, Komodo is a nice enough IDE, so you might choose to use
    ActivePython for integration reasons, and maybe it's a little easier
    on Windows.
    
    However, I would have thought that if you were planning to distribute
    an application, you would want to choose CPython for maximum
    interoperability with external packages.
    
    ActivePython claims to be ready to install across multiple platforms
    (as is CPython) so perhaps a little more work has gone into making a
    consistent experience across operating systems.
    
    I have to say, I am just guessing and would love to hear from an
    expert in the area on this topic. The ActiveState web page doesn't
    really talk about their reasons very much.
    
    Cheers,
    -T
    
    
    
    From duncan.booth at invalid.invalid  Sun Jul  1 05:11:40 2007
    From: duncan.booth at invalid.invalid (Duncan Booth)
    Date: 1 Jul 2007 09:11:40 GMT
    Subject: Reversing a string
    References: 
    	
    	<1182997438.541012.54100@o61g2000hsh.googlegroups.com>
    	
    Message-ID: 
    
    Martin Durkin  wrote:
    
    >>>>> def rev(x):
    >>             mylist = []
    >>             for char in x:
    >>                  mylist.append(char)
    >>             mylist.reverse()
    >>             for letter in mylist:
    >>                  print letter
    >> 
    >> However, compare the incredible difference in clarity and elegance
    >> between that and:
    >> 
    >>> >>> print "\n".join("spam"[::-1])
    >> 
    > 
    > OK, maybe I'm missing the point here as I'm new to Python. The first one 
    > seems clearer to me. What am I missing?
    > 
    I think all you are missing is familarity with Python, but I too don't like 
    one-liners simply for their own sake.
    
    Slicing is one of Pythons great features, but even experienced programmers 
    often forget that you can have a third argument to a slice or that it can 
    even be negative.
    
    The syntax for joining a sequence of strings with a separator is ugly, I 
    sometimes prefer to write it out as:
       print str.join('\n', whatever)
    or:
       joinlines = '\n'.join
       ...
       print joinlines(whatever)
    
    but in this case I'd be as likely to go for an explicit loop for the print:
    
    def rev(x):
        for letter in x[::-1]:
            print letter
    
    which I think hits about the optimum between brevity and clarity. Your own 
    optimum point may of course vary.
    
    
    From bdesth.quelquechose at free.quelquepart.fr  Wed Jul 25 15:38:06 2007
    From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers)
    Date: Wed, 25 Jul 2007 21:38:06 +0200
    Subject: Where do they tech Python officialy ?
    In-Reply-To: 
    References: <1185209574.045112.163780@g4g2000hsf.googlegroups.com>	<7xveca4ajp.fsf@ruckus.brouhaha.com>
    	
    Message-ID: <46ae3dc8$0$634$426a34cc@news.free.fr>
    
    Omari Norman a ?crit :
    > On Mon, Jul 23, 2007 at 10:48:10PM -0700, Paul Rubin wrote:
    >  
    > 
    >>If you're having trouble with Python because you're new at
    >>programming, I can sympathize--I don't think it's the most
    >>beginner-friendly of languages despite the efforts in that direction
    >>by the designers.  
    > 
    > 
    > Just curious--what language would you recommend as most
    > beginner-friendly?
    
    C ?-)
    
    (sorry, just kidding.)
    
    > My previous programming experience was with BASIC--and I think it is
    > true that BASIC will, in many ways, rot your brain.
    
    So will Java.
    
    I learned programming with Hypertalk (MacIntosh's Hypercard scripting 
    language, which more or less gave birth to AppleTalk), then RealBasic 
    (Mac's Better VB-like), then VB, then Java, then C, then bits of Pascal, 
    then Python, and this is where I started to see the light. But I had 
    hard time unlearning all those java-ish anal-retentive stupidities and 
    arbitrary overcomplexifications before I really enjoyed Python. Playing 
    with Lisp (Common Lisp and Scheme) and Smalltalk helped getting rid of 
    mental pollution wrt/ declarative static typing. To be honest, playing 
    with Haskell and O'Caml also helped me understanding that static typing 
    is not necessarily bad by itself.
    
    > I had used QBasic
    > and, later, a little VBA and some PHP. It took some time to unlearn some
    > bad things (object orientation in VBA seems to be mostly a hack, for
    > example, while PHP seems to be a big hack generally)
    
    Well... this is not exactly a scoop !-)
    
    > but it seems to me
    > that Python helped me learn my first modern programming language.
    > 
    > 
    >>I think Python is not used in university programs very much.  Look for
    >>one that uses SICP (Scheme) or CTM (Mozart/Oz) or a functional
    >>language like Haskell, in preference to the ones that use Java (the
    >>Cobol of the 1990's).  With some reasonable experience in Scheme or
    >>Mozart or Haskell, plus a Python manual, you'll be well on your way.
    > 
    > 
    > I had heard of these languages, but learning them is a bit discouraging
    > because (Java excepted) they don't seem to get much practical use.
    
    Before considering practical use (FWIW, Python was pretty far from 
    mainstream 7 year ago), you should ask yourself how learning one of 
    these languages will affect the way you thing about programming. While 
    mostly in the imperative/OO camp, Python stole quite a lot from 
    functional languages, and this is obviously a GoodThing(tm).
    
    My 2 cents
    
    
    From python at rcn.com  Fri Jul 27 14:18:50 2007
    From: python at rcn.com (Raymond Hettinger)
    Date: Fri, 27 Jul 2007 11:18:50 -0700
    Subject: zip() function troubles
    In-Reply-To: <1185492336.850090.279190@b79g2000hse.googlegroups.com>
    References: <1185492336.850090.279190@b79g2000hse.googlegroups.com>
    Message-ID: <1185560330.252916.307390@j4g2000prf.googlegroups.com>
    
    On Jul 26, 4:25 pm, Istvan Albert  wrote:
    > Now I know that zip () wastes lots of memory because it copies the
    > content of the lists, I had used zip to try to trade memory for speed
    > (heh!) , and now that everything was replaced with izip it works just
    > fine.  What was really surprising is that it works with no issues up
    > until 1 million items, but for say 10 million it pretty much goes
    > nuts. Does anyone know why?
    
    There's nothing in izip() that holds memory, tracks indices, or is
    sensitive to the length of its inputs (it simply calls the next method
    on the input iterators as returns the tuple result).  So, if you're
    seeing behavior changes at 10 millions items, the cause almost
    certainly lies elsewhere. One possible candidate could be memory
    consumed by immortal integer objects.
    
    
    Raymond Hettinger
    
    
    
    From rupole at hotmail.com  Thu Jul  5 00:31:54 2007
    From: rupole at hotmail.com (Roger Upole)
    Date: Thu, 5 Jul 2007 00:31:54 -0400
    Subject: windows cetificates
    References: <468b6509$0$27375$ba4acef3@news.orange.fr>
    Message-ID: <1183610011_40089@sp12lax.superfeed.net>
    
    
    m.banaouas wrote:
    > hi,
    >
    > is there any way to decrypt an email (already read with poplib, so available on client side) with python using a window 
    > certificate (those we can see on ie/internet options/content/certificates) ?
    >
    > the purpose is to decrypt an email sent and crypted by the sender with both his own certificate and the recipient one.
    >
    > thanks for any help.
    
    If the messages use standard encoding, you should be able to use CAPICOM.
    The interfaces are fairly simple to use through win32com.client.
    The 'capicom.envelopeddata' object encrypts and decrypts using certificate keys.
    
             Roger
    
    
    
    
    ----== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet News==----
    http://www.newsfeeds.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
    ---= East/West-Coast Server Farms - Total Privacy via Encryption =---
    
    
    From mmara at fibertel.com.ar  Wed Jul 11 19:02:23 2007
    From: mmara at fibertel.com.ar (Mariano Mara)
    Date: Wed, 11 Jul 2007 20:02:23 -0300
    Subject: Accessing OpenLink ODBC driver
    Message-ID: <4695617F.5090200@fibertel.com.ar>
    
    Hi everyone.
    I have a Windows 2000 server with an OpenLink ODBC client installed 
    which we use to connect to an Informix database. I'm not allowed to 
    access to informix directly so I would like to write an script to 
    retrieve some info using the mentioned driver.
    As far as I can tell, there's an odbc module for windows I can use in my 
    script but couldn't find something conclusive about how to enable this 
    module to talk to the OpenLink driver.
    
    Can you guys suggest a few pointers to help me out?
    
    TIA
    Mariano
    
    
    
    
    From istvan.albert at gmail.com  Fri Jul 27 15:40:36 2007
    From: istvan.albert at gmail.com (Istvan Albert)
    Date: Fri, 27 Jul 2007 19:40:36 -0000
    Subject: zip() function troubles
    In-Reply-To: <1185560330.252916.307390@j4g2000prf.googlegroups.com>
    References: <1185492336.850090.279190@b79g2000hse.googlegroups.com>
    	<1185560330.252916.307390@j4g2000prf.googlegroups.com>
    Message-ID: <1185565236.726558.265200@r34g2000hsd.googlegroups.com>
    
    On Jul 27, 2:18 pm, Raymond Hettinger  wrote:
    
    >> What was really surprising is that it works
    >> with no issues up until 1 million items"
    
    later editing made the sentence more difficult to read
    I should have said: "What was really surprising is that zip works
    with no issues up until 1 million items"
    
    It was the zip function (and the garbage collection that it repeatedly
    triggers) that cause the problem
    
    best,
    
    Istvan
    
    
    
    From aleax at mac.com  Wed Jul  4 23:19:36 2007
    From: aleax at mac.com (Alex Martelli)
    Date: Wed, 4 Jul 2007 20:19:36 -0700
    Subject: need a variation algorithm for Lists in Dictionaries
    References: 
    Message-ID: <1i0qt0d.1usr5zfhk5p6N%aleax@mac.com>
    
    Marc Stuart  wrote:
    
    > Hi, I am trying to create a function, where I pass a dictionary with a
    > lits of strings, and try to return a
    > a list of strings, for all variations, any ideas ?
    > Thanks
    > 
    > def getAllVariants(someDict):
    >       keys = someDict.keys()
    >       for x in keys:
    >                       print len(someDict[x])
    
    Note that .keys() returns a somewhat random permutation of the keys
    depending on their hash values (though you don't see that effect when
    the keys are a few small integers;-); you may want keys =
    sorted(someDict) to use the keys in sorted order, or some variant of
    that.
    
    Also, it's not clear what you mean by "return" here, while you use a
    print statement and later you say "output".  I'm going to use neither
    return nor print, but the flexible yield (you can make a list by calling
    list(allVariants(someDict)), or print each string by looping
        for v in allVariants(someDict): print v
    and so forth), technically making this "a generator".
    
    > x = {1:['a','b'],2:['b','c'],3:['d','e','f','g']}
    > getAllVariants(x)
    > 
    > """ I need to get a list of strings that render all possible variants,
    > this is what my output should be based on the
    > x dictionary:
    > abd
    > abe
    
    (etc, snipped).
    
    Such problems are most often easiest to solve recursively: for each
    value in the list corresponding to the first key, yield that value
    followed by all variants of the _rest_ of the dictionary's keys.  Any
    recursion needs a "base case" or terminating condition: simplest though
    not fastest here is to use the empty string as the only value yielded
    when there are no more keys (i.e., the argument's empty).
    
    def allVariants(someDict):
        if not someDict: yield ''
        d = dict(someDict)
        k = min(d)
        v = d.pop(k)
        for i in v:
                for rest in allVariants(d):
                    yield v+rest
    
    the copy at the second statement is needed only to avoid destroying the
    original dict passed by the "real" caller; you can optimize things a
    bit, if need be, by making the recursive function a private auxiliary
    one (which allVariants itself calls appropriately).  I'm not going to
    explore optimization possibilities (including recursion elimination,
    which is often the strongest optimization you can to do a recursive
    function but may well obscure its essential simplicity:-).
    
    
    Alex
    
    
    From nis at superlativ.dk  Mon Jul  2 05:29:09 2007
    From: nis at superlativ.dk (=?ISO-8859-1?Q?Nis_J=F8rgensen?=)
    Date: Mon, 02 Jul 2007 11:29:09 +0200
    Subject: howto resend args and kwargs to other func?
    In-Reply-To: <4688a103$0$29642$426a34cc@news.free.fr>
    References: <1183279997.244378.105810@n60g2000hse.googlegroups.com>
    	
    	<1183280667.542964.175570@u2g2000hsc.googlegroups.com>
    	
    	<1183282733.179683.174350@c77g2000hse.googlegroups.com>
    	<5er6doF31bulkU1@mid.individual.net>
    	<4688a103$0$29642$426a34cc@news.free.fr>
    Message-ID: <4688C565.3030707@superlativ.dk>
    
    Bruno Desthuilliers skrev:
    
    >> Why do people do this without posting what the actual solution is!!!!
    > 
    > Probably because those people think usenet is a free help desk ?
    
    Usenet definitely isn't a help desk. You often get useful answers from
    usenet, from people who are not reading from a script.
    
    Nis
    
    
    From dwarnold45 at suddenlink.net  Sat Jul  7 13:14:57 2007
    From: dwarnold45 at suddenlink.net (David)
    Date: Sat, 07 Jul 2007 10:14:57 -0700
    Subject: malloc error for newbie
    In-Reply-To: <1183814820.594726.301340@e9g2000prf.googlegroups.com>
    References: <1183791562.999601.83790@z28g2000prd.googlegroups.com>
    	<1183814820.594726.301340@e9g2000prf.googlegroups.com>
    Message-ID: <1183828497.061940.77720@g37g2000prf.googlegroups.com>
    
    On Jul 7, 6:27 am, John Machin  wrote:
    > On Jul 7, 4:59 pm, David  wrote:
    >
    > > Hi,
    >
    > > Very new to python. When I uncomment the line
    > > #        self.im.putpalette(mkpalette())
    >
    > Try to focus in on where the nasty is happening:
    >
    >    p = mkpalette()
    >    # self.im.putpalette(p)
    >
    >
    >
    > > in the following code, I get the error:
    >
    > > python $ ./mandelbrot.py
    > > Python(2860) malloc: ***  Deallocation of a pointer not malloced:
    > > 0xff000000; This could be a double free(), or free() called with the
    > > middle of an allocated block; Try setting environment variable
    > > MallocHelp to see tools to help debug
    >
    > > I don't have the expertise to get by this error. Can someone help?
    >
    > > Thanks.
    >
    > > #! /usr/local/bin/python
    > > # Filename: mandelbrot.py
    >
    > > import Image, ImagePalette
    >
    > Read the docs:http://effbot.org/imagingbook/imagepalette.htm
    >
    > They imply that len(palette) should be 769 (256*3)
    >
    >
    >
    > > def mkpalette():
    > >     global palette
    >
    > Nothing to do with your problem, but lose the above line, and examine
    > carefully whatever induced you to include it.
    >
    > >     palette = [0,0,0]
    > >     for i in range(256):
    > >         palette.extend([i*5%200+55,i*7%200+55,i*11%200+55])
    > >     return palette
    >
    > So now len(palette) == 257*3 instead of 256*3; this may be your
    > problem.
    >
    > HTH,
    > John
    
    That did, it. The following corrects he problem. Thanks.
    
    def mkpalette():
        palette = [0,0,0]
        for i in range(255):
            palette.extend([i*5%200+55,i*7%200+55,i*11%200+55])
        return palette
    
    
    
    
    From supercooper at gmail.com  Fri Jul 20 10:02:38 2007
    From: supercooper at gmail.com (supercooper)
    Date: Fri, 20 Jul 2007 07:02:38 -0700
    Subject: Gmail Error using smtplib
    In-Reply-To: <1184934990.184567.93760@z28g2000prd.googlegroups.com>
    References: <1184934990.184567.93760@z28g2000prd.googlegroups.com>
    Message-ID: <1184940158.814592.128190@q75g2000hsh.googlegroups.com>
    
    This works for me...
    
    def SendEmail(msgType,sender,recipient,subject,message):
        """
        Sends either a log file or a string message in email to
    recipient.
        Uses Google smtp server to send the mail.
    
        CHANGELOG:
        2006-12-7:    Set sender, recipient, subject as input variables
     
    ---------------------------------------------------------------------------------------------
        Inputs:
        msgType:    If 'log', message is path to log file that is to be
    written into email body
        sender:     Senders email addy
        recipient:  Who we want to send to
        subject:    Email subject line
        message:    Message body of email
     
    ---------------------------------------------------------------------------------------------
        """
        # determine msg type
        if msgType == 'log':
            # Send log file in email
            fp = open(message, 'rb')
            # Create a text/plain message
            # Read contents of log file into memory
            msg = MIMEText(fp.read())
            fp.close()
        else:
            # If not a log file, just create a text/plain message
            msg = MIMEText(message)
    
        # User/pwd
        me = 'email at gmail.com'
        pwd = 'pass'
    
        # Build the email
        fromAddr = sender
        toAddr = recipient
        msg['Subject'] = subject
        msg['From'] = fromAddr
        msg['To'] = toAddr
    
        # Set up and connect to smtp server
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.set_debuglevel(1)
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(me, pwd)
        # Send the email
        server.sendmail(fromAddr, toAddr, msg.as_string())
        server.close()
    
    
    
    
    
    From thorsten at thorstenkampe.de  Thu Jul 26 04:43:43 2007
    From: thorsten at thorstenkampe.de (Thorsten Kampe)
    Date: Thu, 26 Jul 2007 09:43:43 +0100
    Subject: code indentation
    References: 
    	
    	<1185297657.186852.136950@k79g2000hse.googlegroups.com>
    	
    	<87lkd5jt83.fsf@benfinney.id.au>
    	<1185357861.989194.117000@r34g2000hsd.googlegroups.com>
    	
    	<1185387723.155661.311510@b79g2000hse.googlegroups.com>
    Message-ID: 
    
    *  (Wed, 25 Jul 2007 11:22:03 -0700)
    > On 25 srp, 17:31, Wildemar Wildenburger  wrote:
    > > vedrandeko... at v-programs.com wrote:
    > > >> And while we're on the topic of communication: The original poster
    > > >> would do well to learn that increasing the number of consecutive
    > > >> punctuation marks (!!!, ???) is a sure way to turn away many people
    > > >> who would otherwise be helpful. Sentences need at most one '!' or '?',
    > > >> adding more does not improve the chances of being taken seriously.
    > >
    > > > And if you can help me than please help me , but if you can't then
    > > > please don't leave me some stupid messages
    > >
    > > Whats stupid about this? It's sane advice.
    > >
    > > Which looks more serious to you:
    > >
    > > this:
    > > I can't do it!!!! Can you PLEASE help me????!!!?!
    > >
    > > or this:
    > > I don't know the answer. Can you please help me?
    > >
    > > Even if it makes no difference to you, to many people it does. So Ben is
    > > right: People *will* take your posts more seriously if you restrict your
    > > use of punctuation (if only because its easier to read).
    > > Don't feel offended, nobody was trying to put you down.
    > 
    > On this group I ask for serious help and now we talk about
    > communication. Then I you don't know how to help me then please DON'T
    > SAY ANYTHING
    
    You already got serious help even though you haven't realised that 
    yet.
    
    T.
    
    
    From no at no.no  Tue Jul 17 16:55:05 2007
    From: no at no.no (Daniel)
    Date: Tue, 17 Jul 2007 23:55:05 +0300
    Subject: a=0100; print a ; 64 how to reverse this?
    References: <1184670575.205759.115360@i13g2000prf.googlegroups.com>
    	<469cb76f$0$7584$426a34cc@news.free.fr>
    	
    Message-ID: 
    
    On Tue, 17 Jul 2007 21:22:03 +0300, Wildemar Wildenburger  
     wrote:
    
    >
    > Bruno Desthuilliers wrote:
    >> mosi a ?crit :
    >>
    >>> Problem:
    >>> how to get binary from integer and vice versa?
    >>> [snip]
    >>> What`s the simplest way to do this?
    >>>
    >>
    >> bruno at bruno:~$ 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.
    >>  >>> help(int)
    >> Help on class int in module __builtin__:
    >>
    >> class int(object)
    >>   |  int(x[, base]) -> integer
    >>
    >
    > :D
    >
    > After reading the other two replies, this one made me burst with  
    > laughter. Thanks for that.
    
    Why exactly?
    
    
    From adrian_p_smith at yahoo.com  Tue Jul  3 17:47:13 2007
    From: adrian_p_smith at yahoo.com (Adrian Smith)
    Date: Tue, 03 Jul 2007 14:47:13 -0700
    Subject: mysteries of urllib/urllib2
    In-Reply-To: <1183477360.751290.273740@n2g2000hse.googlegroups.com>
    References: <1183470239.153444.244700@j4g2000prf.googlegroups.com>
    	<1183472702.932557.108600@n2g2000hse.googlegroups.com>
    	<1183475672.295922.47600@e9g2000prf.googlegroups.com>
    	<1183477360.751290.273740@n2g2000hse.googlegroups.com>
    Message-ID: <1183499233.604829.156480@j4g2000prf.googlegroups.com>
    
    On Jul 4, 12:42 am, Ben Cartwright  wrote:
    > On Jul 3, 11:14 am, Adrian Smith  wrote:
    >
    > > > > The following (pinched
    > > > > from Dive Into Python) seems to work perfectly in Idle, but
    > > > > falls at the final hurdle when run as a cgi script
    > > > Put this at the top of your cgi script:
    >
    > > > import cgitb; cgitb.enable()
    >
    > Did you even try this?  Asking for Python help without posting the
    > traceback is like phoning your mechanic and saying, "My car is
    > making a generic rattling noise, can you tell me what the problem
    > is without looking under the hood?"
    
    Sorry, I thought as the cgi did appear to have web access it wasn't
    applicable, and it's amazing what some mechanics can infer from engine
    noise. cgitb certainly does send back an impressive amount of
    information, I'll be sure to use it in future.
    
    > > Apparently there's a way to change the user-agent string
    > > by subclassing urllib's URLopener class, but that's beyond my
    > > comfort zone at present.
    >
    > Untested:
    >
    > import urllib
    > url = 'http://groups.google.com/group/Google-AJAX-Search-API/
    > browse_thread/thread/a0eb87ad13b11762'
    > opener = urllib.FancyURLopener()
    > opener.addheaders = [('User-Agent', 'Fauxzilla 4.0')]
    > data = opener.open(url).read()
    
    That works a treat, thanks!
    
    
    
    From steve at holdenweb.com  Mon Jul 16 11:29:22 2007
    From: steve at holdenweb.com (Steve Holden)
    Date: Mon, 16 Jul 2007 11:29:22 -0400
    Subject: Implementaion of random.shuffle
    In-Reply-To: <87d4ys9z46.fsf@mulj.homelinux.net>
    References: <4e8b75a40707160510h25773f3ch749492cba2dc733@mail.gmail.com>	
    	<87d4ys9z46.fsf@mulj.homelinux.net>
    Message-ID: 
    
    Hrvoje Niksic wrote:
    > Steve Holden  writes:
    > 
    >> So it would appear that the developers chose the Knuth algorithm
    >> (with a slight variation) for *their* implementation. Now you have
    >> to ask yourself whether your surmise is genuinely correct (in which
    >> case the documentation may contain a bug) or whether the
    >> documentation is indeed correct and you are in error.
    > 
    > That is a good question.  The random module uses the Mersenne twister,
    > which has a repetition period of 2**19937.  The number of n-sized
    > permutations of a list with n elements is n!, while each shuffle
    > requires n calls to the PRNG.  This means that to be able to generate
    > all permutations, the PRNG must have a period of at least n! * n.  In
    > the case of MT, it means that, regarding the period, you are safe for
    > lists with around 2079 elements.  shuffle's documentation may have
    > been written before the random module was converted to use the MT.
    > 
    > 2**19937 being a really huge number, it's impossible to exhaust the
    > Mersenne twister by running it in sequence.  However, there is also
    > the question of the spread of the first shuffle.  Ideally we'd want
    > any shuffle, including the first one, to be able to produce any of the
    > n! permutations.  To achieve that, the initial state of the PRNG must
    > be able to support at least n! different outcomes, which means that
    > the PRNG must be seeded by at least log2(n!) bits of randomness from
    > an outside source.  For reference, Linux's /dev/random stops blocking
    > when 64 bits of randomness are available from the entropy pool, which
    > means that, in the worst case, shuffling more than 20 elements cannot
    > represent all permutations in the first shuffle!
    
    Thanks for this thoughtful analysis. I believe we can therefore leave 
    the documentation (which almost certainly *was* written before the 
    adoption of MT) alone for 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 maxkhesin at gmail.com  Sun Jul 15 15:04:53 2007
    From: maxkhesin at gmail.com (xamdam)
    Date: Sun, 15 Jul 2007 19:04:53 -0000
    Subject: zipfile 2GB problems?
    In-Reply-To: <1184509541.717169.89920@d55g2000hsg.googlegroups.com>
    References: <1184474112.081258.111490@n60g2000hse.googlegroups.com>
    	<1184509541.717169.89920@d55g2000hsg.googlegroups.com>
    Message-ID: <1184526293.735672.144170@m3g2000hsh.googlegroups.com>
    
    > Hi,
    > I use PKZIP V9.00 and maintain a 2.5GB zipfile that consists of over
    > 6,600 zipped files.
    > There is no problem with reading or writing.
    > Thanks,
    > Jim
    
    Which version of Python? What platform?
    
    thanks,
    max
    
    
    
    From horpner at yahoo.com  Wed Jul 25 14:47:45 2007
    From: horpner at yahoo.com (Neil Cerutti)
    Date: Wed, 25 Jul 2007 18:47:45 GMT
    Subject: Flatten a list/tuple and Call a function with tuples
    References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com>
    	<46a76a0c$0$1471$9b622d9e@news.freenet.de>
    	<1185378418.100041.38560@w3g2000hsg.googlegroups.com>
    	<1185379218.286977.124040@19g2000hsx.googlegroups.com>
    	<1185384306.104549.287510@19g2000hsx.googlegroups.com>
    	<1185384793.577650.256310@d55g2000hsg.googlegroups.com>
    Message-ID: 
    
    On 2007-07-25, Jeff  wrote:
    > Here's a quick flatten() function:
    >
    > def flatten(obj):
    >     if type(obj) not in (list, tuple, str):
    >         raise TypeError("String, list, or tuple expected in
    > flatten().")
    >     if len(obj) == 1:
    >         if type(obj[0]) in (tuple, list):
    >             return flatten(obj[0])
    >         else:
    >             return [obj[0]]
    >     else:
    >         return [obj[0]] + flatten(obj[1:])
    >
    > x = [1, 2, (3, 4)]
    > y = (1, 2, [3, 4])
    > z = "It even works with strings!"
    > d = {"foo": "bar", "baz": "bat"}
    
    e = [[1], 2, 3, , 4]
    f = [1, 2, 3, 4, []]
    
    -- 
    Neil Cerutti
    
    
    From see.signature at no.spam  Thu Jul  5 04:43:07 2007
    From: see.signature at no.spam (Eric Brunel)
    Date: Thu, 05 Jul 2007 10:43:07 +0200
    Subject: Tkinter toggle a Label Widget based on checkbutton value
    References: 
    Message-ID: 
    
    On Wed, 04 Jul 2007 21:51:34 +0200, O.R.Senthil Kumaran  
     wrote:
    > Following is a tk code, which will display a checkbutton, and when  
    > checkbox is
    > enabled, it will show the below present Label.
    >
    > What I was trying is, when checkbox is enabled the Label should be shown  
    > and
    > when checkbox is disabled, the window should look like before.
    >
    > But, I am finding that once enabled (shown), its not  
    > very-straightforward to
    > hide it from the window.
    >
    > Any suggestions on  how can i make this checkbutton effect.
    > 1) Press Enable IP, the Label IP should be shown.
    > 2) Toggle Enable IP (So that its unset). the Label IP should not be  
    > shown.
    >
    > #!/usr/bin/python
    > from Tkinter import *
    > root = Tk()
    > root.title('something')
    > x = StringVar()
    > def display():
    >     if x.get():
    >         ip = Label(root,text="IP:")
    >         ip.grid(row=3,column=0)
    >
    > proxy = Checkbutton(root, text="Enable IP:", variable =  
    > x,onvalue="proxy",
    >         offvalue="",command=display)
    > proxy.grid(row=2,column=0)
    > root.mainloop()
    
    Wojciech gave a perfectly valid answer that'll work in all cases.
    
    Here is another one, that you may or may not be able to use, which  
    consists in using the same Tkinter variable for your check-button's value  
    and your label's text:
    --------------------------------------------------
     from Tkinter import *
    
    root = Tk()
    
    labelString = StringVar()
    
    b = Checkbutton(root, text="Enable IP:", variable=labelString,
                           onvalue='IP:', offvalue='')
    b.grid(row=2, column=0)
    
    Label(root, textvariable=labelString).grid(row=3, column=0)
    
    root.mainloop()
    --------------------------------------------------
    
    This doesn't really make the label "disappear" when the check-button is  
    off, but simply sets its text to the empty string.
    
    HTH
    -- 
    python -c "print ''.join([chr(154 - ord(c)) for c in  
    'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])"
    
    
    From gagsl-py2 at yahoo.com.ar  Tue Jul 10 22:19:04 2007
    From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina)
    Date: Tue, 10 Jul 2007 23:19:04 -0300
    Subject: serializing datetime object
    References: 
    Message-ID: 
    
    En Tue, 10 Jul 2007 13:13:54 -0300, rkmr.em at gmail.com   
    escribi?:
    
    > I want to serialize datetime.datetime.now() object . I could convert it  
    > to
    > string but how do I get a datetime object back from the string?
    > Any suggestions?
    
    Use the pickle module.
    
    -- 
    Gabriel Genellina
    
    
    
    From orsenthil at gmail.com  Wed Jul  4 07:38:38 2007
    From: orsenthil at gmail.com (Phoe6)
    Date: Wed, 04 Jul 2007 04:38:38 -0700
    Subject: using subprocess for non-terminating command
    Message-ID: <1183549118.773813.132940@r34g2000hsd.googlegroups.com>
    
    Hi all,
    Consider this scenario, where in I need to use subprocess to execute a
    command like 'ping 127.0.0.1' which will have a continuous non-
    terminating output in Linux.
    
    # code
    >>>import subprocess
    >>>process = subprocess.Popen('ping 127.0.0.1', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    >>>print process.pid # returns pid
    >>>print process.poll() # returns None!!! this is strange.
    >>>print process.stdout.read()
    
    # This hangs at this point.
    How should I handle these kind of commands (ping 127.0.0.1) with
    subprocess module. I am using subprocess, instead of os.system because
    at anypoint in time, I need access to stdout and stderr of execution.
    
    Thanks,
    Senthil
    
    
    
    From steve at holdenweb.com  Mon Jul 30 16:38:51 2007
    From: steve at holdenweb.com (Steve Holden)
    Date: Mon, 30 Jul 2007 16:38:51 -0400
    Subject: How to write GUI and event separately in wxPython??
    In-Reply-To: <1185826617.556482.23530@g4g2000hsf.googlegroups.com>
    References: <1185777254.925902.204500@z28g2000prd.googlegroups.com>	<5h5kmiF3hmufcU3@mid.uni-berlin.de>		<5h5upbF3hmufcU5@mid.uni-berlin.de>
    		
    	<1185826617.556482.23530@g4g2000hsf.googlegroups.com>
    Message-ID: <46AE4C5B.5060706@holdenweb.com>
    
    star.public at gmail.com wrote:
    > On Jul 30, 11:42 am, "Chris Mellon"  wrote:
    > 
    >>>> On Mon, 30 Jul 2007 06:32:55 -0400, Steve Holden wrote:
    >>>>>  >>> [x for x in xrange(0, 101)] == [y for y in xrange(101)]
    >>>>> True
    > 
    >> nitpick: list(xrange(42)) == list(xrange(42)) is slightly more concise
    >> than the list comp..
    > 
    > Not that it has anything to do with this topic anymore, but I find the
    > list comp a bit clearer for expressing the thought 'each element in
    > one is the same as the coresponding element in the other, or: the
    > sequences are identical' -- the list() version would proabably have
    > had me going 'huh?' even longer ^_^.
    > --
    > [star for star in weaver]
    
    Here's another one, a little more obscure still, but only valid in 2.5 
    because of all():
    
     >>> all(x==y for (x, y) in zip(xrange(0, 101), xrange(101)))
    True
     >>>
    
    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 khemkaamit at gmail.com  Fri Jul 27 06:05:06 2007
    From: khemkaamit at gmail.com (Amit Khemka)
    Date: Fri, 27 Jul 2007 15:35:06 +0530
    Subject: Filtering content of a text file
    In-Reply-To: <1185528507.750436.91140@j4g2000prf.googlegroups.com>
    References: <1185528507.750436.91140@j4g2000prf.googlegroups.com>
    Message-ID: <1360b7230707270305l42d855ecg630a1d5f6b19e6ee@mail.gmail.com>
    
    On 7/27/07, Ira.Kovac at gmail.com  wrote:
    > Hello All,
    >
    > I'd greatly appreciate if you can take a look at the task I need help
    > with.
    >
    > It'd be outstanding if someone can provide some sample Python code.
    >
    > Thanks a lot,
    >
    > Ira
    >
    > -------------------------------------------------------------------------------
    > Problem
    > -------------------------------------------------------------------------------
    >
    > I am working with 30K+ record datasets in flat file format (.txt) that
    > look like this:
    >
    > //-+alibaba sinage
    > //-+amra damian//_9
    > //-+anix anire//_
    > //-+borom
    > //-+bokima sun drane
    > //-+ciren
    > //-+cop calestieon eded
    > //-+ciciban
    > //-+drago kimano sole
    >
    >
    > The records start with the same string (in the example //-+) wich is
    > followed by another string of characters taht's changing from record
    > to record.
    >
    > I am working on one file at the time and for each file I need to be
    > able to do the following:
    >
    > a) By looping thru the file the program should isolate all records
    > that have letter a following the //-+
    > b) The isolated dataset will contain only records that start with //-
    > +a
    > c) Save the isolated dataset as flat flat text file named a.txt
    > d) Repeat a), b) and c) for all letters of english alphabet (a thru z)
    > and numerical values (0 thru 9)
    
    Well that should be easy if you take a look at methods in "string" module:
    A rough sketch would be :
    
    import string  # import string module
    alnums = list(string.lowercase+string.digits)   # create a list of
    alphabets and digits
    
    for alnum in alnums:
        outfile = open(alnum+'.txt', 'w')
        for line in file("myrecords.txt"):   # iterate over the records
            if line.startswith("//-+"+alnum):  # check your condition
                # write the matches to a file
                outfile.write(line)
         outfile.close()
    
    However rather than looping over the file for each alnum you may just
    iterate over the file, and check the starting characters (if len(line)
    > 4:    ch=line[4]) , and if it is alnum then process it.
    
    Cheers,
    -- 
    ----
    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 byte8bits at gmail.com  Thu Jul 26 16:33:07 2007
    From: byte8bits at gmail.com (brad)
    Date: Thu, 26 Jul 2007 16:33:07 -0400
    Subject: I am giving up perl because of assholes on clpm -- switching
    	to Python
    In-Reply-To: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com>
    References: <0Y2dnTFHdYnENTrbnZ2dnUVZ_vrinZ2d@giganews.com>
    Message-ID: 
    
    Martha_Jones at tx.net wrote:
    > 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
    
    Out of the pan and into the fire. :) Welcome to the world of Ph.D's in 
    Computer Science. You think the Perl guys have attitude, just wait and 
    see what you're in for over here. I think you'll find attitudes in any 
    programming language... just different types. May God have mercy on your 
    soul! You'll be making a similar announcement in a few weeks when you 
    switch to Ruby :) The cold, cruel theoretical, lofty Python will 
    mercilessly crush you :)
    
    I'm just joking, OK.
    
    
    From semanticist at gmail.com  Sun Jul 22 14:02:52 2007
    From: semanticist at gmail.com (Miles)
    Date: Sun, 22 Jul 2007 14:02:52 -0400
    Subject: URL parsing for the hard cases
    In-Reply-To: 
    References: 
    Message-ID: 
    
    On 7/22/07, John Nagle wrote:
    >     Is there something available that will parse the "netloc" field as
    > returned by URLparse, including all the hard cases?  The "netloc" field
    > can potentially contain a port number and a numeric IP address.  The
    > IP address may take many forms, including an IPv6 address.
    
    What do you mean by "parse" the field?  What do you want to get back
    from the parser function?
    
    
    From vedrandekovic at v-programs.com  Fri Jul 27 13:46:46 2007
    From: vedrandekovic at v-programs.com (vedrandekovic at v-programs.com)
    Date: Fri, 27 Jul 2007 10:46:46 -0700
    Subject: a simple string question
    In-Reply-To: 
    References: <1185549793.114644.62170@k79g2000hse.googlegroups.com>
    	
    Message-ID: <1185558406.916313.32980@r34g2000hsd.googlegroups.com>
    
    On 27 srp, 19:29, Wildemar Wildenburger  wrote:
    > vedrandeko... at v-programs.com wrote:
    > > I have one question about string.I am trying to make an function to
    > > analyze line  of some text, this is my example: "HELLO;HELLO2:WORLD:",
    > >  if that function in this text find ";" and ":" ( in this example will
    > > find both)
    >
    > > e.g  that function must return this:
    >
    > > "HELLO;\nHELLO2:\n\t\t\t\t\t\t\tWORLD:"
    >
    > If I understand you correctly you want to replace ";" by ";\n" and ":"
    > by ":\n\t\t\t\t\t\t\t".
    > Well guess what? The replace() method does just this. Have a read:
    > 
    >
    > /W
    
    Hello,
    
    No,that's not what I need...
    When this function detect ";" or ":" ,it must append character "\n" or
    "\n\t" ahead ":" or ";" another e.g
    
    1) text="Hello world;Hello:Hello2"
    
    2) When function detect ";" or ":" it must append character "\n" or "\n
    \t" ahead ":" or ";", so that must look like this:
    
    NEW TEXT :  "Hello world;\nHello:\n\t\t\n\n\n\n\n\nHello2"
    
    Regards,
    Vedran
    
    
    
    From irmen.NOSPAM at xs4all.nl  Mon Jul 30 17:57:03 2007
    From: irmen.NOSPAM at xs4all.nl (Irmen de Jong)
    Date: Mon, 30 Jul 2007 23:57:03 +0200
    Subject: Directory
    In-Reply-To: <1185831827.206641.163630@x40g2000prg.googlegroups.com>
    References: <1185831827.206641.163630@x40g2000prg.googlegroups.com>
    Message-ID: <46ae5eb2$0$232$e4fe514c@news.xs4all.nl>
    
    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.
    > 
    
    Look up os.walk (allows you to selectively walk over files and directories)
    and/or os.path.isdir (allows you to test if a given path is a directory)
    
    --irmen
    
    
    From funtimes at mailinator.com  Mon Jul  9 09:51:02 2007
    From: funtimes at mailinator.com (funtimes at mailinator.com)
    Date: Mon, 09 Jul 2007 09:51:02 -0400
    Subject: Python ghost compile
    Message-ID: <5.2.1.1.0.20070709094449.024dcd58@goldy.holtzman.net>
    
    I split a large python (2.5.1) program into three modules. Let's call them 
    mainmod, submod1, and submod2. mainmod imports submod1 and submod2. When I 
    make changes to any of these modules, it is not reflected in the 
    compile.  Only if exit idle and re-run idle. I've removed the two relevant 
    .pyc files. It holds onto the first compile made after starting idle. I've 
    triple-checked the names I've given the modules, they're all unique. Any clues?
    
    
    
    
    From oren.tsur at gmail.com  Thu Jul 26 10:23:35 2007
    From: oren.tsur at gmail.com (oren.tsur at gmail.com)
    Date: Thu, 26 Jul 2007 07:23:35 -0700
    Subject: Parsing XML with ElementTree (unicode problem?)
    In-Reply-To: <1185455621.498620.51650@i13g2000prf.googlegroups.com>
    References: <1185200976.082516.105420@57g2000hsv.googlegroups.com>
    	<1185279975.254458.7510@57g2000hsv.googlegroups.com>
    	<1185287404.060182.314750@57g2000hsv.googlegroups.com>
    	<46A618E9.6010304@web.de>
    	<1185449094.998635.67870@w3g2000hsg.googlegroups.com>
    	<1185455621.498620.51650@i13g2000prf.googlegroups.com>
    Message-ID: <1185459815.871401.35320@b79g2000hse.googlegroups.com>
    
    On Jul 26, 3:13 pm, John Machin  wrote:
    > On Jul 26, 9:24 pm, oren.t... at gmail.com wrote:
    >
    > > OK, I solved the problem but I still don't get what went wrong.
    > > Solution - use tree builder in order to create the new xml file
    > > (previously I was  "manually" creating it).
    >
    > > I'm still curious so I'm adding a link to a short and very simple
    > > script that gets an xml (containing non ascii chars) from the web and
    > > saves some of the elements to 2 different local xml files - one is
    > > created by XMLWriter and the other is created manually. you could see
    > > that parsing of the first local file is OK while parsing of the
    > > "manually" created xml file fails. obviously I'm doing something wrong
    > > and I'd love to learn what.
    >
    > > the toy script:http://staff.science.uva.nl/~otsur/code/xmlConversions.py
    >
    > Simple file comparison:
    >
    > File 1: ... Modern Church.  <p>The book ...
    > File 2: ... Modern Church.  

    The book ... > > Firefox: > > XML Parsing Error: mismatched tag. Expected:

    . > Location: file:///C:/junk/myDeVinciCode166_2.xml > Line Number 3, Column 1153: > > The...Church.

    The...thrill. > ------------------------------------------^ yup, but why does this happen - on the script side - I write the exact same strings, of content with supposedly, same encoding, so why the encoding is different? From bj_666 at gmx.net Sun Jul 22 05:19:59 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: 22 Jul 2007 09:19:59 GMT Subject: Pythonic way for missing dict keys References: <46a20f0b$0$27858$426a74cc@news.free.fr> <1185060037.143793.50490@n60g2000hse.googlegroups.com> Message-ID: <5gglpvF3g1e4eU2@mid.uni-berlin.de> On Sat, 21 Jul 2007 16:20:37 -0700, genro wrote: > On Jul 19, 6:29 am, Bruno Desthuilliers > wrote: >> No "surprise" here, but it can indeed be suboptimal if instanciating >> myobject is costly. > > What about this way ? > > my_obj = my_dict.get(key) or my_dict.setdefault(key,myobject()) Reduces the unnecessary instantiation of `myobject` to "false" objects. May be not good enough. Ciao, Marc 'BlackJack' Rintsch From giovanni.porcari at gmail.com Sun Jul 8 06:25:34 2007 From: giovanni.porcari at gmail.com (genro) Date: Sun, 08 Jul 2007 10:25:34 -0000 Subject: Expandable 2D Dictionaries? In-Reply-To: <1183736635.415927.208450@57g2000hsv.googlegroups.com> References: <1183736635.415927.208450@57g2000hsv.googlegroups.com> Message-ID: <1183890334.500741.60860@57g2000hsv.googlegroups.com> On Jul 6, 5:43 pm, Robert Dailey wrote: > Hi, > > I am interested in creating an expandable (dynamic) 2D dictionary. For > example: > > myvar["cat"]["paw"] = "Some String" > > The above example assumes "myvar" is declared. In order for this to > work, I have to know ahead of time the contents of the dictionary. For > the above to work, my declaration must look like: > > myvar = {"cat": {"paw":""} } > > I would like to not have to declare my dictionary like this, as it > does not allow it to be expandable. I'm very new to Python (I'm a > professional C++ programmer. Any comparisons to C++ would help me > understand concepts). > > Is there a way that when I index into my dictionary using an "unknown" > index (string), that python will dynamically add that key/value pair? > > Thanks. Hi Robert take a look to our Bag module ( http://trac.genropy.org/wiki/BagManual). Bag is a hierarchical container that can be used as nested dictionary. If you are interested I'll send you the module. There is not yet a public DL link as documentation has still to be tuned... HTH Giovanni From data at azcgroup.com Tue Jul 10 13:25:29 2007 From: data at azcgroup.com (data at azcgroup.com) Date: Tue, 10 Jul 2007 10:25:29 -0700 Subject: REALLY! Message-ID: Is this for reals man! I hope this is not one of those rip-off emails. -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Thu Jul 5 10:53:39 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Thu, 05 Jul 2007 14:53:39 GMT Subject: Re-raising exceptions with modified message References: Message-ID: On 2007-07-05, Christoph Zwerschke wrote: > Thomas Heller wrote: >> I have the impression that you do NOT want to change the >> exceptions, instead you want to print the traceback in a >> customized way. But I may be wrong... > > No, I really want to modify the exception, supplementing its > message with additional information about the state of the > program. > > The use case are compiled Kid templates > (http://kid-templating.org). If an error occurs, I want to add > the corresponding line number of the XML file as information > for the template developer. Since the final error handling may > happen somewhere else (e.g. by TurboGears importing a Kid > template), I do not want to modify trackeback handling or > something. The documentation for BaseException contains something that might be relevant: [...] If more data needs to be attached to the exception, attach it through arbitrary attributes on the instance. All arguments are also stored in args as a tuple, but it will eventually be deprecated and thus its use is discouraged. New in version 2.5. [...] I don't know if something like the following would help: >>> def foo(): ... try: ... 12/0 ... except ZeroDivisionError, e: ... e.my_info = "Oops!" ... raise ... >>> try: ... foo() ... except ZeroDivisionError, e: ... print e.my_info ... Oops! Users could get at the extra info you attached, but it wouldn't be automatically displayed by the interpreter. -- Neil Cerutti Symphonies of the Romantic era were a lot longer in length. --Music Lit Essay From leipold at ace-net.com Tue Jul 31 15:45:28 2007 From: leipold at ace-net.com (Walt Leipold) Date: Tue, 31 Jul 2007 15:45:28 -0400 Subject: Process Control Help In-Reply-To: <1185808072.695752.20720@z28g2000prd.googlegroups.com> References: <1185808072.695752.20720@z28g2000prd.googlegroups.com> Message-ID: <46AF9158.4030002@ace-net.com> Azazello wrote: > We're looking to run some industrial machinery from a PC. Starting > with some basic servo controls and IO port reading for something like > an XYZ table (just X would be a good start!). Now there is some > existing software out there for PC control but this software is, to my > understanding, largely unnecessary and "black box". This "black box" > creates a problem when trying to e.g. control servos and IO with the > same program. And if we want to include an HMI like a touchscreen, or > export the machinery's production into a RSS feed, the web of software > becomes messy and slow. > Soo.... > I need to find some ethernet friendly IO, serial would be fine but but > it's a leash in many instances. I know some protocols have been > ported to ethernet, but I am having extreme difficulty figuring out > what these protocols entail. ModBus/TCP is the one I'd like to > choose. > I know that people have done this kind of software but it > seems that industrial python remains a bit taboo because of > proprietary issues... 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 industry evolved, and the kinds of programmers and development teams that write industrial control packages. > If we could consolidate this software into a single, non > "black-box" package, we could see significant improvements > in development time. 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? > Having to program 3 different devices with three > different languages to control your PLC, Servos, and module X is > the status quo we face, but it is quite frustrating and limited. I share your frustration with the status quo in industrial automation. On the other hand, I've been brought in to customer sites a number of time to fix their re-invented wheels, and my advice is not to re-invent the wheel. 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. For reasons of quality, long-term supportability, manageability, insurability, and several other -ilities, the sad facts are: * Unless you're a hobbyist, if you want to do machine/motion control, do it from a PLC. Windows is not reliable, stable, or real-time enough to be trusted to control moving pieces of hardware, and custom software, possibly with hand-crafted multithreading, is not as reliable or predicatable as ladder logic on a PLC. (Look up "Therac 25" for some reasons why.) Python is a great language, but it depends on the underlying OS for threading, and has a GIL that can bite you too. 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. * 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. (Wow, that was a depressing post to write.) -- Walt "Eddies in the space-time continuum!" "And this is his sofa, is it?" From wildemar at freakmail.de Wed Jul 25 22:30:27 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Thu, 26 Jul 2007 04:30:27 +0200 Subject: idiom for RE matching In-Reply-To: References: <5MidnUx8Mb4DcAPbnZ2dnUVZ_t63nZ2d@comcast.com> <1185157313.356112.159020@z24g2000prh.googlegroups.com> <2f6dnUlUxd2_7TjbnZ2dnUVZ_qy3nZ2d@comcast.com> Message-ID: <46A80743.3020004@freakmail.de> Gordon Airporte wrote: > Yes, that's pseudo code even though I didn't really mean it that way > when I typed it. The actual code uses the proper 'if foo in line or if > bar in line:' form. > One 'if' too many. /W From steve at holdenweb.com Mon Jul 2 16:12:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Jul 2007 16:12:17 -0400 Subject: subprocess -- broken pipe error In-Reply-To: <1183403782.214378.270510@m36g2000hse.googlegroups.com> References: <1183396350.429008.185200@n2g2000hse.googlegroups.com> <1183397577.959518.264230@g4g2000hsf.googlegroups.com> <1183403782.214378.270510@m36g2000hse.googlegroups.com> Message-ID: 7stud wrote: > Why doesn't the following program write to the file? > > driver.py > ------- > import subprocess as sub > > p = sub.Popen(["python", "-u", "test1.py"], stdin=sub.PIPE, > stdout=sub.PIPE) > > > p.stdin.write("text3") > > while True: > pass > ------- > > test1.py: > --------- > import sys > > data = sys.stdin.read() > Let me ask you a question: what conditions have to be true to this statement to terminate? A: the Python driver.py process has to close its output file. Since it doesn't do this (instead writing a little bit of output then going into an infinite loop) the whole thing just sits there consuming CPU time. > f = open("aaa.txt", "w") > f.write(data + "\n") > f.close() > ----------- > > > After I hit Ctrl+C to end the program and look in the file, the text > wasn't written to the file. But, if I change driver.py to the > following it works: > > driver.py: > ---------- > import subprocess as sub > > p = sub.Popen(["python", "-u", "test1.py"], stdin=sub.PIPE, > stdout=sub.PIPE) > > > p.stdin.write("text3") > ------- > > Ok. So that looks like the data is caught in a buffer--even though the > pipes should be unbuffered by default. But this doesn't work: > Who told you pipes should be unbuffered by default, and what difference does that make anyway? The reason it works now is that your program closes its standard output by default when it terminates. > driver.py > ---------- > import subprocess as sub > > p = sub.Popen(["python", "-u", "test1.py"], stdin=sub.PIPE, > stdout=sub.PIPE) > > p.stdin.write("text4") > p.stdin.flush() > > while True: > pass > ------- > > It just hangs, and then when I hit Ctrl+C and look in the file, the > data isn't in there. > Of course it does, for the reasons mentioned above. file.read() only returns when it has consumed *all* the data from the file (which means the write must close the file for the reader to be able to return). 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 star.public at gmail.com Fri Jul 13 16:11:43 2007 From: star.public at gmail.com (star.public at gmail.com) Date: Fri, 13 Jul 2007 13:11:43 -0700 Subject: Pass by reference or by value? In-Reply-To: <1184353832.314694.228270@n60g2000hse.googlegroups.com> References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> Message-ID: <1184357503.509205.171950@k79g2000hse.googlegroups.com> On Jul 13, 3:10 pm, Robert Dailey wrote: > Hi, > > I noticed in Python all function parameters seem to be passed by > reference. ... [And later otherwise, etc, snip] Heya. Go read through the thread from yesterday, title starts with "Understanding Python Functions" -- they go through the whole pass by object, mutable vs immutable stuff pretty well in there. Short possibly bad version: Assigning (inclding to a function var) makes a new name for an object, reassigning (x=...) only changes what the indvidual name (x) means, but changing the object itself (x[n]=..., x.n=..., etc) affects anything that has a name for that object. Names are names, not variables. -- Weaver[0]=Star From marketing-python-bounces at wingware.com Fri Jul 6 06:36:54 2007 From: marketing-python-bounces at wingware.com (marketing-python-bounces at wingware.com) Date: Fri, 06 Jul 2007 04:36:54 -0600 Subject: Auto-response for your message to the "marketing-python" mailing list Message-ID: This mailing list has been retired. Please use the new Python Advocacy mailing list instead: http://mail.python.org/mailman/listinfo/advocacy Thanks! From aleax at mac.com Thu Jul 12 01:02:07 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 11 Jul 2007 22:02:07 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> Message-ID: <1i13w96.kyyobph71qxrN%aleax@mac.com> Donn Cave wrote: > I've wondered if programmers might differ a lot in how much they > dread errors, or how they react to different kinds of errors. That's quite possible. I'm reminded of a by-now commonplace theory, well summarized at : """ The only place you should try "doing it right the first time" is with established, repetitive processes. Beyond that, this quality improvement clich? can kill innovation. A major study from the American Quality Foundation concluded, "We don't do things right the first time. Trial and error -- making mistakes, experiencing failures, and learning from them -- is how we improve. We need mistakes in order to learn; they are an integral part of how we get better." """ If what you wonder about, and the theory mentioned by Clemmer and detailed by the AQF, are both true, then this may help explain why some programmers are fiercely innovative why other, equally intelligent ones, prefer to stick with some plodding, innovation-killing process that only works well for repetitive tasks: the latter group may be the ones who "dread errors", and therefore miss the "making mistakes, experiencing failures, and learning from them" that is "how we improve". Alex From gagsl-py2 at yahoo.com.ar Thu Jul 12 20:15:58 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Jul 2007 21:15:58 -0300 Subject: atexit, sys.exit, sys.exitfunc, reaching end of source code References: <1184192510.343401.13860@57g2000hsv.googlegroups.com> <1184232645.089981.168090@n60g2000hse.googlegroups.com> Message-ID: En Thu, 12 Jul 2007 06:30:45 -0300, carl.dhalluin at gmail.com escribi?: > I am getting quite confused with this SystemExit. > If I register a custom sys.excepthook then it is never invoked > when I do sys.exit(.) No, sys.excepthook won't be called for SystemExit: py> help(sys) Help on built-in module sys: [...] excepthook -- called to handle any uncaught exception other than SystemExit Unfortunately help(sys.excepthook) does not provide the same information, neither the docs for the sys module. (Should be corrected...) -- Gabriel Genellina From bbxx789_05ss at yahoo.com Sun Jul 1 01:26:20 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 30 Jun 2007 22:26:20 -0700 Subject: unicode Message-ID: <1183267580.178435.265640@o61g2000hsh.googlegroups.com> Based on this example and the error: ----- u_str = u"abc\u9999" print u_str UnicodeEncodeError: 'ascii' codec can't encode character u'\u9999' in position 3: ordinal not in range(128) ------ it looks like when I try to display the string, the ascii decoder parses each character in the string and fails when it can't convert a numerical code that is higher than 127 to a character, i.e. the character \u9999. In the following example, I use encode() to convert a unicode string to a regular string: ----- u_str = u"abc\u9999" reg_str = u_str.encode("utf-8") print repr(reg_str) ----- and the output is: 'abc\xe9\xa6\x99' 1) Why aren't the characters 'a', 'b', and 'c' in hex notation? It looks like python must be using the ascii decoder to parse the characters in the string again--with the result being python converts only the 1 byte numerical codes to characters. 2) Why didn't that cause an error like above for the 3 byte character? Then if I try this: --- u_str = u"abc\u9999" reg_str = u_str.encode("utf-8") print reg_str --- I get the output: abc Here it looks like python isn't using the ascii decoder anymore. 2) What determines which decoder python uses? From siona at chiark.greenend.org.uk Fri Jul 20 08:53:10 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 20 Jul 2007 13:53:10 +0100 (BST) Subject: Interpreting os.lstat() References: <1184806559.224636.266500@e9g2000prf.googlegroups.com> <46a057e8$0$19051$9b622d9e@news.freenet.de> Message-ID: =?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?= wrote: >> (a) Running 'stat' is *not the same* as a system call. >Why do you say that? It is *exactly* the same [ ... ] Maybe if stat were implemented as int main(int argc, char** argv) { struct stat so_what_am_I_supposed_to_do_with_this; return stat(argv[1], &so_what_am_I_supposed_to_do_with_this); } But it obviously does a lot of other stuff, including formatting the results of the system call for display. Since what it really at issue here is presentation of the results, I'd say that the stat system call and the stat program wrapping it are very different things. -- \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 arnoreg at gmail.com Tue Jul 10 05:10:56 2007 From: arnoreg at gmail.com (Arno Stienen) Date: Tue, 10 Jul 2007 11:10:56 +0200 Subject: xmlrpclib hangs execution In-Reply-To: <1182162228.246643.135210@u2g2000hsc.googlegroups.com> References: <45AC0631.8080601@ctw.utwente.nl><465890FB.4030405@utwente.nl> <465A9DC7.2010708@gmail.com> <465d9040$0$326$e4fe514c@news.xs4all.nl> <1182162228.246643.135210@u2g2000hsc.googlegroups.com> Message-ID: <46934D20.30802@gmail.com> Hi Andy, Your patches solves the problem too. Thanks! One thing: if I use the unpatched xmlrpclib.py, the printed output of xml calls look like: {'state': 0, 'str': 'Info_RT'} But if I use your patch, they look like: state0strInfo_RT I prefer the former, as it is easier to extract the info. Why did this change with your patch? Bye, Arno. itkovian wrote: > I think a better fix than the one I posted below is using the > HTTPConnection library, as opposed to the HTTP library from httplib. > > A patch can be found below: > > --- /sw/lib/python2.5/xmlrpclib.py 2006-11-29 02:46:38.000000000 > +0100 > +++ xmlrpclib.py 2007-06-15 16:03:17.000000000 +0200 > @@ -1182,23 +1182,13 @@ > self.send_user_agent(h) > self.send_content(h, request_body) > > - errcode, errmsg, headers = h.getreply() > + response = h.getresponse() > + > + if response.status != 200: > + raise ProtocolError(host + handler, response.status, > response.reason, response.msg.headers) > > - if errcode != 200: > - raise ProtocolError( > - host + handler, > - errcode, errmsg, > - headers > - ) > - > - self.verbose = verbose > - > - try: > - sock = h._conn.sock > - except AttributeError: > - sock = None > - > - return self._parse_response(h.getfile(), sock) > + payload = response.read() > + return payload > > ## > # Create parser. > @@ -1250,7 +1240,7 @@ > # create a HTTP connection object from a host descriptor > import httplib > host, extra_headers, x509 = self.get_host_info(host) > - return httplib.HTTP(host) > + return httplib.HTTPConnection(host) > From XX.XmcX at XX.XmclaveauX.com Thu Jul 5 16:26:28 2007 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Thu, 05 Jul 2007 22:26:28 +0200 Subject: IDEs for COM scripting: C# v. Python v. Iron Python v. JPython References: <468c844b$0$27401$ba4acef3@news.orange.fr> <5f3igjF39a72dU1@mid.uni-berlin.de> Message-ID: Hi! > No. The IDIspatch-interface explicitely lists what methods with what > arguments it has. So code completion is possible there as well. Sorry, I think different. In VS, assists use TLB for find methods & arguments. Dynamic-server can't have TLB. Other way for verify : try a Makepy on a COM server write with Python+Pywin32... -- @-salutations Michel Claveau From info at egenix.com Thu Jul 26 11:07:17 2007 From: info at egenix.com (eGenix Team: M.-A. Lemburg) Date: Thu, 26 Jul 2007 17:07:17 +0200 Subject: ANN: eGenix EuroPython 2007 Presentations & Videos Message-ID: <46A8B8A5.80707@egenix.com> ________________________________________________________________________ eGenix EuroPython 2007 Presentations & Videos ________________________________________________________________________ eGenix is pleased to announce the immediate availability of PDF and Flash video versions of the presentations we gave at this years EuroPython 2007 conference in Vilnius. This announcement is also available on our web-site for online reading: http://www.egenix.com/company/news/EuroPython-2007-Presentations.html ________________________________________________________________________ INTRODUCTION The EuroPython Conference is the one of the premier conferences for Python & Zope users and developers. This year it was being held from the 9th to 11th July in Vilnius, Lithuania. eGenix was one of the founding members of the EuroPython conference team and played a major role in organizing the first EuroPython conference in the year 2002. Since then we have attended every EuroPython conference to meet up face-to-face with the people from the Python & Zope communities and have given regular talks at these conferences. ________________________________________________________________________ TALKS AT EUROPYTHON 2007 We gave the following two talks at the conference. The presentations are available for viewing and download from our Presentations and Talks section: http://www.egenix.com/library/presentations/ As special feature, we have added talk videos in addition to providing the slide PDFs. You can view the talks online if you have the Adobe Flash Player 8 or later installed. * Parsing Languages with mxTextTools mxTextTools comes with a high performance Tagging Engine for text and Unicode data which can be used to tokenize and parse languages. The resulting abstract syntax tree can then be hooked up to a generator to build a complete and fast compiler in pure Python. The talk gives a short introduction to the way the mxTextTools Tagging Engine works and how it can be used to build compilers. mxTextTools is an eGenix Open Source product available as part of the eGenix mx Base Distribution. * An introduction to working with relational databases from Zope Although Zope has been around for quite a while, it continues to find new users particularly amongst non-programmers who are looking for a way to work with existing data which is usually in some relational database (PostgreSQL, MySQL, MS SQL, Oracle, DB2, etc.). One of the reasons for this is that Zope provides an extremely powerful, yet secure, through-the-web programming environment. The presentation is directed towards new users and will provide a brief introduction by example into the Zope way of doing things. At the same time it highlights how working within Zope is automatic training in good programming methodology: data management is delegated to ZSQL methods, PythonScripts act as controllers and Zope Page Templates provide the views. Together they encourage modularity and reusability. The sample application and database are available for download. Enjoy, -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Jul 26 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 laurstorage at yahoo.com Tue Jul 10 04:44:09 2007 From: laurstorage at yahoo.com (Laurentiu) Date: Tue, 10 Jul 2007 09:44:09 +0100 (BST) Subject: Transfer folders to ftp In-Reply-To: Message-ID: <896312.73769.qm@web36715.mail.mud.yahoo.com> hi! i am new to python and i made some digging about how to send files and folders to ftp server. i manage to send a file, but i don't know how to send folders with subfolders in it. please, can someone help me to accomplish this tasks: 1. send a folder with subfolders to ftp server. 2. make the program invisible... running hide 3. send only folder that is different to the host i know that this tasks can be easily accomplish with a sync program, but i want to make this in python. thanks a lot ___________________________________________________________ New Yahoo! Mail is the ultimate force in competitive emailing. Find out more at the Yahoo! Mail Championships. Plus: play games and win prizes. http://uk.rd.yahoo.com/evt=44106/*http://mail.yahoo.net/uk From edgardo.delgado at navy.mil Tue Jul 31 15:37:26 2007 From: edgardo.delgado at navy.mil (Delgado, Edgardo CIV NAVAIR 4.1.4.3) Date: Tue, 31 Jul 2007 15:37:26 -0400 Subject: Creating a shared object in python Message-ID: <0C8FBA9C0F70E1479497B4DD7ED592236C5CAF@naeapaxrez05.nadsusea.nads.navy.mil> Is there a way to create a shared object in python? Thx, Edgar From steve at holdenweb.com Thu Jul 26 20:43:27 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Jul 2007 20:43:27 -0400 Subject: code indentation In-Reply-To: <87myxihgkg.fsf@benfinney.id.au> References: <1185297657.186852.136950@k79g2000hse.googlegroups.com> <87lkd5jt83.fsf@benfinney.id.au> <1185357861.989194.117000@r34g2000hsd.googlegroups.com> <1185387723.155661.311510@b79g2000hse.googlegroups.com> <87myxihgkg.fsf@benfinney.id.au> Message-ID: Ben Finney wrote: > Steve Holden writes: > >> We should be making allowances for this particular poster on account >> of relative youth: I hadn't realised earlier, but we are dealing >> with a fourteen-year-old. > > I don't believe that's true. One of the great advantages of discussion > over the internet is that one's behaviour is what is judged, without > necessary prejudice from one's age, skin tone, facial features, or the > like. Set against the many disadvantages of internet discussion, I > think "judge only on basis of behaviour" is a good default. > Fair enough, but I was simply suggesting we cut him some slack, not that we completely ignore any obnoxious behavior we might observe. 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 Xin.Zheng at jpl.nasa.gov Wed Jul 11 14:24:33 2007 From: Xin.Zheng at jpl.nasa.gov (Jason Zheng) Date: Wed, 11 Jul 2007 11:24:33 -0700 Subject: os.wait() losing child? In-Reply-To: <4694903B.8000105@cosc.canterbury.ac.nz> References: <4694903B.8000105@cosc.canterbury.ac.nz> Message-ID: greg wrote: > Jason Zheng wrote: >> Hate to reply to my own thread, but this is the working program that >> can demonstrate what I posted earlier: > > I've figured out what's going on. The Popen class has a > __del__ method which does a non-blocking wait of its own. > So you need to keep the Popen instance for each subprocess > alive until your wait call has cleaned it up. > > The following version seems to work okay. > It still doesn't work on my machine. I took a closer look at the Popen class, and I think the problem is that the __init__ method always calls a method _cleanup, which polls every existing Popen instance. The poll method does a nonblocking wait. If one of my child process finishes as I create a new Popen instance, then the _cleanup method effectively de-zombifies the child process, so I can no longer expect to see the return of that pid on os.wait() any more. ~Jason From tazmaster at rocketmail.com Thu Jul 5 22:18:16 2007 From: tazmaster at rocketmail.com (Jim Langston) Date: Thu, 5 Jul 2007 19:18:16 -0700 Subject: Interfacing python program to C++ program instance Message-ID: <_Dhji.1190$Jw2.323@newsfe04.lga> Windows. Situation: Using a Python program called OpenRPG. I have a program that displays form data (a character sheet) in C++. I am able in the C++ program to build a string and copy it into the clipboard, then paste it into the input in the running Python program. I would like to somehow automate this, that is, have the python instance communicate with the C++ instance and vice versa. I'm still trying to think of a way to do this. There seems to be a number of options, but I'm not sure which one is best, or there is a better one. 1. Write a new C++ program/library with extern C that Python could call. This interface program would open up some shared memory that the C++ application would also open up, and python and C++ could communicate that way. Python writing requests to the memory, C++ responding with responses. 2. Have the C++ program interface directly into the python form, reading directly from controls. C++ could write to the input box with reponses. 3. Have Python write a small file with the request to the HD. Have the C++ program intermittedly check for the presense of this file. If it exists, it would open the file, read the request, write a response file, then delete the file Python wrote. 4. Find out if python can directly, somehow, open up shared memory and do the same as 1 without the need for the extern C interface program. 5. Something else I'm not thinking of but you know. Thanks. From missive at frontiernet.net Fri Jul 13 18:41:04 2007 From: missive at frontiernet.net (Lee Harr) Date: Fri, 13 Jul 2007 22:41:04 GMT Subject: Class decorators do not inherit properly References: <46972b93$0$11779$426a74cc@news.free.fr> Message-ID: <4cTli.12068$ya1.11048@news02.roc.ny> >> I think the term "class decorator" is going to eventually >> mean something other than what you are doing here. I'd >> avoid the term for now. >> >> >> When you decorate a class method, >> the function you use >> needs to be defined before the method definition. > > FWIW, the term "class method" has a > definite meaning in Python. Certainly. But "class decorator" is being introduced in Python 3000 with PEP 3129: http://www.python.org/dev/peps/pep-3129/ From R.Brodie at rl.ac.uk Mon Jul 23 10:46:15 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Mon, 23 Jul 2007 15:46:15 +0100 Subject: Parsing XML with ElementTree (unicode problem?) References: <1185200976.082516.105420@57g2000hsv.googlegroups.com> Message-ID: wrote in message news:1185200976.082516.105420 at 57g2000hsv.googlegroups.com... > so what's the difference? how comes parsing is fine > in the first case but erroneous in the second case? You may have guessed the encoding wrong. It probably wasn't utf-8 to start with but iso8859-1 or similar. What actual byte value is in the file? > 2. there is another problem that might be similar I get a similar > error if the content of the (locally saved) xml have special > characters such as '&' Either the originator of the XML has messed up, or whatever you have done to save a local copy has mangled it. From horpner at yahoo.com Mon Jul 16 11:27:00 2007 From: horpner at yahoo.com (Neil Cerutti) Date: Mon, 16 Jul 2007 15:27:00 GMT Subject: Private functions and inheritance References: <1184596318.146981.242830@n60g2000hse.googlegroups.com> Message-ID: On 2007-07-16, Maciej Blizi?ski wrote: > Hello, > > I've come across something that I don't quite understand about > Python's inheritance. Consider the following code snippet: > > class A(object): > def call_bar(self): return self.bar() > def call___bar(self): return self.__bar() > def __bar(self): return "A::__bar()" > def bar(self): return "A::bar()" > class B(A): > def __bar(self): return "B::__bar()" > def bar(self): return "B::bar()" > > b = B() > print "calling B::call_bar():", b.call_bar() > print "calling B::call___bar():", b.call___bar() > > The result is: > > calling B::call_bar(): B::bar() > calling B::call___bar(): A::__bar() the __* naming convention for class private attributes is intended to "help ensure" that attribute names of derived classes cannot conflict with private attribute names in any base classes. I.e., you should not use that naming convention when you *intend* to override it in a derived class. If you do use the __* naming convention, use it only for attributes that should not be overrided or accessed by derived classes. the weasel words from the documentation (which I put in quotes) are there because the feature doesn't work (in all cases). -- Neil Cerutti The doctors X-rayed my head and found nothing. --Dizzy Dean From lachlan.gunn at internode.on.net Thu Jul 12 05:35:19 2007 From: lachlan.gunn at internode.on.net (Lachlan Gunn) Date: Thu, 12 Jul 2007 09:35:19 -0000 Subject: Anonymous Classes References: <139bkaf7m30iu49@corp.supernews.com> <4695ec04$0$8947$426a74cc@news.free.fr> Message-ID: <139btenljg6lia9@corp.supernews.com> Thanks for your help. After trying your suggestion for a while, I eventually realised that SQLObject was doing something funny in its metaclass that was causing the issue, which I got around by mangling the class names with a counter. From evan at yelp.com Mon Jul 30 12:59:21 2007 From: evan at yelp.com (Evan Klitzke) Date: Mon, 30 Jul 2007 09:59:21 -0700 Subject: making a variable available in a function from decorator In-Reply-To: References: <5h5e3lF3hmufcU1@mid.uni-berlin.de> Message-ID: On 7/30/07, rkmr.em at gmail.com wrote: > is it possible to do this without passing it as a function argument? > Sort of. Functions are objects in python, so you can set attribute on them. E.g. def foo(): return foo.c foo.c = 1 print foo() Which will print 1. Of course, it would generally be better to write your own class for this sort of thing, so that you can set the variable in the instance scope. -- Evan Klitzke From byte8bits at gmail.com Thu Jul 26 16:24:52 2007 From: byte8bits at gmail.com (brad) Date: Thu, 26 Jul 2007 16:24:52 -0400 Subject: question about math module notation In-Reply-To: <46a901c5$0$25771$9b622d9e@news.freenet.de> References: <46a901c5$0$25771$9b622d9e@news.freenet.de> Message-ID: Stargaming wrote: > Explicitly converting it to `int` works for me. (Without the 3-digit- > block notation, of course.) Thank you! From Eric_Dexter at msn.com Tue Jul 10 19:56:07 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Tue, 10 Jul 2007 16:56:07 -0700 Subject: trouble controlling vim with subprocess on windows machine In-Reply-To: <1184081889.194824.214960@22g2000hsm.googlegroups.com> References: <1183970186.663847.4380@o61g2000hsh.googlegroups.com> <1184023825.646120.251060@d55g2000hsg.googlegroups.com> <5qFki.19733$2v1.4163@newssvr14.news.prodigy.net> <1184058013.324624.220540@i38g2000prf.googlegroups.com> <1184081889.194824.214960@22g2000hsm.googlegroups.com> Message-ID: <1184111767.111472.15390@o61g2000hsh.googlegroups.com> On Jul 10, 10:38 am, "Eric_Dex... at msn.com" wrote: > On Jul 10, 4:00 am, agc wrote: > > > > > > > Hi Josiah, > > > > >> This recipe for asynchronous communication usingsubprocesscould be > > > >> used to write an expect-like tool: > > > >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 > > > I have played with the above recipe and it is excellent, > > but could you please go into some more detail about what is needed > > to make a cross platform [p]expect like (non-pty based) tool? > > > Specifically, could you describe how you would connect to > > *another* interactive Python process with your subclass of > > subprocess.Popen? > > i.e: > > > a = Popen('python', stdin=?, stdout=?, stderr=?) > > #now run an interactive session with 'a' > > > I have tried several combinations of the above and I seem > > to be stuck on the fact that python is interacting with a > > 'tty', not 'std*'. Maybe I'm missing a basic piece? > > > Thanks for any input, > > Alex > > > > >> It works on both Windows and *nix. > > > > >> - Josiah > > > > > I had the original dir work but when I tried to trade it out withvim > > > > it isn't clear > > > > how I should call it.. vimfilename and it doesn't find filename for > > > > some reason. > > > > I called it pipe and then > > > > > inport pipe > > > > > def load_instrument3(instr_name, csd_name): > > > > if sys.platform == 'win32': > > > > shell, commands, tail = ('gvim' + csd_name, (csd_name, > > > > csd_name), '\r\n') > > > > else: > > > > shell, commands, tail = ('sh', ('ls', 'echo HELLO WORLD'), > > > > '\n') > > > > > a = pipe.Popen(shell, stdin=pipe.PIPE, stdout=pipe.PIPE) > > > > print pipe.recv_some(a), > > > > for cmd in commands: > > > > pipe.send_all(a, csd_name) > > > > print pipe.recv_some(a), > > > > pipe.send_all(a, csd_name) > > > > print pipe.recv_some(a, e=0) > > > > a.wait() > > > > The example uses a platform-specific shell in order to use the > > > environment variable PATH to discover the executable to run. If you > > > know the exact path to your binary ('gvim' for you), it should work. > > > As-is, your program would require a binary with the name 'gvim'+csd_name > > > in the same path as the script you are executing. > > > > - Josiah- Hide quoted text - > > > - Show quoted text - > > I gave this a shot with a windows batch file (although I am not sure I > am doing it right) > > path c:\program files\vim\vim71 > path c:\dex tracker > gvim bay-at-night.csd > echo \intsr | gvim > echo \ | gvim > echo :r strings.orc | gvim > pause > > and it just pulls up gvim bay-at-night.csd and never does the two > searches or pulls up the file. I do have a windows version of sh if > that works better.- Hide quoted text - > > - Show quoted text - since there are alot of questions about subprocess I will suggest http://www.rutherfurd.net/python/sendkeys/ this emulates the keyboard for windows.. I am not sure if it works yet, From steve at REMOVE.THIS.cybersource.com.au Mon Jul 30 19:49:01 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Tue, 31 Jul 2007 09:49:01 +1000 Subject: Fwd: Re: Comparing Dictionaries References: Message-ID: On Mon, 30 Jul 2007 14:06:29 -0500, Kenneth Love wrote: > >>From: "Steven D'Aprano" >>Newsgroups: comp.lang.python >>Subject: Re: Comparing Dictionaries >>Date: Sat, 28 Jul 2007 10:21:14 +1000 >>To: python-list at python.org >> >>On Fri, 27 Jul 2007 14:11:02 -0500, Kenneth Love wrote: >> >> > The published recipe (based on ConfigParser) did not handle my INI >> > files. I have periods in both the section names and the key names. >> > The INI files contents were developed according to an internally >> > defined process that other non-Python programs rely on. The published >> > recipe *did not work* with this scenario. >> >>I think you have made a mistake. ConfigParser as published certainly DOES >>accept periods in section and option names. It just *works*. > > The recipe I'm using is based upon ConfigParser and creates a dictionary > that is based on the contents of the INI file. The dictionary's key is > based on the section name and the key name from the INI file. The two > are concatenated with a separator. > > In the original recipe, the separator is a period. To use your example > (deleted as an attempt at brevity), the dictionary would be: > > { "SECTION.FRED.option.wilma" : "45" } Well, that's just broken. "Flat is better than nested" is only true when things are actually better flat rather than nested. The right way to build a dictionary from an INI file is with nested dictionaries: {"SECTION1": {"option1": 20, "option2": 30}, "SECTION2": {"option1", 2.0, "option2": 3.0}} That treats each section as a single piece. But if you absolutely insist on flattening the dictionary, the right way is not to concatenate the section name and the option name into a single string, but to use a tuple ("SECTION", "option"). [snip] > In no way did I rewrite ConfigParser. I have a real job with time > pressures and I'm not so arrogant as to think I could whip something > up in an hour that would be anywhere close to correct. > > I see that I wasn't as clear as I thought I was in my original post > as you are second person to think I was developing my own INI solution. Copying somebody else's code and modifying it is still recreating an existing solution. Python has an INI file parser. What does it not do that you have to recreate it by creating your own version? Oh, ironically, the recipe you borrowed in fact uses the Python ConfigParser to do all the heavy work. All it really does is flatten the ConfigParser nested dictionary into a flat dictionary. I fail to see the advantage. > All I wanted to know was "How do I compare two dictionaries to see if > they are equal?". Yes, but I suspect what you _wanted_ to know and what you _needed_ to know are different. -- Steven. From steve at holdenweb.com Mon Jul 9 14:50:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 09 Jul 2007 14:50:58 -0400 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Thu, 05 Jul 2007 17:57:32 -0300, Wojtek escribi?: > >> Note: Since I am using the year 9999 as a "magic number", some of you >> may think that I am repeating the Y2K problem. Hey, if my application >> is still being used in the year 9998 I am not being paid nearly >> enough... > > I would not say the code itself, but some design decisions may survive for > a long time. Like the railroad inter-rail distance, which even for the > newest trains, remains the same as used by Stephenson in England two > centuries ago - and he choose the same width as used by common horse carts > at the time. (Some people goes beyond that and say it was the same width > as used in the Roman empire but this may be just a practical coincidence, > no causality being involved). > Brunel, of course, being an original, built his system with a wider inter-rail gap, and passengers commented on the smoother ride they got. But standardization wars aren't new, and IKB lost that one. 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 Jul 26 12:32:16 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Jul 2007 12:32:16 -0400 Subject: first, second, etc line of text file In-Reply-To: <1185457346.458799.55360@j4g2000prf.googlegroups.com> References: <1185394350.032814.262990@d55g2000hsg.googlegroups.com> <1185457346.458799.55360@j4g2000prf.googlegroups.com> Message-ID: Mike wrote: > On Jul 26, 8:46 am, "Daniel Nogradi" wrote: >>>> A very simple question: I currently use a cumbersome-looking way of >>>> getting the first, second, etc. line of a text file: >>>> for i, line in enumerate( open( textfile ) ): >>>> if i == 0: >>>> print 'First line is: ' + line >>>> elif i == 1: >>>> print 'Second line is: ' + line >>>> ....... >>>> ....... >>>> I thought about f = open( textfile ) and then f[0], f[1], etc but that >>>> throws a TypeError: 'file' object is unsubscriptable. >>>> Is there a simpler way? >>> If all you need is sequential access, you can use the next() method of >>> the file object: >>> nextline = open(textfile).next >>> print 'First line is: %r' % nextline() >>> print 'Second line is: %r' % nextline() >>> ... >>> For random access, the easiest way is to slurp all the file in a list >>> using file.readlines(). >> Thanks! This looks the best, I only need the first couple of lines >> sequentially so don't need to read in the whole file ever. > > if you only ever need the first few lines of a file, why not keep it > simple and do something like this? > > mylines = open("c:\\myfile.txt","r").readlines()[:5] > > that will give you the first five lines of the file. Replace 5 with > whatever number you need. next will work, too, obviously, but won't > that use of next hold the file open until you are done with it? Or, > more specifically, since you do not have a file object at all, won't > you have to wait until the function goes out of scope to release the > file? Would that be a problem? Or am I just being paranoid? > Unfortunately the expression f.readlines()[:5] reads the whole file in and generates a list of the lines just so it can slice the first five off. Compare that, on a large file, with something like [f.next() for _ in range(5)] and I think you will see that the latter is significantly better in almost all respects. 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 deets at nospam.web.de Mon Jul 9 10:31:39 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 09 Jul 2007 16:31:39 +0200 Subject: catching empty strings (I guess that's what they are) References: Message-ID: <5fev6bF3bcgoiU2@mid.uni-berlin.de> brad wrote: > I've began accepting user input :( in an old program. The input comes > from a simple text file where users enter filenames (one per line). What > is the appropriate way to handle blank lines that hold whitespace, but > not characters? Currently, I'm doing this: > > for user_file in user_files: > # Remove whitespace and make lowercase. > file_skip_list.append(user_file.strip().lower()) > > file_skip_list = list(sets.Set(file_skip_list)) > > However, if the input file has blank lines in it, I get this in my list: > > '' (that's two single quotes with noting in between) > > I thought I could do something like this: > > if user_file == None: > pass > > Or this: > > if user_file == '': > pass > > But, these don't work, the '' is still there. Any suggestions are > appreciated! They are still there because you perform the stripping and lowercasing in the append-call. Not beforehand. So change the code to this: for uf in user_files: uf = uf.strip().lower() if uf: file_skip_list.append(uf) Diez From hniksic at xemacs.org Mon Jul 9 10:24:46 2007 From: hniksic at xemacs.org (Hrvoje Niksic) Date: Mon, 09 Jul 2007 16:24:46 +0200 Subject: What is the most efficient way to test for False in a list? References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <7x7ipajvst.fsf@ruckus.brouhaha.com> <5fejp2F3cp3igU1@mid.individual.net> <5feju0F3c7pd1U1@mid.uni-berlin.de> <87tzsd21ld.fsf@mulj.homelinux.net> <1183989753.501355.70810@k79g2000hse.googlegroups.com> Message-ID: <87ir8t1wpd.fsf@mulj.homelinux.net> Paul McGuire writes: >> >>> False in [3, 2, 1, 0, -1] >> >> True # no False here>>> all([3, 2, 1, 0, -1]) >> >> False # false value present, not necessarily False > > I think if you want identity testing, you'll need to code your own; I'm aware of that, I simply pointed out that "False in list" and any(list) are not equivalent and where the difference lies. >>>> any(map(lambda _ : _ is False,[3,2,1,0,-1])) Note that you can use itertools.imap to avoid the unnecessary intermediate list creation. Even better is to use a generator expression: >>> any(x is False for x in [3, 2, 1, 0, -1]) False >>> any(x is False for x in [3, 2, 1, 0, -1, False]) True From jeffober at gmail.com Wed Jul 25 16:00:28 2007 From: jeffober at gmail.com (Jeff) Date: Wed, 25 Jul 2007 20:00:28 -0000 Subject: first, second, etc line of text file In-Reply-To: References: Message-ID: <1185393628.573678.27040@k79g2000hse.googlegroups.com> Files should be iterable on their own: filehandle = open('/path/to/foo.txt') for line in filehandle: # do something... But you could also do a generic lines = filehandle.readlines(), which returns a list of all lines in the file, but that's a bit memory hungry. From bdesth.quelquechose at free.quelquepart.fr Sat Jul 21 07:47:23 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Jul 2007 13:47:23 +0200 Subject: classmethod & staticmethod In-Reply-To: References: <1185247145.678362.75150@i38g2000prf.googlegroups.com> <46a5b2ad$0$18903$426a74cc@news.free.fr> Message-ID: <46a66363$0$483$426a74cc@news.free.fr> Alex Popescu a ?crit : > Bruno Desthuilliers wrote > in news:46a5b2ad$0$18903$426a74cc at news.free.fr: > > > >>[snip...] >> >> >>Not necessarily - you can access class attributes from within an >>instance method (but obviously a classmethod cannot access instance >>attributes). >> > > What I am doing wrong here then: > > class MyClass(object): > class_list = ['a', 'b'] > > def instance_method(self): > print "instance_method with class list %s" % class_list > > o = MyClass() > o.instance_method() > > Traceback (most recent call last): > File "", line 1, in > File "", line 4, in instance_method > NameError: global name 'class_list' is not defined The answer is in the error message. There's no local definition of 'class_list' in function 'instance_method', and no global definition of 'class_list' in the module. If you want to access MyClass.class_list in function instance_method, you need to use a fully qualified name, ie either self.class_list[1], self.__class__.class_list[2], type(self).class_list[3] or MyClass.class_list[4] [1] this one is ok in 'read mode' since attributes not found in the instance's __dict__ will be looked up in the class's __dict__ (and then in parent's classes __dict__), but be warned that something like 'self.class_list = []' will create an instance attribute of the same name, shadowing the class one. This is one of the (in)famous Python gotchas. [2] && [3] Those two ones are equivalent. [3] is cleaner since it avoids direct access to an implementation attribute, but [2] is faster since it avoids a function call. In both cases, the lookup will be what one would expect in OO, that is first on the concrete class, then in the parents classes. [4] Only use this one if you really want to bypass inheritance. From attn.steven.kuo at gmail.com Mon Jul 30 19:33:54 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: Mon, 30 Jul 2007 16:33:54 -0700 Subject: What is the "functional" way of doing this? In-Reply-To: <1185835690.530367.66600@m37g2000prh.googlegroups.com> References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> Message-ID: <1185838434.596591.132640@d30g2000prg.googlegroups.com> On Jul 30, 3:48 pm, beginner wrote: > 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. > Recursion is common in functional programming: def f(n, l=None): if l == None: l = [] if n > 0: return f(n/26, l + [n%26]) else: return l print f(1000) -- Hope this helps, Steven From urbangabo at gmail.com Fri Jul 13 08:32:17 2007 From: urbangabo at gmail.com (Gabor Urban) Date: Fri, 13 Jul 2007 14:32:17 +0200 Subject: The Modernization of Emacs: terminology buffer and Message-ID: Hullo, I was just wondering if this thread was whithering out...... I gues not for a good time. A short summary in the hope for the last posting in this topic. Some provocative posting caused or Twister brother to send a large amount of doubtful info. It seems, he had some very bad experience with an undefined version of so called 'emacs'. Or he was not able to win against his prejudice. On the other hand most of the users of the true, standard and canonical Emacs (and Xemacs as well) were able to point out his factual errors and misconceptions. (BTW Xemacs is not for X11... just eXtended...... :-)) ) But, for God's sake.... this is Python list. Would like to stick to it? Back to Python... which version is to be used in production environment? Sincerely yours, gabaux -------------- next part -------------- An HTML attachment was scrubbed... URL: From mensanator at aol.com Mon Jul 16 19:07:03 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 16 Jul 2007 16:07:03 -0700 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: References: <1184042559.120947.124560@k79g2000hse.googlegroups.com> <1184050285.997766.299860@d55g2000hsg.googlegroups.com> <1184351416.166930.290710@k79g2000hse.googlegroups.com> <1184362323.476796.22570@w3g2000hsg.googlegroups.com> Message-ID: <1184627223.569011.242340@w3g2000hsg.googlegroups.com> On Jul 15, 4:28 pm, Wayne Brehaut wrote: > On Fri, 13 Jul 2007 14:32:03 -0700, "mensana... at aol.com" > wrote: > >On Jul 13, 2:52 pm, Wayne Brehaut wrote: > >> On Fri, 13 Jul 2007 11:30:16 -0700, Paul McGuire > >> wrote: > > >> >On Jul 13, 1:20 pm, Wayne Brehaut wrote: > >> >> On Mon, 09 Jul 2007 23:51:25 -0700, "mensana... at aol.com" > > >> >> wrote: > >> >> >On Jul 9, 11:42?pm, Paul McGuire wrote: > >> >> >> On Jul 9, 11:21 pm, "Jim Langston" wrote:> In Python 2.5 on intel, the statement > >> >> >> > 2**2**2**2**2 > >> >> >> > evaluates to>>> 2**2**2**2**2 > > === 8< === > > >> >> >Did you count the 'L'? > > >> >> numdigits(n)? > > >> >> What? 'L' is a digit in Python? I'm going back to Fortran! > > >> >> wwwayne > > === 8< === > > >> >'L' counts for 50, but only when you use Roman font. > > >> WTL?! Not Times New Roman I hope? > > >> Now I'll have to extend my remarks below to include: > > >> L**L**L > >> D**D**D > >> M**M**M > >> etc. (since I don't recall what comes next) > > >> though these (L, D, M, ...) would seem to be numbers rather than > >> digits: the Romans used a base-1 system > > >No, "base" refers to a Positional Number system for which > >radix 1 is undefined. > > >You can call Roman Numerals a Tally System of Radix 1. > > I can call it what I want--within reason-- Noted. > so long as those I'm mainly > addressing understand what I mean and the context in which I'm saying > it. As I note in my other response to your response below, my remark > was intended to be humorous, and everyone else who responded took it > that way. But this is comp.lang.python, not sci.math. And in that context "base" implies positional number system. To assume anything else is not within reason. > > There's no need to get all formal in such a context, and there's no > harm in defining a tally system to be 1-based or to be a base-1 > system. You do know that "radix 1" is the proper usage? Since "base 1" is meaningless in some contexts? Programming languages tend to be a bit anal about syntax, so yes, you do need to get all formal. > If I had intended this to be a formal discussion instead of > just having a little fun (and sorry for doing that) I would have > instead said: "Define a base-1 number system as...". > > Since you clearly don;t want to accept my terminology and assume > there's just one right one, please seehttp://www.psinvention.com/zoetic/basenumb.htmfor an independent > opinion of the reasonableness of using this term: "Base Valued Numbers I prefer Knuth's "The Art of Computer Programming" where these things are presented formally rather than the informality of some stupid web page. > > Any use of numbers implies the use of a base value for the numbers. > The simplest base value to use in a numbering scheme is '1'." And I didn't say you couldn't use it. Just not with positional number systems. > > Because we're most familiar with the use of the term "base" in the > context of positional notation in no way implies that's the only > possible context in which it can be used And I didn't say it was the only context. But since this context happens to be Python, that argument is moot. > --or has been used--with > perfectly clear meaning. So the Roman system was based on the number > 1 and was, therefore, 1-based or base-1. You should say "radix 1" to be unambiguous. > > Even in the context of positional systems it's perfectly clear what a > base-1 system would be and the fact that it's generally excluded isn;t > because it's not cleaar what it weould be, but only that most assume > it isn't of any uise, An assumption that is, in fact, true. > so exclude it. As we all know: Oh boy, here we go. And you were doing so good up to this point. > > 1^0 = 1 > 1^1 = 1 > 1^n = 1 for any positive natural number > [and negative natural numbers don't exist, but extension to negative > integers is left as an exercise for the reader] > > In the base 1 positional number system, what is the value of: > > 1 > 11 > 111 > 1...1 (with n 1s)? These numbers don't exist in a positional number system of radix 1. > > And would the value be any different if I wrote them: > > 1 > 11 > 111 > 1...1 (with n 1s)? No, because they don't exist either. > > In pictures: > > Pos? ? > Value 1 > Digit 1 > > Pos? ? ? > Value 1 1 > Digit 1 1 > > Pos? ? ? ? > Value 1 1 1 > Digit 1 1 1 > > Pos? ? ... ? > Value 1 ... 1 (n positions) > Digit 1 ... 1 (n 1s) > > >Tally sytems ARE defined for radix 1, but operate > >completely different from positional systems. > > Clearly, the algorithm to find the value of a base-1 number is to > multiply the value of each position (1) by the digit in that position > (1) and add the results--just as you would do for any other positional > system. > > One common assumption for excluding base-1 is that this can't be a > proper positional number system because there's no zero digit, How is it you know this and still get it wrong? > so how > can we represent the 0 value of a position? You can't. Period. > The obvious answer is that > there is no way of knowing what power of 1 each position represents > anyway, Huh? The power IS the position! > since the value of each and every position is 1, Each position is a_p*base**p where p is the position and "a" taken from the set of digits[:base]. With base=1, there can only be one "a". > so we just > leave out positions whose value is zero; What makes you think there are any? > equivalently, we just admit > that the base-1 tally system is equivalent to the base-1 positional > system so far as counting is concerned, since we don't count things > that aren't there. There aren't any things that aren't there. There are an infinite number of positions a_p*base**p and since EVERY a_p is 1, and every base**p is 1 (at least you got that right), EVERY position is 1*1**p. The only number that can be represented is infinity. You can't have a 0 equivalent (whether actual or by hiding), otherwise you would have radix 2. You can only have a 0 if digits=[0]. But then the only number you can represent is 0. Having only infinity or 0 isn't very useful. THAT'S why radix 1 is undefined for positional number systems. Your lame attempt to circumvent this would be called "crackpot" over in sci.math. > > I claim this demonstrates that your statement is incorrect: The demonstration contains a fallacy. > so far as > counting or representing a count is concerned the base-1 tally system > is the base-1 positional system, and is the base-1 system I claim > Roman numerals represent using various shorthand symbols and rules > (like subtracting the value of lesser-valued symbols when immediately > to the left of a higher-valued one--and this is a loose description, > so please don't look for counter-examples to prove me wrong here too). Ok, I won't look for counter-examples. BTW, that rule was invented in the Middle Ages, the Romans didn't use it so you don't have to either. > > Of course, by "operate completely different from positional systems" > you may have meant that when you go beyond counting to operations on > and between such numbers the usual rules and algorithms of positional > systems don't apply--but what has that to do with counting the number > of digits in a number respresented in this base-1 system? The count will always be infinity. But I was refering to addition being done by concatenation, which is different than how positional number systems do addition. You should try it sometime. It's fairly easy when you drop the Middle Ages rule. > An > arithmetic on numbers (whether written using a positional system or > not) is a completely different animal than the base set of objects > themselves, and doesn't alter the fact of whether the numbers are or > aren't written in a positional notation! As long as the radix isn't 1. > > And the p-adic numbers (http://en.wikipedia.org/wiki/P-adic_number) > also use a positional notation, but don't follow what you would > probably regard as "the only true rules and algorithms" of a > positional notation; so there's no such thing as "_the_ positional > notation". And Python doesn't use p-adic numbers. > > But I digress (but only because provoked!)... Sorry, didn't know you had a hair up your ass. > > >> [for purposes of this argument, at least] > > This statement is the informal equivalent to saying "Define a base-1 > number system as...", as I noted above. You may have noted it, but you didn't define it. > If you'd noted this, and understood it, I understood that what you said was wrong. > or were willing to accept it whether or not you > understood it, Why would I accept what I don't understand? Because YOU say so? > you'd have saved us both some bother-- Others read these threads. If only one person learns something, then it's not bother. > but me more than you I guess, Yeah, a real shame. Better to be thought a fool than to open one's mouth and remove all doubt. > so maybe you were just trolling? Of course not. Not everyone has read Knuth. I'm just pointing out that your positional number system of radix 1 is simply a crackpot concept mathematically and you're doing a disservice to the newbies. > > wwwayne From http Mon Jul 9 11:05:14 2007 From: http (Paul Rubin) Date: 09 Jul 2007 08:05:14 -0700 Subject: What is the most efficient way to test for False in a list? References: <1183938194.761283.97950@57g2000hsv.googlegroups.com> <7x7ipajvst.fsf@ruckus.brouhaha.com> <5fejp2F3cp3igU1@mid.individual.net> <5feju0F3c7pd1U1@mid.uni-berlin.de> Message-ID: <7xsl7xmxcl.fsf@ruckus.brouhaha.com> "Diez B. Roggisch" writes: > >> status = all(list) > > > > Am I mistaken, or is this no identity test for False at all? > > You are mistaken. all take an iterable and returns if each value of it is > true. all(list) does what the OP's code did, tests for the presence of a false value in the list. If you want an identity test, use status = not (False in list) From http Tue Jul 24 01:56:44 2007 From: http (Paul Rubin) Date: 23 Jul 2007 22:56:44 -0700 Subject: code packaging References: <7xfy3jpem8.fsf_-_@ruckus.brouhaha.com> <87y7h9n7lk.fsf@pobox.com> Message-ID: <7xsl7e73ab.fsf@ruckus.brouhaha.com> jjl at pobox.com (John J. Lee) writes: > You can go further: in addition to developing a Debian package (or a > few of them) for your own project, build your OS image using > debootstrap (you'll probably want your own local repository(ies), for > reproducibility). Then you do your development in a virtual machine > or chroot environment. That way you develop in the same (or very > similar) environment to the one in which your code will eventually be > deployed (one difference being the use of an version control checkout > rather a .deb install for the code you're actually working on, unless > troubleshooting problems that are somehow tied up with that particular > aspect of deployment). I've seen this working in a real-world > project. Thanks for these suggestions. Buildbot (per Ben Finney) looks interesting as does the above, and Ryan's notes about experience with Windows installers is also appreciated. Whether lot of build automation would have been worth it at the beginning of the thing I'm working on or not, we probably need to move towards it now that more of the system is running. From gopi420 at gmail.com Tue Jul 17 19:31:26 2007 From: gopi420 at gmail.com (Anmolads) Date: Tue, 17 Jul 2007 16:31:26 -0700 Subject: A new Classifieds Website has been Launched. Message-ID: <1184715086.197943.66940@z28g2000prd.googlegroups.com> A new Classifieds Website has been Launched. Place Full page Ad for free at Anmolads.com http://www.Anmolads.com Get your desired Job from our Job Portal... www.Anmoljobs.com/forum Logon to www.anmolads.com for further details. Place Full Page For Free at www.Anmolads.com , www.earnyourcash.com , www.eternaldating.com , www.voiptechnocrats.com/forum0020, www.anmoljobs.com/forum From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Jul 24 14:09:00 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 24 Jul 2007 20:09:00 +0200 Subject: From D References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> Message-ID: <5gmthsF3hc0n2U1@mid.individual.net> Stargaming wrote: > On Tue, 24 Jul 2007 03:19:53 -0700, bearophileHUGS wrote: >> While in a syntax like: >> for i in xrange(1_000_000): >> my eyes help me group them at once. > > Sounds like a good thing to be but the arbitrary positioning > doesnt make any sense. Checking underscore positions would only add complexity. Why not just ignore them, no matter where they are? > Additionally, I'd suggest 10**n in such cases (eg. 10**6). This fails if you happen to have more than only zeros at the right side. Regards, Bj?rn -- BOFH excuse #97: Small animal kamikaze attack on power supplies From bbxx789_05ss at yahoo.com Sat Jul 14 12:47:15 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Sat, 14 Jul 2007 09:47:15 -0700 Subject: Installing mod_python on mac os 10.4.7 Message-ID: <1184431635.014748.291030@q75g2000hsh.googlegroups.com> The mod_python manual says this under section 2.1 Prerequisites: ------ In order to compile mod_python you will need to have the include files for both Apache and Python, as well as the Python library installed on your system. If you installed Python and Apache from source, then you already have everything needed. However, if you are using prepackaged software (e.g. Red Hat Linux RPM, Debian, or Solaris packages from sunsite, etc) then chances are, you have just the binaries and not the sources on your system. Often, the Apache and Python include files and libraries necessary to compile mod_python are part of separate ``development'' package. If you are not sure whether you have all the necessary files, either compile and install Python and Apache from source, or refer to the documentation for your system on how to get the development packages. ----- I installed Apache from source using these instructions: http://switch.richard5.net/isp-in-a-box-v2/installing-apache-on-mac-os-x/ but I used a package to install python 2.4. The package was from here: http://www.pythonmac.org/packages/ and it's a "Universal binary version of Python that runs natively on PPC and Intel systems." But my mac came with Python 2.3.5 pre-installed, so I wonder if I already have the necessary "include files for both Apache and Python, as well as the Python library" already installed. From http Wed Jul 4 17:32:21 2007 From: http (Paul Rubin) Date: 04 Jul 2007 14:32:21 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <5dveb4F360un0U1@mid.individual.net> <1182858785.886469.93060@n60g2000hse.googlegroups.com> <46824d8d$0$2324$426a74cc@news.free.fr> <4682eddc$0$23164$426a74cc@news.free.fr> <5ehokpF38ov3jU2@mid.individual.net> <4683d5cd$0$8993$426a74cc@news.free.fr> <7xps3e3g9x.fsf@ruckus.brouhaha.com> <468565a0$0$3686$426a74cc@news.free.fr> <7xhcopj10g.fsf@ruckus.brouhaha.com> <46863ea7$0$970$426a34cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <468c0827$0$22906$426a74cc@news.free.fr> Message-ID: <7x3b03lusa.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > Haskell - as other languages using type-inference like OCaml - are in > a different category. Yes, I know, don't say it, they are statically > typed - but it's mostly structural typing, not declarative > typing. Which makes them much more usable IMHO. Some users in fact recommend writing an explicit type signature for every Haskell function, which functions sort of like a unit test. That doesn't bloat the code up noticibly. The conciseness of those languages comes more from polymorphism and convenient ways of writing and using higher-order functions, than from type inference. > Still, static typechecking is not a garantee against runtime > errors. Nor against logical errors. Right, however the reality is it does seem to prevent a lot of surprises. There's even an intermediate language (a language generated by a compiler as an intermediate step towards emitting machine code) called Henk, in which EVERY value is type-annotated (and in a very fancy type system too). The author reports that the annotations have been very helpful for noticing compiler bugs. > I'd have to see a concrete use case. And I'd need much more real-world > experience with some ML variant, but this is not something I can > expect to happen in a near future - it's difficult enough to convince > PHBs that Python is fine. Monad Reader #7 has an article about some Wall street company using ML: http://www.haskell.org/sitewiki/images/0/03/TMR-Issue7.pdf see the article by Yaron Minsky. From vasudevram at gmail.com Fri Jul 20 14:48:57 2007 From: vasudevram at gmail.com (vasudevram) Date: Fri, 20 Jul 2007 18:48:57 -0000 Subject: Python MAPI In-Reply-To: <1184954229.222401.213380@k79g2000hse.googlegroups.com> References: <1184954229.222401.213380@k79g2000hse.googlegroups.com> Message-ID: <1184957337.367674.104760@i13g2000prf.googlegroups.com> On Jul 20, 10:57 pm, kyoso... at gmail.com wrote: > Hi, > > I've been googling all over and can't find any good answers about this > problem. I would like to create some kind of MAPI interface with > Python such that when I open Microsoft Word (or another Office > program) and click File, Send To, Mail Recipient it opens a program I > wrote in Python and uses it to send the email rather than Outlook. > > The closest I've come is finding the registry key HKLM\Software\Clients > \Mail which seems to control the default email client. I did figure > out how to redirect mailto directives on websites to my program > successfully, but this is a whole 'nother ballgame. > > Any suggestions are welcome. I am considering writing some VBA hooks > in Office Apps in question, but would prefer to avoid that. > > Thanks! > > Mike > > P.S. Currently using Python 2.4, wxPython 2.8.3 (for GUI) on Windows > XP Pro. Hi, 1: I don't know much about Windows APIs, but am currently reading the "Windows Internals" book. Got this idea from it: Go to http://www.microsoft.com/technet/sysinternals/default.mspx and check out the SysInternals utilities there. The book says that you can use some of them to "spy" on what an app is doing - what registry keys it is reading/writing, lots of other OS-level calls it makes as it runs. Digging around and using some of these utilities to check out what an Office app does when you use it to send mail, might help you figure out a way to do what you want. 2. Try looking for registry entries specific to Office Apps, and look under those subtrees for likely email-related entries to modify (if you haven't tried that already). I guess you already know that fiddling with the registry can be risky and can crash your system, so take backups, etc. Using COM via Python may also help - again, some digging required. You probably already have the PyWin32 Python extensions for Windows COM (earlier called win32all - see http://wiki.python.org/moin/Win32All) - if not, its available here: http://www.python.org/download/releases/2.4.4/ (scroll down the page for the link) Vasudev Ram www.dancingbison.com jugad.livejournal.com sourceforge.net/projects/xtopdf From aleax at mac.com Wed Jul 4 00:03:51 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 3 Jul 2007 21:03:51 -0700 Subject: ActivePython References: <5f0g54F396io7U1@mid.individual.net> Message-ID: <1i0p0l1.152ee0mcffr6aN%aleax@mac.com> Frank Swarbrick wrote: > Why might one choose to use ActivePython instead of using the free CPython? I believe ActivePython is also free, and it's packaged up differently (with more 3rd party modules accompanying it than the standard Python distribution), which might make it attractive to some. Also, I believe ActivePython is also available as a pre-built binary for some platforms for which CPython is only distributed as sources (e.g., Solaris), and again this difference may be seen as favorable by some. Alex From steve at holdenweb.com Mon Jul 23 13:41:35 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Jul 2007 13:41:35 -0400 Subject: decorators tutorials In-Reply-To: <1185200309.234308.152290@z24g2000prh.googlegroups.com> References: <1185178383.499234.299850@z24g2000prh.googlegroups.com> <1185180112.321457.73170@n2g2000hse.googlegroups.com> <1185183257.471106.318070@x35g2000prf.googlegroups.com> <877iorkz80.fsf@benfinney.id.au> <1185200309.234308.152290@z24g2000prh.googlegroups.com> Message-ID: james_027 wrote: > Hi, > >>> def check_login(func): >>> def _check_login(*args): >>> print "I am decorator" >>> return func(*args) >>> return _check_login >>> @check_login >>> def method2(input): >>> print "I am method TWO. Input %s" % input >> That looks okay. What is unclear? >> > > It just look complicated than using a simple function like this > def check_login(msg): > #... > def my_func(toto, tata): > #... > > #call it like this > check_login('msg') > my_func('toto', 'tata') > > I hope I could be able to understand clearly the decorators and use it > to it efficiently > Unfortunately your example isn't equivalent to the decorator version. The decorator syntax actually calls the decorator function using the following function as its argument, then replaces the function definition on with the result of the call on the decorator. Your example just calls two functions one after the other without any relationship being established between 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 ninja.krmenadl at nes.com Sun Jul 8 03:35:44 2007 From: ninja.krmenadl at nes.com (Boris Ozegovic) Date: Sun, 8 Jul 2007 09:35:44 +0200 Subject: httplib module References: Message-ID: Steve Holden wrote: >>> Why do I get double new lines when geting data from server? Example: > How? It's customary to include details when you've solved your own > problem in case someone else gets the same issue. Ok. In do_GET I had this two lines: for line in file: print line As you can see, print inserted another \n. :-) Correct code is: for line in file: print line, -- Ne dajte da nas la?ljivac Bandi? truje: http://cnn.blog.hr/arhiva-2007-06.html#1622776372 From ptmcg at austin.rr.com Thu Jul 5 10:29:06 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: Thu, 05 Jul 2007 07:29:06 -0700 Subject: The best platform and editor for Python In-Reply-To: References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183644537.859604.27790@w5g2000hsg.googlegroups.com> Message-ID: <1183645746.239349.68260@n2g2000hse.googlegroups.com> On Jul 5, 9:21 am, Roy Smith wrote: > In article <1183644537.859604.27... at w5g2000hsg.googlegroups.com>, > Nicola Musatti wrote: > > > On Jul 5, 1:23 pm, Gregor Horvath wrote: > > [...] > > > That's a property of open source projects. > > > Features nobody really needs are not implemented. > > > No, no, you got it all wrong. It's in *commercial* projects that > > features nobody really needs are not implemented. > > No, no, squared. In a commercial project, the only features that get > implemented are the ones somebody is willing to pay for. Whether there is > any correlation between need and willingness to pay is an open question. Then tell us, pray, who was willing to pay for the epitome of useless features in MS Word, that Useless Features' Useless Feature, the ability to format text with the animated effect "Marching Red Ants"? I'm sure I paid for it, but it wasn't willingly... -- Paul From steve at holdenweb.com Thu Jul 26 23:00:38 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Jul 2007 23:00:38 -0400 Subject: instantiate a 'classobj' In-Reply-To: <1185501791.311662.220980@57g2000hsv.googlegroups.com> References: <1185501791.311662.220980@57g2000hsv.googlegroups.com> Message-ID: <46A95FD6.9020906@holdenweb.com> westymatt wrote: > I have a class where a parameter to its constructor is a type(param) = > 'classobj'. How would I go about instantiating that given it has no > constructor. > Just call the parameter: if it's of type classobj then it's callable, and calling it will create an instance of the class. >>> class MyClass: ... def __init__(self, a, b): ... self.a = a ... self.b = b ... >>> MyClass >>> type(MyClass) >>> def builder(c): ... return c(3, 4) ... >>> builder(MyClass) <__main__.MyClass instance at 0x7ff281cc> >>> 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 Mon Jul 30 14:10:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 30 Jul 2007 15:10:30 -0300 Subject: problems with logging module References: <1185744598.663382.126920@19g2000hsx.googlegroups.com> <1185778252.177411.286660@k79g2000hse.googlegroups.com> Message-ID: En Mon, 30 Jul 2007 03:50:52 -0300, Alia Khouri escribi?: > But I'm not letting the logging module off, it's still not the easiest > or most intuitive module to work with. > > For example: a basic Log class that can be programatically configured > would be quicker to work with then messing around with three different > classes types if you want to get beyond basicConfig functionality: > (Logger, handlers, formatters) To be able to do this would be nice: > > from logging import Log > > class MyClass: > def __init__(self, x): > self.x = x > self.log = Log( > level=logging.DEBUG, > format="%(asctime)s %(levelname)s: %(message)s", > datefmt = '%H:%M:%S', > filename='app.log', > filemode='a' > ) You are not going beyond basicConfig - I'd write the above as: logging.basicConfig(...) def __init__(self, x): self.x = x self.log = logging.getLogger("a.nice.name") If you *do* need more than a handler, or different formatters for different loggers, then you must write your own setup anyway; perhaps using logging.config files, or perhaps writing your own code. I can't think of a simple and generic approach (beyond what basicConfig provides) but if you can write something that other people find useful, feel free to submit a patch. -- Gabriel Genellina From james.harris.1 at googlemail.com Wed Jul 4 19:04:10 2007 From: james.harris.1 at googlemail.com (James Harris) Date: Wed, 04 Jul 2007 16:04:10 -0700 Subject: Portable general timestamp format, not 2038-limited In-Reply-To: References: <1182544384.709759.235300@o11g2000prd.googlegroups.com> <1183574760.225389.266470@o61g2000hsh.googlegroups.com> Message-ID: <1183590250.478207.139190@k79g2000hse.googlegroups.com> On 4 Jul, 22:18, "Peter J. Holzer" wrote: ... > But it really doesn't matter much. If you ignore leap seconds, using > days instead of seconds is just a constant factor (in fact, the unix > timestamp ignores leap seconds, too, so it's always a constant factor). > You can't represent a second exactly if the unit is one day (1/86400 is > not a multiple of a power of two), but that probably doesn't matter. Sure. However, the proposal was to define ticks as 25 microseconds. From B.Ogryczak at gmail.com Thu Jul 12 10:14:40 2007 From: B.Ogryczak at gmail.com (Bart Ogryczak) Date: Thu, 12 Jul 2007 14:14:40 -0000 Subject: lists and dictionaries In-Reply-To: References: Message-ID: <1184249680.684670.290650@k79g2000hse.googlegroups.com> On 11 jul, 21:08, Ladislav Andel wrote: > Hi, > I have a list of dictionaries. > e.g. > [{'index': 0, 'transport': 'udp', 'service_domain': 'dp0.example.com'}, > {'index': 1, 'transport': 'udp', 'service_domain': 'dp1.example.com'}, > {'index': 0, 'transport': 'tcp', 'service_domain': 'dp0.example.com'}, > {'index': 1, 'transport': 'tcp', 'service_domain': 'dp1.example.com'}] > > how could I make a new list of dictionaries which would look like: > [{'transports': ['udp','tcp'], 'service_domain': 'dp0.example.com'}, > {'transports': ['udp','tcp'], 'service_domain': 'dp1.example.com'}] > > Could you help me, please? doms = {} for entry in oldList: doms.setdefault(entry['service_domain'], []).append(entry['transport']) newList = [{'transports': t, 'service_domain': d} for d,t in doms.iteritems()] From missive at frontiernet.net Thu Jul 12 18:11:10 2007 From: missive at frontiernet.net (Lee Harr) Date: Thu, 12 Jul 2007 22:11:10 GMT Subject: How to create new files? References: <1184274877.612434.26870@k79g2000hse.googlegroups.com> Message-ID: <2Gxli.11989$ya1.9248@news02.roc.ny> > So far, I've found that unlike with the C++ version of fopen(), the > Python 'open()' call does not create the file for you when opened > using the mode 'w'. I get an exception saying that the file doesn't > exist. Works for me... :~$ mkdir foo :~$ cd foo :foo$ ls :foo$ python Python 2.4.4 (#2, Apr 5 2007, 20:11:18) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('bar', 'w') >>> f.write('test\n') >>> f.close() >>> :foo$ ls bar :foo$ cat bar test :foo$ You're going to have to show us the actual code you used and the actual error message you are getting. > Also, you might notice that my "self.m_file.read()" function is wrong, > according to the python docs at least. read() takes the number of > bytes to read, however I was not able to find a C++ equivalent of > "sizeof()" in Python. If I wanted to read in a 1 byte, 2 byte, or 4 > byte value from data into python I have no idea how I would do this. Are you trying to read in unicode? Generally in python, you do not concern yourself with how much space (how many bytes) a particular value takes up. You may want to look at how the pickle module works. From http Sat Jul 14 03:02:30 2007 From: http (Paul Rubin) Date: 14 Jul 2007 00:02:30 -0700 Subject: PEP 3107 and stronger typing (note: probably a newbie question) References: <468565a0$0$3686$426a74cc@news.free.fr> <1i0ikru.1uccqtm1efnzn3N%aleax@mac.com> <1i0n0tr.ve0o791347ugyN%aleax@mac.com> <7xd4za1086.fsf@ruckus.brouhaha.com> <5f0mhuF3b0stbU1@mid.individual.net> <7xd4z837e2.fsf@ruckus.brouhaha.com> <468b7426$0$9063$426a34cc@news.free.fr> <7x4pkkun56.fsf@ruckus.brouhaha.com> <1183575597.272150.152200@w5g2000hsg.googlegroups.com> <7xzm2budfv.fsf@ruckus.brouhaha.com> <7xir8vju1l.fsf@ruckus.brouhaha.com> <7xvecumrte.fsf@ruckus.brouhaha.com> <1i13w96.kyyobph71qxrN%aleax@mac.com> <7xwsx63we6.fsf@ruckus.brouhaha.com> <878x9llv5x.fsf@benfinney.id.au> Message-ID: <7xodifo4c9.fsf@ruckus.brouhaha.com> Ben Finney writes: > This seems to make the dangerous assumption that the programmer has > the correct program in mind, and needs only to transfer it correctly > to the computer. Well, I hope the programmer can at least state some clear specficiations that a correct program should implement, e.g. it should not freeze or crash. > I would warrant that anyone who understands exactly how a program > should work before writing it, and makes no design mistakes before > coming up with a program that works, is not designing a program of any > interest. I'm not sure what the relevance of this is. Programmers generally have an idea of what it is that they're trying to write. They then have to make a bunch of design and implementation decisions as they go along. Soemtimes those decisions are subtly incorrect, and the more errors the computer can identify automatically, the fewer errors are likely to remain in the program. > Certainly. Which is why the trend continues toward developing programs > such that mistakes of all kinds cause early, obvious failure -- where > they have a much better chance of being caught and fixed *before* > innocent hands get ahold of them. Here is what Edward Lee wrote about developing a multi-threaded Java app (http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1.pdf): A part of the Ptolemy Project experiment was to see whether effective software engineering practices could be developed for an academic research setting. We developed a process that included a code maturity rating system (with four levels, red, yellow, green, and blue), design reviews, code reviews, nightly builds, regression tests, and automated code coverage metrics [43]. The portion of the kernel that ensured a consistent view of the program structure was written in early 2000, design reviewed to yellow, and code reviewed to green. The reviewers included concurrency experts, not just inexperienced graduate students (Christopher Hylands (now Brooks), Bart Kienhuis, John Reekie, and myself were all reviewers). We wrote regression tests that achieved 100 percent code coverage. The nightly build and regression tests ran on a two processor SMP machine, which exhibited different thread behavior than the development machines, which all had a single processor. The Ptolemy II system itself began to be widely used, and every use of the system exercised this code. No problems were observed until the code deadlocked on April 26, 2004, four years later. It is certainly true that our relatively rigorous software engineering practice identified and fixed many concurrency bugs. But the fact that a problem as serious as a deadlock that locked up the system could go undetected for four years despite this practice is alarming. How many more such problems remain? How long do we need test before we can be sure to have discovered all such problems? Regrettably, I have to conclude that testing may never reveal all the problems in nontrivial Multithreaded code. Now consider that the code you test today on a 2-core processor may be running on a 100-core processor in 4 years, making any concurrency errors that much worse. You can't test on the 100-core cpu today because it doesn't exist yet, but your code still has to run on it correctly once it's out there. Heck, if you're writing in CPython (no parallelism at all, due to the GIL) you might be in for a surprise as soon as real parallelism arrives on even 2 cores. It gets worse, maybe you're writing operating system or language runtime code (e.g. parallel garbage collector for Java). That means there will be hostile code on the same machine, written by diabolical maniacs who know every detail of your implementation, and who deliberately do stuff (e.g. write code to hit specific cache lines or cause page faults at fiendishly precisely chosen moments) specifically to cause weird timing conditions and trigger bugs. Testing is not enough to ensure that such attacks won't succeed. I remember an old programming book (might even have been Knuth vol. 3) recommending using the Shell sorting algorithm (a very simple exchange sort that runs in about O(n**1.4) time) instead of an O(n log n) algorithm because Shell's algorithm (being simpler) was less likely to end up with implementation errors. Today I think an experienced programmer needing to code a sort routine wouldn't hesitate to code a good algorithm, because our languages and coding/testing methods are better than they were in the Fortran and assembly language era when that book was written. But there are still more complex problems (like shared memory multiprocessing) that we're advised to stay away from because they're so fraught with hazards. We instead use approaches that are simpler but take perforamnce penalties. (As a non-concurrency example, we might implement geometric search through some kind of list scanning algorithm instead of using more efficient but complicated k-d trees). With higher reliability languages we'll hopefully be in better shape to tackle those complex problems instead of retreating from them, without expecting to spend eternity hunting down mysterious bugs. From sjmachin at lexicon.net Thu Jul 26 09:13:41 2007 From: sjmachin at lexicon.net (John Machin) Date: Thu, 26 Jul 2007 06:13:41 -0700 Subject: Parsing XML with ElementTree (unicode problem?) In-Reply-To: <1185449094.998635.67870@w3g2000hsg.googlegroups.com> References: <1185200976.082516.105420@57g2000hsv.googlegroups.com> <1185279975.254458.7510@57g2000hsv.googlegroups.com> <1185287404.060182.314750@57g2000hsv.googlegroups.com> <46A618E9.6010304@web.de> <1185449094.998635.67870@w3g2000hsg.googlegroups.com> Message-ID: <1185455621.498620.51650@i13g2000prf.googlegroups.com> On Jul 26, 9:24 pm, oren.t... at gmail.com wrote: > OK, I solved the problem but I still don't get what went wrong. > Solution - use tree builder in order to create the new xml file > (previously I was "manually" creating it). > > I'm still curious so I'm adding a link to a short and very simple > script that gets an xml (containing non ascii chars) from the web and > saves some of the elements to 2 different local xml files - one is > created by XMLWriter and the other is created manually. you could see > that parsing of the first local file is OK while parsing of the > "manually" created xml file fails. obviously I'm doing something wrong > and I'd love to learn what. > > the toy script:http://staff.science.uva.nl/~otsur/code/xmlConversions.py > Simple file comparison: File 1: ... Modern Church. <p>The book ... File 2: ... Modern Church.

    The book ... Firefox: XML Parsing Error: mismatched tag. Expected:

    . Location: file:///C:/junk/myDeVinciCode166_2.xml Line Number 3, Column 1153: The...Church.

    The...thrill. ------------------------------------------^ From david at boddie.org.uk Thu Jul 26 13:13:45 2007 From: david at boddie.org.uk (David Boddie) Date: Thu, 26 Jul 2007 19:13:45 +0200 Subject: Scope PyQt question Message-ID: <200707261913.45774.david@boddie.org.uk> On Thu Jul 26 18:00:44 CEST 2007, dittonamed wrote: > On Jul 26, 10:15 pm, Stargaming wrote: > > Answering from a non-Qt point of view (ie. I don't know if there were > > cleaner ways using Qt stuff), you have to bind p somewhere not local to > > the function. Any attribute of `self` (that's hopefully not used by > > QMainWindow) should be fine. [...] > I was having trouble getting that to work and thought it because of > event driven nature of gui/qt programming. But i'll give it another go > anyway .. any examples? ;-) from qt import * class Form2(QMainWindow): def __init__(self,parent = None,name = None,fl = 0): QMainWindow.__init__(self,parent,name,fl) self.statusBar() def playAudio(self): self.p = QProcess(self, 'player') playcmd = '/usr/bin/play' filename = 'song.ogg' self.p.addArgument(playcmd) self.p.addArgument(filename) self.p.start() def stopAudio(self): self.p.kill() > Im wondering what the "right" way to do this is - the Qt way, or is > what you mentioned in fact the "right" way? Can i access the QObject > another way or am i barking up the wrong tree? If you store the process in the instance of Form2, you don't need to access it via the object tree. Most Qt programs (in C++) would also use the same approach. You _can_ access the process via the object tree, as you discovered - it's just less convenient to do it that way. Just to satisfy your curiosity, let's look at your code again: ''' #This is just to show that i can "see" the object, though i #dont know how to "access" it #the output shows the QProcess object by name... # but how do i reference it?? allobjs = list(QObject.objectTrees()) for obj in allobjs: objName = QObject.name(obj) if objName == 'Form2': print QObject.children(obj) ''' When you obtain the Form2 instance, you could inspect its children, testing whether each one is a QProcess object with either Python's isinstance() function or QObject's inherits() method. Alternatively, you could use QObject's queryList() method or the qt_find_obj_child() function. With PyQt4, QObject has a findChild() method to perform these kinds of searches. Still, I'd recommend just keeping a reference to the process in your Form2 instance. David From steven.klass at gmail.com Mon Jul 9 16:19:19 2007 From: steven.klass at gmail.com (rh0dium) Date: Mon, 09 Jul 2007 20:19:19 -0000 Subject: A clean way to program an interface In-Reply-To: <1184000380.457434.316970@g4g2000hsf.googlegroups.com> References: <1183957402.819499.227350@o11g2000prd.googlegroups.com> <5feidnF3au460U1@mid.uni-berlin.de> <1183989399.366239.250850@g4g2000hsf.googlegroups.com> <5feuvvF3bcgoiU1@mid.uni-berlin.de> <1184000380.457434.316970@g4g2000hsf.googlegroups.com> Message-ID: <1184012359.352835.147960@o61g2000hsh.googlegroups.com> On Jul 9, 9:59 am, Paul McGuire wrote: > I believe the OP is talking about "interface" as in "hardware > interface", using some form of serial communication. His example does > not use pyserial, but it does refer to a "UnidenConnection" class, > with parameters such as bitrate, port, etc. for what looks like serial > communication. Yes - You are correct UnidenConnection is nothing more than a pyserial connection which handles all of the setup and returns (converting strings to list objects etc). > Some general comments: > > 1. Much of the OP's use of sys._getframe().f_code.co_name coincides > with his naming of certain methods with the same name as the command > to be sent down the serial line. "STS", "EPG", "PRG", "SIN", etc. are > all 3-character command codes that get sent down the wire, along with > the appropriate values for the particular command. While many of > these routines have *some* code in common, only a few have their > entire method body duplicated with one or more other methods. > Refactoring a couple of these into code closures, you can get: > > @staticmethod > def makeStatusCheckCommandFunction(cmd): > def fn(self): > return ( self.uniden.write(cmd)[0]=="OK" ) > return fn > PRG = makeStatusCheckCommandFunction("PRG") > EPG = makeStatusCheckCommandFunction("EPG") > > @staticmethod > def makeCmdFunction(cmd,attrname): > def fn(self): > setattr(self, attrname, int(self.PRGWrite(cmd)[0])) > return getattr(self,attrname) > return fn > SCT = makeCmdFunction("SCT","systems") > SIH = makeCmdFunction("SIH","sih") > SIT = makeCmdFunction("SIT","sit") Hmm very interesting - I've never played with code closures. Very cool - I need to learn me about these thingy's :) > Now there is no sys._getframe().f_code.co_name legerdemain going on, > the command strings are just passed along as the argument cmd, and the > functions themselves are named the same for some level of self- > documentation and/or convenience. > > For the remaining methods, I declare a local variable named cmd and > assign to it the write mnemonic. Yes, I know it violates DRY ("Don't > Repeat Yourself"), but it avoids the getframe() stuff and again, is at > least a snippet of self-documentation. > > 2. This code for reading and unpacking all the non-blank values feels > ugly: > > cmd = "SIF" > if args is None: > p=self.PRGWrite("%s,%s" % (cmd,idx)) > t={} > t["site_type"],t["name"],t["quick_key"],t["hld"],t["lout"],\ > t["mod"],t["att"],t["cch"],t["apco"],t["threshold"],\ > t["rev_index"],t["fwd_index"],t["sys_index"],t["chn_head"], > \ > t["chn_tail"],t["seq_no"],t["start_key"],t["latitude"],\ > t["longitude"],t["range"],t["gps_enable"],t["rsv"]=p > > delitems=[] > for item in t: > if t[item]=="": delitems.append(item) > for x in delitems: del t[x] > > How about this instead?: > > cmd = "SIF" > if args is None: > p=self.PRGWrite("%s,%s" % (cmd,idx)) > names = "site_type name quick_key hld lout mod att cch "\ > "apco threshold rev_index fwd_index sys_index "\ > "chn_head chn_tail seq_no start_key latitude " \ > "longitude range gps_enable rsv".split() > > t = dict( k,v for k,v in zip(names,p) if v != "" ) This is absolutely the right way to do this - I totally like this - Super!! > HTH, > -- Paul Hey thanks a lot!! From zyzhu2000 at gmail.com Tue Jul 31 15:11:38 2007 From: zyzhu2000 at gmail.com (beginner) Date: Tue, 31 Jul 2007 19:11:38 -0000 Subject: standalone process to interact with the web In-Reply-To: References: <1185899130.331170.151980@e16g2000pri.googlegroups.com> <1185904623.754078.198910@e9g2000prf.googlegroups.com> Message-ID: <1185909098.952860.217190@j4g2000prf.googlegroups.com> On Jul 31, 1:11 pm, Steve Holden wrote: > beginner wrote: > > Hi Steve, > > > On Jul 31, 11:42 am, Steve Holden 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 - > > >> http://wwwsearch.sourceforge.net/mechanize/ > > >> With mechanize and its partner ClientForm you can rule the web world ;-) > > >> 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 ------------- > > > 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. > > Well, surely in that case you can use any protocol you like. It's up to > the web server and your "web server server" to agree how to communicate. > Take a look at the SocketServer library, for example. > > regartds > 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 - 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. Thanks, Geoffrey From zentraders at gmail.com Sat Jul 28 00:08:53 2007 From: zentraders at gmail.com (Zentrader) Date: Fri, 27 Jul 2007 21:08:53 -0700 Subject: Tkinter -- Show Data in an Excel like Read-Only Grid In-Reply-To: <1185573410.087935.146830@d30g2000prg.googlegroups.com> References: <1185573410.087935.146830@d30g2000prg.googlegroups.com> Message-ID: <1185595733.188575.275680@m37g2000prh.googlegroups.com> On Jul 27, 2:56 pm, beginner wrote: > Hi All, > > I am really new to Tk and Tkinter. I googled the web but it was not > mentioned how to build a data grid with Tkinter. > > Basically, I want to show an excel like data grid with fixed column > and row headers and sortable columns. But the grids can be read-only. > > Can anyone give some hint on implementing this? > > Thanks, > beginner See if tkTable will help http://tkinter.unpythonic.net/wiki/TkTable From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Jul 9 13:59:56 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 09 Jul 2007 19:59:56 +0200 Subject: Class file location References: Message-ID: <5ffbcsF3b1ie7U1@mid.individual.net> axjacob at comcast.net wrote: > Is there a way to define a different directory for the generated > .class(*$py.class) files than the current directory where the > python scripts are located and executed from? Excuse me, since when does python generate .class files? Regards, Bj?rn -- BOFH excuse #439: Hot Java has gone cold From steve at REMOVE.THIS.cybersource.com.au Fri Jul 27 20:25:58 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Jul 2007 10:25:58 +1000 Subject: adding a docstring to an instancemethod References: <1185361537.733690.238280@k79g2000hse.googlegroups.com> <1185438522.978804.118010@19g2000hsx.googlegroups.com> <1185472092.427646.266270@g4g2000hsf.googlegroups.com> Message-ID: On Fri, 27 Jul 2007 06:24:48 -0300, Gabriel Genellina wrote: > En Thu, 26 Jul 2007 14:48:12 -0300, jelle > escribi?: > >> Hi Gabriella, >> thanks for pointing me in the right direction: > > Twice in a week... I'll have to revise my own masculinity... You need to spit and fart a lot in your posts, and talk about sport. Either that, or change your name to Sylar and eat people's brains. -- Steven. From emin.shopper at gmail.com Thu Jul 19 09:25:50 2007 From: emin.shopper at gmail.com (Emin.shopper Martinian.shopper) Date: Thu, 19 Jul 2007 09:25:50 -0400 Subject: How do you debug when a unittest.TestCase fails? In-Reply-To: <32e43bb70707181442h56f471b3we818ad9a403d4733@mail.gmail.com> References: <32e43bb70707181340u7e4b545bp1f025c941b40134e@mail.gmail.com> <20070718210454.4947.853567445.divmod.quotient.13123@ohm> <32e43bb70707181442h56f471b3we818ad9a403d4733@mail.gmail.com> Message-ID: <32e43bb70707190625u4fba3fafg45d7856556ea1844@mail.gmail.com> After poking around the unittest source code, the best solution I could come up with was to do >>> import unittest; unittest.TestCase.run = lambda self,*args,**kw: unittest.TestCase.debug(self) before running my tests. That patches things so that I can use pdb.pm() when a test fails. Still, that seems like an ugly hack and I would think there is a better solution... Thanks, -Emin On 7/18/07, Emin.shopper Martinian.shopper wrote: > > Thanks for the reply, but neither of those work for me. I don't seem to > have the "trial" program installed. Where do you get it? > > Also, when I use the try/catch block, I get the following error: > > Traceback (most recent call last): > File "_test.py", line 10, in > pdb.pm() > File "c:\python25\lib\pdb.py", line 1148, in pm > post_mortem(sys.last_traceback) > AttributeError: 'module' object has no attribute 'last_traceback' > > > On 7/18/07, Jean-Paul Calderone wrote: > > > > On Wed, 18 Jul 2007 16:40:46 -0400, "Emin.shopper Martinian.shopper" > > wrote: > > >Dear Experts, > > > > > >How do you use pdb to debug when a TestCase object from the unittest > > module > > >fails? Basically, I'd like to run my unit tests and invoke pdb.pm when > > >something fails. > > > > > >I tried the following with now success: > > > > > >Imagine that I have a module _test.py that looks like the following: > > > > > >----------------------- > > >import unittest > > >class MyTest(unittest.TestCase): > > > def testIt(self): > > > raise Exception('boom') > > >if __name__ == '__main__': > > > unittest.main() > > >----------------------- > > > > > >If I do > > >>>>import _test; _test.unittest() > > > > > >no tests get run. > > > > > >If I try > > >>>>import _test; t = _test.MyTest() > > > > > >I get > > > > > >Traceback (most recent call last): > > > File "", line 1, in > > > File "c:\python25\lib\unittest.py", line 209, in __init__ > > > (self.__class__, methodName) > > >ValueError: no such test method in : runTest > > > > > >If I try > > >>>>import _test; t = _test.MyTest(methodName='testIt'); t.run() > > > > > >nothing happens. > > > > I use `trial -b ', which automatically enables a bunch of nice > > > > debugging functionality. ;) However, you can try this, if you're not > > interested in using a highly featureful test runner: > > > > try: > > unittest.main() > > except: > > import pdb > > pdb.pm () > > > > This will "post-mortem" the exception, a commonly useful debugging > > technique. > > > > Jean-Paul > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From XX.XmcX at XX.XmclaveauX.com Tue Jul 3 14:35:44 2007 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Tue, 03 Jul 2007 20:35:44 +0200 Subject: python 3.0 or 3000 ....is it worth waiting??? Newbie Question References: <468a8dc1$0$27406$ba4acef3@news.orange.fr> <5evhnqF39v66mU4@mid.uni-berlin.de> Message-ID: Hi! >> non-Ascii characters in identifiers > > And this change may be already in a Python 2.x before P3K. Good new! (if it's True...) -- @-salutations Michel Claveau From steve at holdenweb.com Mon Jul 30 06:54:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 30 Jul 2007 06:54:24 -0400 Subject: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why? In-Reply-To: <1185791793.141118.44080@x35g2000prf.googlegroups.com> References: <1185791793.141118.44080@x35g2000prf.googlegroups.com> Message-ID: <46ADC360.20209@holdenweb.com> Gilbert Fine wrote: > This is a very strange exception raised from somewhere in our program. > I have no idea how this happen. And don't know how to reproduce. It > just occurs from time to time. > > Can anyone give me some suggestion to fix this? > If it's raised from "somewhere in your program" the first this to do is disable the except clause that is apparently stopping you from getting a full traceback, then post that traceback with an appropriate code snippet. People on this list are good at guessing, but it's better to give then some hard information to work with. Otherwise you are calling the shop (garage?) and saying "My car doesn't work, can you tell me how to fix it, please?" 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 willmaier at ml1.net Sat Jul 14 14:39:08 2007 From: willmaier at ml1.net (Will Maier) Date: Sat, 14 Jul 2007 13:39:08 -0500 Subject: getting text inside the HTML tag In-Reply-To: References: Message-ID: <20070714183908.GF821@lass.lfod.us> On Sat, Jul 14, 2007 at 05:47:22PM +0000, Nikola Skoric wrote: > I'm using sgmllib.SGMLParser to parse HTML. I have successfuly > parsed start tags by implementing start_something method. But, now > I have to fetch the string inside the start tag and end tag too. I > have been reading through SGMLParser documentation, but just can't > figure that out... You need to define handle_data. You may also want to look at HTMLParser in addition to the alternatives previously mentioned. http://docs.python.org/lib/module-sgmllib.html -- [Will Maier]-----------------[willmaier at ml1.net|http://www.lfod.us/] From roy at panix.com Thu Jul 5 10:21:13 2007 From: roy at panix.com (Roy Smith) Date: Thu, 05 Jul 2007 10:21:13 -0400 Subject: The best platform and editor for Python References: <1183317054.513102.127950@q69g2000hsb.googlegroups.com> <1183380558.135204.83790@e16g2000pri.googlegroups.com> <1183398645.511107.258700@n2g2000hse.googlegroups.com> <1183630730.251890.238900@m36g2000hse.googlegroups.com> <1183644537.859604.27790@w5g2000hsg.googlegroups.com> Message-ID: In article <1183644537.859604.27790 at w5g2000hsg.googlegroups.com>, Nicola Musatti wrote: > On Jul 5, 1:23 pm, Gregor Horvath wrote: > [...] > > That's a property of open source projects. > > Features nobody really needs are not implemented. > > No, no, you got it all wrong. It's in *commercial* projects that > features nobody really needs are not implemented. No, no, squared. In a commercial project, the only features that get implemented are the ones somebody is willing to pay for. Whether there is any correlation between need and willingness to pay is an open question. From see at signature.invalid Wed Jul 11 16:17:19 2007 From: see at signature.invalid (Douglas Wells) Date: Wed, 11 Jul 2007 16:17:19 -0400 (EDT) Subject: asyncore and OOB data References: <1184172867.420979.215300@q75g2000hsh.googlegroups.com> Message-ID: In article <1184172867.420979.215300 at q75g2000hsh.googlegroups.com>, billiejoex writes: > In an asyncore based FTP server I wrote I should be able to receive > OOB data from clients. > A client sending such kind of data should act like this: > > >>> import socket > >>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > >>> s.connect(('127.0.0.1', 21)) > >>> s.sendall('hello there\r\n', socket.MSG_OOB) > > According to asyncore documentation I should handle this kind of event > in "handle_expt" method of dispatcher class, that should be called > when OOB is received by the underlying socket. I've tried to override > handle_expt method in such way: > > def handle_expt(self): > print "OOB data arrived" > data = self.socket.recv(1024, socket.MSG_OOB) > print data > > ...but, even if it is called, "data" contains only a "\n" character > instead of the entire string ("hello there\r\n"). > Why does this happen? Should I have to use a different approach? You should use a different approach, but first you need to read the relevant documentation. I've never used asyncore, but when I look at the documentation, the only reference that I find to OOB says: "Called when there is out of band (OOB) data for a socket connection. This will almost never happen, as OOB is tenuously supported and rarely used." That should be fair warning. Second, when I look at the FTP specification, I don't find the concept of OOB anywhere. So, it's not clear what OOB data would mean in terms of the defined FTP commands in any case. Third, the TCP protocol, which you have selected via the SOCK_STREAM option doesn't support OOB at all, so there's no way that you can even send OOB data in the manner that you are expecting. Let's switch to the positive, however. What TCP does have is the concept of "urgent" data. Urgent data is data that the sender believes is so important that the receiver should discard intermediate data, if necessary, in order to process the urgent data -- but the urgent data is sent *in-band*. In the case of FTP, the concept of urgent data is used to allow the user side to interrupt the data transfer, which it does by sending an ABOR command. The underlying problem is that the server might be blocked on a receive on the data connection and not listening for commands on the control connection. So the user side is required to perform some "special action" that includes sending urgent data, which the server can then process specially. This problem arises primarily in systems without either threading or asynchronous I/O APIs. Your use of asyncore should alleviate this problem. The thing that may be confusing you is that for whatever reason the designers of the Berkeley socket API (which is what you are using when running under POSIX/Linux/MS Windows), chose to use the OOB flags (e.g., MSG_OOB) to indicate the *transmission* of OOB data -- but it's not really OOB data. In fact, when I attempt to receive using the MSG_OOB flag using the OS interfaces on my system, I get back an error (EINVAL - Invalid argument). I would expect that asyncore would report this error somehow or other. In summary, you almost certainly can't use the concept of a separate OOB channel to transfer data in an FTP environment. If you really, really need something like this, you will need to extend the FTP protocol for your special purposes. - dmw -- . Douglas Wells . Connection Technologies . . Internet: -sp9804- -at - contek.com- . From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Jul 3 07:47:55 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 03 Jul 2007 13:47:55 +0200 Subject: Programming Idiomatic Code In-Reply-To: References: <468a0768$0$14120$426a74cc@news.free.fr> Message-ID: <468a373a$0$22943$426a74cc@news.free.fr> Nathan Harmston a ?crit : > HI, (snip) > I have one question though: > > Using a module global for this kind of data is usually a bad idea > (except eventually for run-once throw-away scripts, and even then...) > > Why is this a bad idea? Don't you have any idea ? From gagsl-py2 at yahoo.com.ar Thu Jul 12 20:50:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Jul 2007 21:50:23 -0300 Subject: 2**2**2**2**2 wrong? Bug? References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> <1184173446.779276.250530@k79g2000hse.googlegroups.com> <1184182757.797808.206480@d55g2000hsg.googlegroups.com> Message-ID: En Thu, 12 Jul 2007 07:30:05 -0300, Nick Craig-Wood escribi?: > Gabriel Genellina wrote: >> En Wed, 11 Jul 2007 16:39:17 -0300, Paul McGuire >> escribi?: >> >> > As was >> > pointed out earlier, left-associativity with exponentiation is of >> > little value, since (2**3)**2 is the same as 2**(3*2) or 2**6=64. >> >> Just for curiosity: This helps to find the answer to the problem >> "Which is >> the largest number that can be written with only 3 digits?" >> Some people stop at 999, others try 99**9 and 9**99, and the winner is >> 9**9**9, or: > > Actually I think 9**9E9 is bigger! But you have to use an "E", or write "...x10?" in standard "paper-and-pen" mathematical notation. The idea was to use *only* digits. -- Gabriel Genellina From david at boddie.org.uk Fri Jul 27 10:58:53 2007 From: david at boddie.org.uk (David Boddie) Date: Fri, 27 Jul 2007 16:58:53 +0200 Subject: [python-list] pdf read & write Message-ID: <200707271658.53374.david@boddie.org.uk> On Fri Jul 27 15:35:02 CEST 2007, Hyunchul Kim wrote: > How can I read a pdf file and add invisible comment? > I want to make a script which read a pdf file and add tags inside the > file invisibly. Then, I will make a script for managing tags of given > pdf files. > > I know "referencer" can manage tags for pdf file but it seems store tag > information to additional file outside pdf file. > > Any suggestion are welcome. pyPdf may do some or all of what you are asking for: http://pybrary.net/pyPdf/ David From dwahler at gmail.com Sat Jul 14 00:34:51 2007 From: dwahler at gmail.com (David Wahler) Date: Fri, 13 Jul 2007 23:34:51 -0500 Subject: Can I change one line in a file without rewriting the whole thing? In-Reply-To: <1184381184.772946.218220@w3g2000hsg.googlegroups.com> References: <1184381184.772946.218220@w3g2000hsg.googlegroups.com> Message-ID: On 7/13/07, J. J. Ramsey wrote: > In Perl, there is a module called "Tie::File". What it does is tie a > list to each line of a file. Change the list, and the file is > automatically changed, and on top of this, only the bits of the file > that need to be changed are written to disk. At least, that's the > general idea. > > I was wondering if something roughly similar could be done in Python, > or at the very least, if I can avoid doing what amounts to reading the > whole file into memory, changing the copy in memory, and writing it > all out again. The mechanism behind Perl's ties -- an array that, when read from or written to, passes control to a user function -- is easy to implement in Python. See the documentation of the mapping protocol : >>> class SpecialList(object): ... def __getitem__(self, index): ... return "Line %d" % index >>> foo = SpecialList() >>> foo[42] 'Line 42' >From the documentation for Tie::File, it doesn't look like a trivial piece of code; for example, it has to maintain a table in memory containing the offset of each newline character it's seen for fast seeking, and it has to handle moving large chunks of the file if the length of a line changes. All this could be implemented in Python, but I don't know of a ready-made version off the top of my head. If all you want is to read the file line-by-line without having the whole thing in memory at once, you can do " From gagsl-py2 at yahoo.com.ar Fri Jul 13 21:51:55 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Jul 2007 22:51:55 -0300 Subject: permission denied in shutil.copyfile References: <1184338589.129432.178560@w3g2000hsg.googlegroups.com> <14A2A120D369B6469BB154B2D2DC34D20855ACB9@EXCHVS01.ad.sfwmd.gov> Message-ID: En Fri, 13 Jul 2007 12:10:20 -0300, Ahmed, Shakir escribi?: > Is there any way to copy a file from src to dst if the dst is > exclusively open by other users. > > I am using > > src = 'c:\mydata\data\*.mdb' > dst = 'v:\data\all\*.mdb' > > shutil.copyfile(src,dst) > > but getting error message permission denied. 1) try with a local copy too, and you'll notice an error too - it's unrelated to other users holding the file open. 2) use either r'c:\mydata\data' or 'c:\\mydata\\data\' 3) shutil.copyfile copies ONE FILE at a time. 4) use glob.glob to find the desired set of files to be copied; and perhaps you'll find copy2 more convenient. -- Gabriel Genellina From semanticist at gmail.com Tue Jul 24 13:37:20 2007 From: semanticist at gmail.com (Miles) Date: Tue, 24 Jul 2007 13:37:20 -0400 Subject: datetime.time() class - How to pass it a time string? In-Reply-To: <1185297087.998644.53940@r34g2000hsd.googlegroups.com> References: <1185297087.998644.53940@r34g2000hsd.googlegroups.com> Message-ID: On 7/24/07, Robert Dailey wrote: > Hi, > > I have a string in the following format: > > "00:00:25.886411" > > I would like to pass this string into the datetime.time() class and > have it parse the string and use the values. However, the __init__() > method only takes integers (which means I'd be forced to parse the > string myself). Does anyone know of a way I can make it use the > string? Thanks. timestr = "00:00:25.886411" timesep = re.compile('[:.]') datetime.time(*[int(i) for i in timesep.split(timestr)]) From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Jul 11 05:00:37 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 11 Jul 2007 11:00:37 +0200 Subject: Dynamic method In-Reply-To: References: <46939ba9$0$32159$426a74cc@news.free.fr> Message-ID: <46949c19$0$23164$426a34cc@news.free.fr> Daniel Nogradi a ?crit : (snip) >> > def method_for_instance( message ): >> > print message >> > >> > class myClass( object ): >> > pass >> > >> > inst = myClass( ) >> > inst.method = method_for_instance >> > >> > inst.method( 'hello' ) (snip) >> This won't work as expected: >> >> class Bidule(object): >> def __init__(self, name): >> self.name = name >> >> def greet(self, who): >> print "hello %s, my name is %s" % (who, self.name) >> >> b = Bidule('Bruno') >> b.greet = greet >> b.greet('Daniel') >> >> => >> Traceback (most recent call last): >> File "", line 1, in >> File "/tmp/python-23258Nq5.py", line 10, in >> b.greet('Daniel') >> TypeError: greet() takes exactly 2 arguments (1 given) > > > Well, I thought the name method_for_instance and method_for_class are > clear enough that if you want to 'attach' one of them to an instance > then method_for_instance should be used :) > And method_for_instance has only one argument and so will work as in > the example I gave (I guess you just overlooked them). I didn't overlooked anything. *You* did. Your "method_for_instance" is *not* a method - it's a function. It's easy to check this out: >>> class Toto(object): ... def truc(self): ... print "%s.truc" % self ... >>> def chose(): ... print "in chose, no 'self' here" ... >>> t = Toto() >>> t.truc > >>> t.chose = chose >>> t.chose >>> The whole point of methods is that they do have access to the object (instance or class) - which is not the case of your "method_for_instance". Please reread the following: > >> The point is that Python functions are descriptor objects that, when >> looked up, return a (bound or unbound) method object wrapping >> themselves. So to attach functions as method *on a per-instance basis*, >> you either need to use new.instancemethod (as explained by Alex), or >> directly use the descriptor protocol, ie: >> >> b.greet = greet.__get__(b) >> b.greet('Daniel') >> => hello Daniel, my name is Bruno >> >> Note that you don't need this to attach a function as method to a class >> - the descriptor protocol will then JustWork(tm). > > > I agree that in general the solution explained by Alex and you is better. They are not "better" - they are correct. HTH From grante at visi.com Thu Jul 26 10:20:58 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 26 Jul 2007 14:20:58 -0000 Subject: Generating PDF reports References: Message-ID: <13ahbear9nuv841@corp.supernews.com> On 2007-07-26, marcpp wrote: > Hi i'm introducing to do reports from python, any recomendation? Learn to use Google? http://www.google.com/search?q=pdf+report+python -- Grant Edwards grante Yow! My haircut is totally at traditional! visi.com From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Jul 13 03:52:59 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 13 Jul 2007 09:52:59 +0200 Subject: Class decorators do not inherit properly In-Reply-To: References: Message-ID: <46972f33$0$26400$426a74cc@news.free.fr> Chris Fonnesbeck a ?crit : > I have a class that does MCMC sampling (Python 2.5) that uses decorators > -- one in particular called _add_to_post that appends the output of the > decorated method to a class attribute. > However, when I > subclass this base class, the decorator no longer works: > > Traceback (most recent call last): > File "/Users/chris/Projects/CMR/closed.py", line 132, in > class M0(MetropolisHastings): > File "/Users/chris/Projects/CMR/closed.py", line 173, in M0 > @_add_to_post > NameError: name '_add_to_post' is not defined > > yet, when I look at the dict of the subclass (here called M0), I see the > decorator method: > > In [5]: dir(M0) > Out[5]: > ['__call__', > '__doc__', > '__init__', > '__module__', > '_add_to_post', > ... > > I dont see what the problem is here -- perhaps someone could shed > some light. I thought it might be the underscore preceding the name, > but I tried getting rid of it and that did not help. A minimal runnable code snippet reproducing the problem would *really* help, you know... Anyway: the body of a class statement is it's own namespace. So in the body of your base class, once the _add_to_post function is defined, you can use it. But when subclassing, the subclass's class statement creates a new namespace, in which _add_to_post is not defined - hence the NameError. To access this symbol, you need to use a qualified name, ie: class SubClass(BaseClass): @BaseClass._add_to_post def some_method(self): # code here Now there may be better solutions, but it's hard to tell without knowing more about your concrete use case. HTH From larry.bates at websafe.com Wed Jul 25 15:16:58 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 25 Jul 2007 14:16:58 -0500 Subject: Windows error 126 loading a dll on windows 2000 In-Reply-To: <1185386102.634182.264810@b79g2000hse.googlegroups.com> References: <1185386102.634182.264810@b79g2000hse.googlegroups.com> Message-ID: <4oSdnfrRosA7PDrbnZ2dnUVZ_jmdnZ2d@comcast.com> luis wrote: > Hi! > > I'm using ctypes with python 2.4 on windows xp > > the code > > if exists(join(getcwd(),'statistics.dll')): > ...ap=windll.LoadLibrary(join(getcwd(),'statistics.dll')) > > works fine > > > but on windows 2000, the some code raise the windows error 126, it > can't load the module statistics.dll > > thanks in advance > Using Google on "windows error 126" turned this up, hope it helps. http://flashexperiments.insh-allah.com/ApacheError126.html -Larry From duncan.booth at invalid.invalid Mon Jul 30 07:20:30 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Jul 2007 11:20:30 GMT Subject: TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal'. Why? References: <1185791793.141118.44080@x35g2000prf.googlegroups.com> <5h5ufoF3hmufcU4@mid.uni-berlin.de> Message-ID: Marc 'BlackJack' Rintsch wrote: > On Mon, 30 Jul 2007 03:36:33 -0700, Gilbert Fine wrote: > >> This is a very strange exception raised from somewhere in our >> program. I have no idea how this happen. And don't know how to >> reproduce. It just occurs from time to time. > > Maybe different `Decimal`\s? Here's how to reproduce such a > traceback: > Or even just one Decimal type but not one which supports subtraction: >>> class Decimal(object): pass >>> a = Decimal() >>> b = Decimal() >>> a-b Traceback (most recent call last): File "", line 1, in a-b TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal' Another option of course is that Decimal() did support substraction but someone deleted it: >>> from decimal import Decimal >>> del Decimal.__sub__ >>> Decimal()-Decimal() Traceback (most recent call last): File "", line 1, in Decimal()-Decimal() TypeError: unsupported operand type(s) for -: 'Decimal' and 'Decimal' From stuart.tett at gmail.com Thu Jul 5 00:19:32 2007 From: stuart.tett at gmail.com (Stuart) Date: Thu, 05 Jul 2007 04:19:32 -0000 Subject: PyRun_String using my module in a def In-Reply-To: <1i0qtvm.sq102f16mpe7tN%aleax@mac.com> References: <1183601931.930115.132400@n2g2000hse.googlegroups.com> <1i0qtvm.sq102f16mpe7tN%aleax@mac.com> Message-ID: <1183609172.421840.171130@n60g2000hse.googlegroups.com> What command do you mean when you say "update main_dict with dlfl_dict"? I tried PyObject *rstring = PyRun_String( cmd, Py_file_input, dlfl_dict, dlfl_dict ); This worked, but has the side effect of not allowing other commands like "execfile" I was able to type that before, but now it just says "name 'execfile' is not defined" Thanks for your help! :) On Jul 4, 10:23 pm, a... at mac.com (Alex Martelli) wrote: > Stuart wrote: > > ... > > > PyObject *rstring = PyRun_String( cmd, Py_file_input, main_dict, > > dlfl_dict ); > > You're passing difl_dict as the "locals" to PyRun_String -- but a > function has its own locals, so it won't use those locals. Just update > main_dict with difl_dict (that's the equivalent of the "from difl import > *" which you appear to desire) and use main_dict for both globals and > locals in your PyRun_String call. > > Alex From steve at REMOVE.THIS.cybersource.com.au Tue Jul 31 12:57:02 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 01 Aug 2007 02:57:02 +1000 Subject: What is the "functional" way of doing this? References: <1185835690.530367.66600@m37g2000prh.googlegroups.com> <1185838434.596591.132640@d30g2000prg.googlegroups.com> <7x3az5wjfa.fsf@ruckus.brouhaha.com> <1185839713.412656.242950@i13g2000prf.googlegroups.com> Message-ID: 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] -- Steven. From michele.simionato at gmail.com Wed Jul 4 09:21:21 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: Wed, 04 Jul 2007 13:21:21 -0000 Subject: CGI vs WSGI In-Reply-To: <1183553365.160758.29320@q75g2000hsh.googlegroups.com> References: <1183553365.160758.29320@q75g2000hsh.googlegroups.com> Message-ID: <1183555281.317426.160070@c77g2000hse.googlegroups.com> On Jul 4, 2:49 pm, tuom.lar... at gmail.com wrote: > Dear all, > > what is the difference? Middleware? Yes, and also the fact that you have a large choice of WSGI web frameworks to choose from. CGI looks so much 20th century ... ;) Michele Simionato From bernhard.voigt at gmail.com Tue Jul 3 07:59:51 2007 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: Tue, 03 Jul 2007 11:59:51 -0000 Subject: good matlab interface In-Reply-To: References: Message-ID: <1183463991.086787.233520@q69g2000hsb.googlegroups.com> On Jul 2, 3:02 pm, Brian Blais wrote: > On Jun 30, 2007, at 2:31 AM, felix seltzer wrote: > > > Does any one know of a good matlab interface? > > I would just use scipy or numpy, but i also need to use > > the matlab neural network functions. I have tried PyMat, but am > > having > > a hard time getting it to install correctly. did you try mlabwrap? for me it worked without problems. http://mlabwrap.sourceforge.net/ bernhard > > What problems are you having installing? I had one problem with the > terrible matlab license server, which I had to solve by making site- > packages world writable, installing pymat as a user, and then > removing the world writable flag. Root just didn't have access to > matlab on my machine. :P > > bb From Eric_Dexter at msn.com Tue Jul 10 11:38:09 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: Tue, 10 Jul 2007 08:38:09 -0700 Subject: trouble controlling vim with subprocess on windows machine In-Reply-To: <1184058013.324624.220540@i38g2000prf.googlegroups.com> References: <1183970186.663847.4380@o61g2000hsh.googlegroups.com> <1184023825.646120.251060@d55g2000hsg.googlegroups.com> <5qFki.19733$2v1.4163@newssvr14.news.prodigy.net> <1184058013.324624.220540@i38g2000prf.googlegroups.com> Message-ID: <1184081889.194824.214960@22g2000hsm.googlegroups.com> On Jul 10, 4:00 am, agc wrote: > Hi Josiah, > > > >> This recipe for asynchronous communication usingsubprocesscould be > > >> used to write an expect-like tool: > > >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554 > > I have played with the above recipe and it is excellent, > but could you please go into some more detail about what is needed > to make a cross platform [p]expect like (non-pty based) tool? > > Specifically, could you describe how you would connect to > *another* interactive Python process with your subclass of > subprocess.Popen? > i.e: > > a = Popen('python', stdin=?, stdout=?, stderr=?) > #now run an interactive session with 'a' > > I have tried several combinations of the above and I seem > to be stuck on the fact that python is interacting with a > 'tty', not 'std*'. Maybe I'm missing a basic piece? > > Thanks for any input, > Alex > > > > > >> It works on both Windows and *nix. > > > >> - Josiah > > > > I had the original dir work but when I tried to trade it out withvim > > > it isn't clear > > > how I should call it.. vimfilename and it doesn't find filename for > > > some reason. > > > I called it pipe and then > > > > inport pipe > > > > def load_instrument3(instr_name, csd_name): > > > if sys.platform == 'win32': > > > shell, commands, tail = ('gvim' + csd_name, (csd_name, > > > csd_name), '\r\n') > > > else: > > > shell, commands, tail = ('sh', ('ls', 'echo HELLO WORLD'), > > > '\n') > > > > a = pipe.Popen(shell, stdin=pipe.PIPE, stdout=pipe.PIPE) > > > print pipe.recv_some(a), > > > for cmd in commands: > > > pipe.send_all(a, csd_name) > > > print pipe.recv_some(a), > > > pipe.send_all(a, csd_name) > > > print pipe.recv_some(a, e=0) > > > a.wait() > > > The example uses a platform-specific shell in order to use the > > environment variable PATH to discover the executable to run. If you > > know the exact path to your binary ('gvim' for you), it should work. > > As-is, your program would require a binary with the name 'gvim'+csd_name > > in the same path as the script you are executing. > > > - Josiah- Hide quoted text - > > - Show quoted text - I gave this a shot with a windows batch file (although I am not sure I am doing it right) path c:\program files\vim\vim71 path c:\dex tracker gvim bay-at-night.csd echo \intsr | gvim echo \ | gvim echo :r strings.orc | gvim pause and it just pulls up gvim bay-at-night.csd and never does the two searches or pulls up the file. I do have a windows version of sh if that works better. From claird at lairds.us Mon Jul 16 15:33:15 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 16 Jul 2007 19:33:15 +0000 Subject: Technology solutions for Ruby? References: <1184606739.054580.197740@g37g2000prf.googlegroups.com> <1184611602.414529.41090@i38g2000prf.googlegroups.com> <1184611876.692894.17140@g4g2000hsf.googlegroups.com> Message-ID: In article <1184611876.692894.17140 at g4g2000hsf.googlegroups.com>, wrote: . . . >wxPython uses the native widgets of the platform it is running on in >most (if not all) cases, so if you want the "native look & feel", than >that is the way I would go. They have the best user's group I've seen >so far as well. > >Mike > Now you have me curious--when you write of "the best user's group ...", do you mean ? From alia_khouri at yahoo.com Tue Jul 31 07:36:00 2007 From: alia_khouri at yahoo.com (Alia Khouri) Date: Tue, 31 Jul 2007 04:36:00 -0700 Subject: problems with logging module In-Reply-To: References: <1185744598.663382.126920@19g2000hsx.googlegroups.com> <1185778252.177411.286660@k79g2000hse.googlegroups.com> Message-ID: <1185881760.484421.171780@b79g2000hse.googlegroups.com> > You are not going beyond basicConfig - I'd write the above as: Intentionally didn't go beyond basicConfig. The problem is global level configuration vs. easy local (in function or in class) configuration. > logging.basicConfig(...) > > def __init__(self, x): > self.x = x > self.log = logging.getLogger("a.nice.name") > > If you *do* need more than a handler, or different formatters for > different loggers, then you must write your own setup anyway; perhaps > using logging.config files, or perhaps writing your own code. I can't > think of a simple and generic approach (beyond what basicConfig provides) > but if you can write something that other people find useful, feel free to > submit a patch. Why not indeed... let's see what happens. AK From steve at holdenweb.com Mon Jul 23 21:16:58 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Jul 2007 21:16:58 -0400 Subject: Subclassing int In-Reply-To: <4a7f84ac0707231803x7083a688kc91965a5d78e679@mail.gmail.com> References: <4a7f84ac0707231803x7083a688kc91965a5d78e679@mail.gmail.com> Message-ID: G wrote: > Hi, > > I am trying to subclass int to allow a constructor to accept None. I > am trying the following > > class INT(int): > def __init__(self, x): > if x is None: > return None > else: > int.__init__(x) > > b = INT(x=None) > > When i run the previous code i get the following error: > b = INT(x=None) > TypeError: int() argument must be a string or a number, not 'NoneType'. > > Do you guys know why the if statement is not evaluated? > > Thanks for your help > Probably because you need to override the __new__() method rather than the __init__() method: >>> class INT(int): ... def __new__(cls, arg=0): ... if arg is None: ... return None ... else: ... return int.__new__(cls, arg) ... >>> n = INT(3.2) >>> n 3 >>> n = INT("42") >>> n 42 >>> n = INT(None) >>> print n None >>> 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 jzgoda at o2.usun.pl Thu Jul 12 05:57:31 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Thu, 12 Jul 2007 11:57:31 +0200 Subject: Samodzielny program pod linuksem In-Reply-To: <1184233689.085729.254850@g4g2000hsf.googlegroups.com> References: <1184233689.085729.254850@g4g2000hsf.googlegroups.com> Message-ID: stainboy napisa?(a): > Witam. Zastanawiam si? w jaki spos?b mog? stworzy? samodzielny program > pod linuksem napisany w pythonie, aby mo?na go by?o uruchomi? bez > instalacji bibliotek pythona, chodzi mi o co? takiego jak py2exe pod > Windowsa. I think you tried to post on pl.comp.lang.python so I'd just set FUT. -- Jarek Zgoda Skype: jzgoda | GTalk: zgoda at jabber.aster.pl | voice: +48228430101 "We read Knuth so you don't have to." (Tim Peters) From tjreedy at udel.edu Fri Jul 27 10:55:09 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Jul 2007 10:55:09 -0400 Subject: <> vs != References: <8a6b8e350707261228x234b7da0g17d43736e45e67ca@mail.gmail.com> <8c7f10c60707270408sdb320acua927ce016a90b20b@mail.gmail.com> Message-ID: "Simon Brunning" wrote in message news:8c7f10c60707270408sdb320acua927ce016a90b20b at mail.gmail.com... | On 7/26/07, James Matthews wrote: | > What is the difference between <> and != | | <> is deprecated, != isn't. Other than that, nothing AFAIK. And <> will disappear in 3.0. From danb_83 at yahoo.com Fri Jul 13 19:31:50 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: Fri, 13 Jul 2007 16:31:50 -0700 Subject: Pass by reference or by value? In-Reply-To: <1184353832.314694.228270@n60g2000hse.googlegroups.com> References: <1184353832.314694.228270@n60g2000hse.googlegroups.com> Message-ID: <1184369510.117726.125720@x35g2000prf.googlegroups.com> On Jul 13, 2:10 pm, Robert Dailey wrote: > Hi, > > I noticed in Python all function parameters seem to be passed by > reference. This means that when I modify the value of a variable of a > function, the value of the variable externally from the function is > also modified. Python is pass-by-value. It's just that all values are implicit "pointers". Much like Java except without a distinction between primitives and objects. > Sometimes I wish to work with "copies", in that when I pass in an > integer variable into a function, I want the function to be modifying > a COPY, not the reference. Is this possible? Typically, there's no reason to make a copy of an immutable object. But if you want to copy things, take a look at the "copy" module. From evan at yelp.com Wed Jul 11 16:53:06 2007 From: evan at yelp.com (Evan Klitzke) Date: Wed, 11 Jul 2007 13:53:06 -0700 Subject: 2**2**2**2**2 wrong? Bug? In-Reply-To: <1184182757.797808.206480@d55g2000hsg.googlegroups.com> References: <7xbqek7ty1.fsf@ruckus.brouhaha.com> <1184173446.779276.250530@k79g2000hse.googlegroups.com> <1184182757.797808.206480@d55g2000hsg.googlegroups.com> Message-ID: On 7/11/07, Paul McGuire wrote: > On Jul 11, 12:04 pm, David Jones wrote: > > > In fact, if I put (2**2)**2**2**2 > > > it comes up with the correct answer, 4294967296 > > > > Actually, the "correct" answer (even by your own demonstration) is > > 65536. > > It might be easier to demonstrate if we chose a less homogeneous > problem: 2**3**2. A right (rightly?) associative language (such as > Python) reads this as 2**(3**2), or 2**9=512. A left-associative > language (such as VB) reads this as (2**3)**2 or 8**2=64. As was > pointed out earlier, left-associativity with exponentiation is of > little value, since (2**3)**2 is the same as 2**(3*2) or 2**6=64. It doesn't have anything to do with the language being left/right associative, it has to do with the operators in question. For example, subtraction is always left associative -- you would be really surprised if 3 - 2 - 1 evaluated to 2. Python happens to choose right associativity for exponentiation because it is more useful for that operator, but that doesn't make the language itself right associative. -- Evan Klitzke From sjmachin at lexicon.net Sat Jul 14 22:14:40 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 14 Jul 2007 19:14:40 -0700 Subject: Fastest way to convert a byte of integer into a list In-Reply-To: <1184461927.888285.47100@k79g2000hse.googlegroups.com> References: <1184279667.771787.219500@w3g2000hsg.googlegroups.com> <1184321842.921823.317470@k79g2000hse.googlegroups.com> <1184359588.648337.24830@m3g2000hsh.googlegroups.com> <1184453355.853001.5510@57g2000hsv.googlegroups.com> <1184461927.888285.47100@k79g2000hse.googlegroups.com> Message-ID: <1184465680.373127.99740@g12g2000prg.googlegroups.com> On Jul 15, 11:12 am, "mensana... at aol.com" wrote: > On Jul 14, 5:49?pm, Paul McGuire wrote: > > > > > On Jul 13, 3:46 pm, "mensana... at aol.com" wrote: > > > > On Jul 13, 5:17 am, Paul McGuire wrote: > > > > > On Jul 12, 5:34 pm, Godzilla wrote: > > > > > > Hello, > > > > > > I'm trying to find a way to convert an integer (8-bits long for > > > > > starters) and converting them to a list, e.g.: > > > > > > num = 255 > > > > > numList = [1,1,1,1,1,1,1,1] > > > > > > with the first element of the list being the least significant, so > > > > > that i can keep appending to that list without having to worry about > > > > > the size of the integer. I need to do this because some of the > > > > > function call can return a 2 lots of 32-bit numbers. I have to find a > > > > > way to transport this in a list... or is there a better way? > > > > > Standing on the shoulders of previous posters, I put this together. > > > > > -- Paul > > > > But aren't we moving backwards? The OP did ask for the fastest way. > > > > I put this together (from other posters and my own): > > > > import gmpy > > > import time > > > > y = 2**177149 - 1 > > > > # init list of tuples by byte > > > bytebits = lambda num : [num >> i & 1 for i in range(8)] > > > bytes = [ tuple(bytebits(i)) for i in range(256) ] > > > # use bytes lookup to get bits in a 32-bit integer > > > bits = lambda num : sum((bytes[num >> i & 255] for i in range(0,32,8)), > > > ()) > > > # use base-2 log to find how many bits in an integer of arbitrary > > > length > > > from math import log,ceil > > > log_of_2 = log(2) > > > numBits = lambda num : int(ceil(log(num)/log_of_2)) > > > # expand bits to integers of arbitrary length > > > arbBits = lambda num : sum((bytes[num >> i & 255] for i in > > > range(0,numBits(num),8)),()) > > > t0 = time.time() > > > L = arbBits(y) > > > t1 = time.time() > > > print 'Paul McGuire algorithm:',t1-t0 > > > > t0 = time.time() > > > L = [y >> i & 1 for i in range(177149)] > > > t1 = time.time() > > > print ' Matimus algorithm:',t1-t0 > > > > x = gmpy.mpz(2**177149 - 1) > > > t0 = time.time() > > > L = [gmpy.getbit(x,i) for i in range(177149)] > > > t1 = time.time() > > > print ' Mensanator algorithm:',t1-t0 > > > > ## Paul McGuire algorithm: 17.4839999676 > > > ## Matimus algorithm: 3.28100013733 > > > ## Mensanator algorithm: 0.125 > > > Oof! Pre-calculating those byte bitmasks doesn't help at all! It > > would seem it is faster to use a single list comp than to try to sum > > together the precalcuated sublists. > > > I *would* say though that it is somewhat cheating to call the other > > two algorithms with the hardcoded range length of 177149, when you > > know this is the right range because this is tailored to fit the input > > value 2**177149-1. This would be a horrible value to use if the input > > number were something small, like 5. I think numBits still helps here > > to handle integers of arbitrary length (and only adds a slight > > performance penalty since it is called only once). > > I agree. But I didn't want to compare your numBits > against gmpy's numdigits() which I would normally use. > But since the one algorithm required a hardcoded number, > I thought it best to hardcode all three. > > I originally coded this stupidly by converting > the number to a string and then converting to > a list of integers. But Matimus had already posted > his which looked a lot better than mine, so I didn't. > > But then I got to wondering if Matimus' solution > requires (B**2+B)/2 shift operations for B bits. > > My attempt to re-code his solution to only use B > shifts didn't work out and by then you had posted > yours. So I did the 3-way comparison using gmpy's > direct bit comparison. I was actually surprised at > the difference. > > I find gmpy's suite of bit manipulation routines > extremely valuable and use them all the time. > That's another reason for my post, to promote gmpy. > > It is also extremely important to keep coercion > out of loops. In other words, never use literals, > only pre-coerced constants. For example: > > import gmpy > def collatz(n): > ONE = gmpy.mpz(1) > TWO = gmpy.mpz(2) > TWE = gmpy.mpz(3) > while n != ONE: > if n % TWO == ONE: > n = TWE*n + ONE > else: > n = n/TWO > collatz(gmpy.mpz(2**177149-1)) > > > > > -- Paul Try the following function; it works for arbitrary positive integers, doesn't need a 3rd party module, doesn't need to worry whether all that ceil/log/log floating-point stuffing about could result in an off- by-one error in calculating the number of bits, works with Python 1.5.2, and is competitive with Matimus's method. def listbits(n): result = [] app = result.append while n: app(n & 1) n = n >> 1 return result Cheers, John From mensanator at aol.com Mon Jul 30 18:38:39 2007 From: mensanator at aol.com (mensanator at aol.com) Date: Mon, 30 Jul 2007 15:38:39 -0700 Subject: yield keyword usage In-Reply-To: References: <1185830034.713489.174640@r34g2000hsd.googlegroups.com> Message-ID: <1185835119.029148.36040@d30g2000prg.googlegroups.com> On Jul 30, 4:40 pm, Erik Jones wrote: > On Jul 30, 2007, at 4:13 PM, Ehsan wrote: > > > > > > > hi > > coulde any one show me the usage of "yield" keyword specially in this > > example: > > > """Fibonacci sequences using generators > > > This program is part of "Dive Into Python", a free Python book for > > experienced programmers. Visithttp://diveintopython.org/for the > > latest version. > > """ > > > __author__ = "Mark Pilgrim (m... at diveintopython.org)" > > __version__ = "$Revision: 1.2 $" > > __date__ = "$Date: 2004/05/05 21:57:19 $" > > __copyright__ = "Copyright (c) 2004 Mark Pilgrim" > > __license__ = "Python" > > > def fibonacci(max): > > a, b = 0, 1 > > while a < max: > > yield a > > a, b = b, a+b > > > for n in fibonacci(1000): > > print n, > > As in how it works? Sure, when you use the yield statement in a > function or method you turn it into a generator method that can then > be used for iteration. What happens is that when fibonacci(1000) is > called in the for loop statement it executes up to the yield > statement where it "yields" the then current value of a to the > calling context at which point n in the for loop is bound to that > value and the for loop executes one iteration. Upon the beginning of > the for loop's next iteration the fibonacci function continues > execution from the yield statment until it either reaches another > yield statement or ends. In this case, since the yield occured in a > loop, it will be the same yield statement at which point it will > "yield" the new value of a. It should be obvious now that this whole > process will repeat until the condition a < max is not longer true in > the fibonacci function at which point the function will return > without yielding a value and the main loop (for n in ...) will > terminate. Also note that the function could terminate without ever executing a yield statement (if max<0). In which case nothing would get printed just like in for n in []: print n, You could also force the generator to abort rather than relying on the while loop not executing by using a return instead of a yield statement. This can be useful if the while executes even when given bad arguments. def fibonacci(max): if max < 0: # test for invalid argument print 'max must be >0' # diagnostic message return # kill generator a, b = 0, 1 while a < max: yield a a, b = b, a+b for n in fibonacci(1000): print n, print print for n in fibonacci(-1000): print n, ## 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 ## ## max must be >0 > > Erik Jones > > Software Developer | Emma? > e... 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 athttp://www.myemma.com From carsten at uniqsys.com Wed Jul 25 17:21:38 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 25 Jul 2007 17:21:38 -0400 Subject: Why PHP is so much more popular for web-development In-Reply-To: <1185396904.642985.141300@z24g2000prh.googlegroups.com> References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> <1185392048.737400.290050@j4g2000prf.googlegroups.com> <1185396904.642985.141300@z24g2000prh.googlegroups.com> Message-ID: <1185398498.4432.124.camel@dot.uniqsys.com> On Wed, 2007-07-25 at 13:55 -0700, walterbyrd wrote: > On Jul 25, 2:12 pm, Carsten Haese wrote: > > > Also, CherryPy's requirements are very > > minimal. > > In terms of memory and CPU, maybe. But I think that *requires* apache > 2.x and a very recent version of mod_python. By web-hosting > standards, those are very steep requirements. Apache 2 came out 5 years ago. I wouldn't trust a web hosting provider who can't be bothered to install software that's been out for 5 years to stay up to date on security patches. You get what you pay for. Also, CherryPy does not *require* Apache. It supplies its own web server. Getting that server to run on a shared host may be a problem, but it is incorrect to state that CherryPy *requires* Apache 2. -- Carsten Haese http://informixdb.sourceforge.net From ajaksu at gmail.com Mon Jul 9 00:42:25 2007 From: ajaksu at gmail.com (ajaksu) Date: Mon, 09 Jul 2007 04:42:25 -0000 Subject: How to override PyGridTableBase.SetColLabelValue()? In-Reply-To: <1183951644.304339.243210@z28g2000prd.googlegroups.com> References: <1183951644.304339.243210@z28g2000prd.googlegroups.com> Message-ID: <1183956145.534911.138880@n2g2000hse.googlegroups.com> On Jul 9, 12:27 am, fck... at gmail.com wrote: > Dear all, > > the doc is missing, and i failed to find the solution on google search. > anyone know how to override the function SetColLabel() inside > the class PyGridTableBase or the class GridTableBase? Some docs to back up the old code that follows :) http://wiki.wxpython.org/wxPyGridTableBase http://wiki.wxpython.org/wxGrid http://wxwidgets.org/manuals/stable/wx_wxgrid.html#wxgridsetcollabelvalue I hope this helps, it's old and 2.6, the design had many weird requirements plus I never got to think about whether it was a good way to do it. Anyway, the docs are far better :) > my code, (snip) Mine: class SpeciesBase(object): def __init__(self, ncols=1, nrows=15, colnames=None, rownames=None): self.__data = [] self.rows = [] self.cols = [] def __getitem__(self, col): return self.__data[col][:] class SpeciesTableBase(wx.grid.PyGridTableBase): def __init__(self): wx.grid.PyGridTableBase.__init__(self) self.data = SpeciesBase() self._rows = self.GetNumberRows() self._cols = self.GetNumberCols() def SetColLabelValue(self, col, value): self.data.cols[col] = str(value) def GetNumberRows(self): return len(self.data[0]) class SpeciesGrid(wx.grid.Grid): def __init__(self, parent): wx.grid.Grid.__init__(self, parent, -1) self.table = SpeciesTableBase() def rename_col(self, col, value): self.table.SetColLabelValue(col, value) self.table.ResetView(self) Other useful links: http://wiki.wxpython.org/UpdatingGridData http://wiki.wxpython.org/DrawingOnGridColumnLabel From steve at holdenweb.com Tue Jul 24 07:14:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Jul 2007 07:14:30 -0400 Subject: some parts of wxPython broken on Mac In-Reply-To: <1185268611.681037.298490@m37g2000prh.googlegroups.com> References: <1185268611.681037.298490@m37g2000prh.googlegroups.com> Message-ID: ahlongxp wrote: > Sorry, I know this is not the most appropriate place to talk about > wxPython. > But I can't have access to wxPython mail list page(because I don't pay > enough). > > I downloaded python2.5 and wxPython 2.8.4.0 from pythonmac.org and > installed them into one of my friends' Mac 10.4.8(intel) > and I found wx.lib.flatnotebook and wx.xrc were broken(which are quite > OK under both Linux and Windows). > > because I don't have the machine, I can't give more details. > > I hope someone will be good enough to check out these problems. > I'm not a Mac user, so I can't answer the technical issues. But I *do* know that the wxPython users list is just as open as python-list, so I see no reason why you shouldn't point these issues out there. Cost shouldn't be a factor. If you do so, however, you should give a little more information than that the components "are broken". That won't help anyone isolate an 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 duncan.booth at invalid.invalid Wed Jul 25 15:41:12 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Jul 2007 19:41:12 GMT Subject: is_iterable function. References: <1185389920.275300.174900@q75g2000hsh.googlegroups.com> <5uNpi.36822$G23.3430@newsreading01.news.tds.net> Message-ID: Neil Cerutti wrote: > Speaking of the iter builtin function, is there an example of the > use of the optional sentinel object somewhere I could see? for line in iter(open('somefile.txt', 'r').readline, ''): print line From nytrokiss at gmail.com Wed Jul 18 20:00:59 2007 From: nytrokiss at gmail.com (James Matthews) Date: Wed, 18 Jul 2007 17:00:59 -0700 Subject: Exiting from python shell In-Reply-To: <139t910dmac5i37@corp.supernews.com> References: <469e8068$0$8912$88260bb3@free.teranews.com> <139t910dmac5i37@corp.supernews.com> Message-ID: <8a6b8e350707181700s2e18ad01jaff26a65fdd36824@mail.gmail.com> try raise SystemExit On 7/18/07, Mark Elston wrote: > > * James Stroud wrote (on 7/18/2007 4:27 PM): > > Tobiah wrote: > >> For years now, I've been exiting the shell by typing 'exit\n', > >> being chid by the shell, and then typing ^D. I can't > >> remember a time that I typed the ^D the first time. Call > >> me an idiot if you must, but since someone took the trouble > >> to catch the command 'exit' in a special way, would it have > >> been so awful to just let it be a way to exit when the shell? > >> > >> Thanks, > >> > >> Toby > >> > > > > Yes, this would have required a ground-up approach to redesigning the > > python language, transmuting it to something like a cross between lisp > > and COBOL and would have rendered it impossible to author with C because > > of the way C implements pointers--hardcoding in assembly would likely be > > required. Beyond that, exiting an interpreter is not known in computer > > science and has been shown impossible by Goedel himself in a series of > > monographs on the topic. Thus, to exit python via a keyword would > > require also reformulating mathematics as we know it. Furthermore, such > > a change would propagate itself, via the observer effect, to the > > behavior of sub atomic particles via ill-defined quantum-mechanical > > affects and would likely result in the reversal of the Second Law of > > Thermodynamics, wherein your refrigerator would end up heating its > > contents and milk would spontaneously spoil, among other anomalies. > > > > For these reasons, you might propose a "quit" keyword. > > > > James > > > > You know, some answers simply *must* be saved for posterity.... > > Mark > -- > http://mail.python.org/mailman/listinfo/python-list > -- http://www.goldwatches.com/watches.asp?Brand=14 http://www.jewelerslounge.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From khemkaamit at gmail.com Mon Jul 16 04:34:26 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Mon, 16 Jul 2007 14:04:26 +0530 Subject: Fetching a clean copy of a changing web page In-Reply-To: References: Message-ID: <1360b7230707160134v71d2edacw977dadde9a3193d5@mail.gmail.com> On 7/16/07, John Nagle wrote: > I'm reading the PhishTank XML file of active phishing sites, > at "http://data.phishtank.com/data/online-valid/" This changes > frequently, and it's big (about 10MB right now) and on a busy server. > So once in a while I get a bogus copy of the file because the file > was rewritten while being sent by the server. > > Any good way to deal with this, short of reading it twice > and comparing? > If you have: 1. Ball park estimate of the size of XML 2. Some footers or "last tags" in the XML May be you can use the above to check the xml and catch the "bogus" ones ! cheers, -- ---- 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 datulaida.ali at gmail.com Mon Jul 16 03:20:13 2007 From: datulaida.ali at gmail.com (datulaida ali) Date: Mon, 16 Jul 2007 15:20:13 +0800 Subject: How to import java class used Jython in Python? Message-ID: <3b927740707160020g52eb5a24te58a955821de156c@mail.gmail.com> Hi all... How to import Semantic class used Jython in Python? here my java code.. JAVA CODE ---------------- import java.text.BreakIterator ; class Semantic { // native C++ method //public native void printMessage( String message ); public native String printMessage( String message ); // load library JNIPrintMessage into JVM static { System.loadLibrary( "JNIPrintMessage" ); } public static void main(String [] args) { String l = "i go to school"; pilih_ayat(l); } public static String pilih_ayat(String n){ JNIPrintWrapper wrapper = new JNIPrintWrapper(); String ayat_siap = wrapper.printMessage(n); System.out.println("output >>" + ayat_siap); return n; }//end pilih ayat public Semantic(){ System.out.println ("Berjaya"); } }//end class JAVA OUTPUT -------------------- output >> (S(NLP i) (VP go(PP to(NLP school)))) -------------- next part -------------- An HTML attachment was scrubbed... URL: From tim at tdw.net Thu Jul 26 19:26:23 2007 From: tim at tdw.net (Tim Williams) Date: Fri, 27 Jul 2007 00:26:23 +0100 Subject: From D In-Reply-To: References: <1185272393.484032.125180@22g2000hsm.googlegroups.com> <46a6086d$0$8399$9b622d9e@news.freenet.de> <5gmthsF3hc0n2U1@mid.individual.net> <1185384166.503862.236170@d55g2000hsg.googlegroups.com> <87ps2ghtd7.fsf@benfinney.id.au> <1185412639.075218.186290@z24g2000prh.googlegroups.com> <87d4yfivyv.fsf@benfinney.id.au> Message-ID: <9afea2ac0707261626p78ce48a1udb5adaa049b6ec9d@mail.gmail.com> On 26/07/07, mensanator at aol.com wrote: >> The str.split method has no bearing on this discussion, > It most certainly does. To make '123 456' into an integer, > you split it and then join it. > >>> z = '123 456' > >>> y = z.split() > >>> x = ''.join(y) > >>> w = int(x) > >>> w > 123456 ....but it doesn't if you use replace !! >>> z = '123 456' >>> int( z.replace( ' ' ,'' ) ) > 123456 > Propose: > 123 456 789 => 123456789 > 123.456 789 => 123.456789 +1 for me too -- Tim Williams From exarkun at divmod.com Wed Jul 18 17:04:54 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 18 Jul 2007 17:04:54 -0400 Subject: How do you debug when a unittest.TestCase fails? In-Reply-To: <32e43bb70707181340u7e4b545bp1f025c941b40134e@mail.gmail.com> Message-ID: <20070718210454.4947.853567445.divmod.quotient.13123@ohm> On Wed, 18 Jul 2007 16:40:46 -0400, "Emin.shopper Martinian.shopper" wrote: >Dear Experts, > >How do you use pdb to debug when a TestCase object from the unittest module >fails? Basically, I'd like to run my unit tests and invoke pdb.pm when >something fails. > >I tried the following with now success: > >Imagine that I have a module _test.py that looks like the following: > >----------------------- >import unittest >class MyTest(unittest.TestCase): > def testIt(self): > raise Exception('boom') >if __name__ == '__main__': > unittest.main() >----------------------- > >If I do >>>>import _test; _test.unittest() > >no tests get run. > >If I try >>>>import _test; t = _test.MyTest() > >I get > >Traceback (most recent call last): > File "", line 1, in > File "c:\python25\lib\unittest.py", line 209, in __init__ > (self.__class__, methodName) >ValueError: no such test method in : runTest > >If I try >>>>import _test; t = _test.MyTest(methodName='testIt'); t.run() > >nothing happens. I use `trial -b ', which automatically enables a bunch of nice debugging functionality. ;) However, you can try this, if you're not interested in using a highly featureful test runner: try: unittest.main() except: import pdb pdb.pm() This will "post-mortem" the exception, a commonly useful debugging technique. Jean-Paul From jan.vorwerk at cretin.fr Wed Jul 4 17:46:02 2007 From: jan.vorwerk at cretin.fr (Jan Vorwerk) Date: Wed, 04 Jul 2007 23:46:02 +0200 Subject: Reversing a string In-Reply-To: References: <1182997438.541012.54100@o61g2000hsh.googlegroups.com> <1i0kjpx.wjw44j15np22dN%aleax@mac.com> Message-ID: <468c151b$0$26790$426a74cc@news.free.fr> Martin Durkin a ?crit , le 02.07.2007 06:38: > This is an interesting point to me. I am just learning Python and I > wonder how I would know that a built in function already exists? > At what point do I stop searching for a ready made solution to a > particular problem and start programming my own function? > Is it just a matter of reading *all* the documentation before I start > coding? The answer from another beginner like me is: dir() Try it out interactively (my example with Python 2.4): --------------------------------------- >>> dir() ['__builtins__', '__doc__', '__name__'] >>> __builtins__ >>> dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] >>> reversed >>> dir(reversed) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__iter__', '__len__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'next'] >>> print reversed.__doc__ reversed(sequence) -> reverse iterator over values of the sequence Return a reverse iterator --------------------------------------- Far from me the idea that manuals are useless, but this is a nice thing about Python that you can look at what is available interactively. Cheers Jan From bbxx789_05ss at yahoo.com Tue Jul 31 12:53:11 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: Tue, 31 Jul 2007 09:53:11 -0700 Subject: encode() question Message-ID: <1185900791.595830.21290@d55g2000hsg.googlegroups.com> 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? From paul at boddie.org.uk Tue Jul 17 08:50:47 2007 From: paul at boddie.org.uk (Paul Boddie) Date: Tue, 17 Jul 2007 05:50:47 -0700 Subject: How to organize control access to source code ? In-Reply-To: <1184627782.951682.77870@n2g2000hse.googlegroups.com> References: <1184618776.798929.98960@57g2000hsv.googlegroups.com> <1184627782.951682.77870@n2g2000hse.googlegroups.com> Message-ID: <1184676647.068641.3500@d30g2000prg.googlegroups.com> On 17 Jul, 01:16, Succe... at gmail.com wrote: > > Thanks for your response, > But I want to know if there is a process or best practices, to give > not the access to all of the project. in other words, must every > developer work on the entire copy of the project locally ? You probably want to split the project up into several individual projects (as perceived from a technical perspective), which can then be protected using whichever mechanisms are available. Not only will it be easier to introduce various access controls - for example, you might have a bunch of different CVS modules (or similar things) which are then easier to administer and apply access controls to - but you'll also reduce the undesirable side-effects that come with a monolithic project with lots of people hacking on different stuff that inadvertently breaks other stuff. > Or to work just on his module and manage a process of integration, and > if there is any Agile practices for this problem. I'm not sure what the overlap is between "agile development" and restrictive access controls, but another approach might be to use a totally distributed version control system and then manage the restrictions when merging changes. You'd probably remain "agile" whilst exercising the control you require. Paul From zyzhu2000 at gmail.com Wed Jul 25 21:00:08 2007 From: zyzhu2000 at gmail.com (beginner) Date: Thu, 26 Jul 2007 01:00:08 -0000 Subject: Flatten a list/tuple and Call a function with tuples In-Reply-To: References: <1185375018.793020.224890@w3g2000hsg.googlegroups.com> <46a76a0c$0$1471$9b622d9e@news.freenet.de> <1185378418.100041.38560@w3g2000hsg.googlegroups.com> Message-ID: <1185411608.688527.163210@z24g2000prh.googlegroups.com> > Also, this has not been suggested: > > py> def g(): > ... return (1,2) > ... > py> def f(a,b,c): > ... return a+b+c > ... > py> f(c=10, *g()) > 13 > > James- Hide quoted text - > > - Show quoted text - Great idea. From walterbyrd at iname.com Wed Jul 25 15:34:08 2007 From: walterbyrd at iname.com (walterbyrd) Date: Wed, 25 Jul 2007 12:34:08 -0700 Subject: Why PHP is so much more popular for web-development In-Reply-To: References: <1185385374.866372.198520@x35g2000prf.googlegroups.com> Message-ID: <1185392048.737400.290050@j4g2000prf.googlegroups.com> On Jul 25, 12:40 pm, Carsten Haese wrote: > What exactly could Python learn from PHP? Remember, I'm a noob, I'm not trolling. When I posted "Python" I meant the Python web-developement world. In particular, python frameworks, like CherryPy, have requirements that are not realistic for most shared hosting plans. Maybe I'm wrong, but I often get the idea that those who develop python frameworks don't give a thought to the realities of shared hosting. They seem to think that everybody has complete control over the server. Things are very different in the PHP universe. To use codeignitor as an example, again. On the "why codeignitor" part of the welcome page you will find: --- CodeIgniter is right for you if... * You need broad compatibility with standard hosting accounts that run a variety of PHP versions and configurations. * You want a framework that requires nearly zero configuration. * You want a framework that does not require you to use the command line. --- I don't seem to see Python frameworks using those sorts of selling points. Posting as a noob, who is struggling to get django configured on dreamhost, I gotta tell 'ya: those selling points look awfully attractive. The point is: PHP framework makers are very considerate of the realities of shared hosting. Python framework makers don't seem to give it a thought. Just maybe, that's something that Python could learn from PHP. From rustompmody at gmail.com Sun Jul 1 23:35:38 2007 From: rustompmody at gmail.com (Rustom Mody) Date: Mon, 2 Jul 2007 09:05:38 +0530 Subject: How to uninstall packages In-Reply-To: <200707012003.05390.thomas@jollans.com> References: <200707012003.05390.thomas@jollans.com> Message-ID: Yeah sure thats what is (finally) working but its never clear upfront for a package what its dependency needs are -- linux version of DLL hell. And it gets worse for systems that are little worlds in themselves like python, ruby, eclipse, webmin etc. because they have their own package-management systems which invariably quarell with the native apt/rpm or whatever... On 7/1/07, Thomas Jollans wrote: > On Sunday 01 July 2007, Rustom Mody wrote: > > > I first installed the debian package python-pysqlite1.1 using > > synaptic. Since this seemed too old for other packages (sqlalchemy) I > > downloaded the sources pysqlite-2.3.4.tar.gz and ran setup install. > > I wonder why you chose not to use python-pysqlite2... > -- > http://mail.python.org/mailman/listinfo/python-list > From yinghe.chen at jeppesen.com Wed Jul 25 06:16:29 2007 From: yinghe.chen at jeppesen.com (Yinghe Chen) Date: Wed, 25 Jul 2007 12:16:29 +0200 Subject: how to get next month string? References: <1185279342.863711.246700@d30g2000prg.googlegroups.com> Message-ID: John's method works perfectly, thanks all for your kind help. "John Machin" wrote in message news:1185279342.863711.246700 at d30g2000prg.googlegroups.com... > On Jul 24, 8:31 pm, "Yinghe Chen" wrote: >> Hi, >> Could someone help on how to use python to output the next month string >> like >> this? >> >> "AUG07", suppose now is July 2007. >> >> I think also need to consider Dec 07 case, it is supposed to output as >> below: >> "JAN07". >> >> datetime module seems not supporting the arithmatic operations, any >> hints? >> >> Thanks in advance, >> >> Yinghe Chen > >>>> import datetime >>>> def nextmo(d): > ... mo = d.month > ... yr = d.year > ... mo += 1 > ... if mo > 12: > ... mo = 1 > ... yr += 1 > ... return datetime.date(yr, mo, 1).strftime('%b%y').upper() > ... >>>> nextmo(datetime.date(2007,7,15)) > 'AUG07' >>>> nextmo(datetime.date(2007,12,15)) > 'JAN08' >>>> > From rcdailey at gmail.com Fri Jul 27 19:54:45 2007 From: rcdailey at gmail.com (Robert Dailey) Date: Fri, 27 Jul 2007 23:54:45 -0000 Subject: C++ Modules for python: How to? In-Reply-To: <1185578126.072526.19550@d55g2000hsg.googlegroups.com> References: <1183750094.154566.248170@m36g2000hse.googlegroups.com> <5f7llqF3bfvstU1@mid.uni-berlin.de> <1183764388.576690.31740@n60g2000hse.googlegroups.com> <1183768797.659079.17150@o11g2000prd.googlegroups.com> <1185578126.072526.19550@d55g2000hsg.googlegroups.com> Message-ID: <1185580485.825166.285430@i38g2000prf.googlegroups.com> Okay I've actually got it compiling now, however it is saying it can't find "stdio.h" (No such file or directory). This means it doesn't know where the include directories are. How do I specify include directories? From johnmasters at oxtedonline.net Tue Jul 17 16:49:03 2007 From: johnmasters at oxtedonline.net (John K Masters) Date: Tue, 17 Jul 2007 21:49:03 +0100 Subject: sqlite tuples Message-ID: <20070717204903.GA3890@spookie1.spookiegate> I am fairly new to Python and am trying to get to grips with pysqlite2. >From what I have read data is returned as a list of tuples when using SELECT via connection.cursor. But I have not, despite frantic googling, found how to INSERT a list of tuples into a sqlite table. If I convert the tuple to a string and concatenate it to the 'INSERT INTO table etc.' string then it works, but only if all the tuple values are strings and then only if all the table fields are of type TEXT. Is it possible to, and if so how can one, insert a list of tuples into a sqlite table? Regards, John -- War is God's way of teaching Americans geography Ambrose Bierce (1842 - 1914) From gagsl-py2 at yahoo.com.ar Tue Jul 10 20:37:23 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Jul 2007 21:37:23 -0300 Subject: path backslash escaping trouble References: <1184031604.157526.45120@c77g2000hse.googlegroups.com> Message-ID: En Mon, 09 Jul 2007 22:40:04 -0300, placid escribi?: > I have these files; which are Merge Request (ClearCase) files that are > created by a Perl CGI script (being re-written in Python, as the HTML/ > JavaScript have been mixed with Perl, maintainability is zero) > > MergeType::::codefromlabel:::: > BLname::::BUILDMODS:::: > OldLname:::::::: > BaseVersion::::6.9.1.24A:::: > RequiredRelease::::6.10.1.3:::: > Description:::::::: > FixRelation:::::::: > Dependencies:::::::: > LpAffected::::No:::: > CodeReview::::FirstName LastName:::: > Testing::::Compile/Build;Designer;Smoketests;:::: > OtherTesting:::::::: > Vobs::::ipsupport;:::: > Elements::::\ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3:::: > > i read this whole file into a string so i can search for the value of > Elements which is > \ipsupport\ipbuild\Wizard\build.pl@@\main\buildmods\3 > > but this path is escaped > \\ipsupport\\ipbuild\\Wizard\\build.pl@@\\main\\buildmods\\3 > > so when i try to escape a string containing that same path using any > of the os.path escaping methods doesnt > result in the correct escaped path. It either appends "C:\\" in front > of the string with all the backslashes escaped > or it converts the three(3) at then end to "x03" and a match doesnt > occur! You may be confused about the actual string contents: "a\\b" contains exactly 3 characters, the second being a single backslash. The \ is the escape character; to include an actual \ inside a string, you have to double it. Another way is to use raw string literals (supressing escape processing): r"a\\b" contains four characters. See section 3.1.2 in the Python tutorial or the Reference (more technical): http://docs.python.org/ref/strings.html -- Gabriel Genellina From dlomsak at gmail.com Sun Jul 1 16:29:21 2007 From: dlomsak at gmail.com (dlomsak) Date: Sun, 01 Jul 2007 13:29:21 -0700 Subject: object references/memory access In-Reply-To: <46880833$0$1887$9b622d9e@news.freenet.de> References: <1183247524.662884.153830@n60g2000hse.googlegroups.com> <4687c63b$0$22513$9b622d9e@news.freenet.de> <7xfy48871j.fsf@ruckus.brouhaha.com> <4687cf4b$0$24940$9b622d9e@news.freenet.de> <7xfy48f486.fsf@ruckus.brouhaha.com> <1183318690.661279.256900@n2g2000hse.googlegroups.com> <46880833$0$1887$9b622d9e@news.freenet.de> Message-ID: <1183321761.576679.236070@c77g2000hse.googlegroups.com> Martin v. L?wis wrote: > > I guess now I'd like to know what are good practices in general to get > > better results with sockets on the same local machine. I'm only > > instantiating two sockets total right now - one client and one server, > > and the transfer is taking 15 seconds for only 8.3MB. > > It would be good if you had showed the code that does that. It is hard > for us to guess what programming error you have made. > > As you won't show code, I will. Please try the attached cli.py and > server.py on your machine, and report the timing. On my machine, I get > > 0.00105595588684 0.076632976532 8300000 > > which means I can transmit 8.3MB in 76ms, which is a lot less than > 15s. > > My guess is that you sum up the incoming data with > > total_data += received_data > > That is O(n**2). > > Regards, > Martin > > import socket,time,cStringIO > > t1 = time.time() > s = socket.socket() > s.connect(('localhost', 8989)) > t2 = time.time() > storage = cStringIO.StringIO() > while True: > data = s.recv(1024) > if not data: > break > storage.write(data) > result = storage.getvalue() > t3 = time.time() > > print t2-t1,t3-t2,len(result) > > import socket > > data = ' '*8300000 > s = socket.socket() > s.bind(('', 8989)) > s.listen(10) > while True: > s1, peer = s.accept() > print s1,peer > s1.send(data) > s1.close() I would have put my code up if it were here but it is on my machine at work which I can't touch until Monday. I know people tend to like to see code when you're asking for help but it is not available to me right now so I apologize. You are right though, I believe I made the mistake of using += to sum the data up and I had never considered the fact that the runtime of that approach is O(n^2). I am willing to bet that this was my major shortcoming and you just solved my problem. I bet the reason that jacking up the socket.recv size is because it took fewer concatenations. I'll give an official report tomorrow on weather or not that was the fix but I am very convinced that you got it and that I won't have to step around the socket transmission. Thanks a lot Martin and also to the others who responded. From gagsl-py2 at yahoo.com.ar Sat Jul 21 02:56:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 21 Jul 2007 03:56:53 -0300 Subject: exec and CodeObjects References: Message-ID: En Fri, 20 Jul 2007 12:48:05 -0300, Prepscius, Colin (IT) escribi?: > Does anybody know how to pass parameters to 'exec > somefunction.func_code'? > def f1(): > print 'this is f1' > def f2(p): > print 'this is f2, p =', str(p) > exec f1.func_code > THIS RESULTS IN: "this is nf1" WHICH IS NICE > exec f2.func_code > THIS RESULTS IN: TypeError: f2() takes exactly 1 argument (0 given) > WHICH IS EXPECTED Instead of using exec, rebuild a new function from the unmarshalled code: import new f3 = new.function(f2.func_code, globals()) f3(parameter) -- Gabriel Genellina From wildemar at freakmail.de Sun Jul 1 15:43:49 2007 From: wildemar at freakmail.de (Wildemar Wildenburger) Date: Sun, 01 Jul 2007 21:43:49 +0200 Subject: How does py2exe work? In-Reply-To: <200707012138.10254.thomas@jollans.com> References: <1183314093.002061.310700@m37g2000prh.googlegroups.com> <200707012138.10254.thomas@jollans.com> Message-ID: <468803F5.8010800@freakmail.de> Thomas Jollans wrote: > On Sunday 01 July 2007, vasudevram wrote: > >> Wondering how it works? Does it actually compile the Python source of >> your script into machine language, or does it do something more like >> bundling the Python interpreter, the Python libraries and the script >> itself, into a file? >> > > essentially, that's what it does. > > Q: A or B? A: Yes. *nudgenudge* /W From steve at holdenweb.com Wed Jul 25 12:18:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Jul 2007 12:18:51 -0400 Subject: 16-bit colour representation In-Reply-To: <5gp03nF3hl7siU1@mid.uni-berlin.de> References: <1185364424.797757.84620@22g2000hsm.googlegroups.com> <5gp03nF3hl7siU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > beertje wrote: > >> This has me a bit stumped... >> >> I'm trying to extract pictures from a file. So far I'm successfully >> retrieved the header and what I think is the colour for each pixel. >> Here's the description: >> >> """ >> 3) The picture data format: >> The color information is 15 bit data stored in 16 bit. This means the >> most >> significant bit is unused. The data is stored line for line in little >> endian Intel format starting with top left edge to bottom right edge. >> This >> is normally called chunky format. >> >> Bit 0.. 4 blue value >> Bit 5.. 9 green value >> Bit 10..14 red value >> """ >> >> So I've got a list of 16-bit numbers, but how to extract RGB info from >> those I'm a bit lost. I thought at first I should convert the decimal >> (say 23294) into a binary (say 0101101011111110) into something like >> this: >> blue: 01011 >> green: 01011 >> red: 11111 >> >> But encountered two problems: First, I don't know what the best way is >> to do this conversion, but more importantly I don't see how every >> colour could possibly be represented like this. 65535 is presumably >> white, but converting this into chunks of 5 gives me a 31, 31, 31, a >> dark shade of grey. >> >> I guess I'm on the wrong track completely? >> >> I'm a bit unsure about how to treat what the guide calls 'UWORD'... > > ANDing and SHIFTing are your friends here: > > v = 0x0bcd > b = v & 0xf > v >>= 4 > g = v & 0xf > v >>= 4 > r = v & 0xf > print r, g, b > > Alternatively, using 5-bit colors you would use b = v & 0x1f g = (v >> 5) & 0x1f r = (v >> 10) & 0x1f 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 kasimmominov at gmail.com Sat Jul 21 08:06:02 2007 From: kasimmominov at gmail.com (kasim) Date: Sat, 21 Jul 2007 12:06:02 -0000 Subject: h grup Message-ID: <1185019562.902156.185080@m3g2000hsh.googlegroups.com> Dear ______, I recently joined AGLOCO because of a friend recommended it to me. I am now promoting it to you because I like the idea and I want you to share in what I think will be an exciting new Internet concept. AGLOCO's story is simple: Do you realize how valuable you are? Advertisers, search providers and online retailers are paying billions to reach you while you surf. How much of that money are you making? NONE! AGLOCO thinks you deserve a piece of the action. AGLOCO collects money from those companies on behalf of its members. (For example, Google currently pays AOL 10 cents for every Google search by an AOL user. And Google still has enough profit to pay $1.6 billion dollars for YouTube, an 18-month old site full of content that YouTube's users did not get paid for! AGLOCO will work to get its Members their share of this and more. AGLOCO is building a new form of online community that they call an Economic Network. They are not only paying Members their fair share, but they're building a community that will generate the kind of fortune that YouTube made. But instead of that wealth making only a few people rich, the entire community will get its share. What's the catch? No catch - no spyware, no pop-ups and no spam - membership and software are free and AGLOCO is 100% member owned. Privacy is a core value and AGLOCO never sells or rents member information. So do both of us a favor: Sign up for AGLOCO right now! If you use this link to sign up, I automatically get credit for referring you and helping to build AGLOCO. http://www.agloco.com/r/BBFR2592 http://www.PassportToWealth.com/?id=kasim http://www.perfectwealthformula.com/?id=kasim http://dealsncash.com/members/index.cgi?kasim From duncan.booth at invalid.invalid Mon Jul 23 06:18:55 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Jul 2007 10:18:55 GMT Subject: Lazy "for line in f" ? References: <1185120650.412694.314280@o61g2000hsh.googlegroups.com> <1185143634.778056.227720@g4g2000hsf.googlegroups.com> <1185173778.656660.195650@n60g2000hse.googlegroups.com> <7xbqe3efm5.fsf@ruckus.brouhaha.com> <1185177589.837857.105390@r34g2000hsd.googlegroups.com> <1185182315.489049.271010@r34g2000hsd.googlegroups.com> Message-ID: Alexandre Ferrieux wrote: > On Jul 23, 10:33 am, Duncan Booth > wrote: >> >> The extra buffering means that iterating over a file is about 3 times >> faster than repeatedly calling readline. >> >> while 1: >> line = f.readline() >> if not line: >> break >> >> for line in f: >> pass >> > > Surely you'll notice that the comparison is spoilt by the fact that > the readline version needs an interpreted test each turn around. > A more interesting test would be the C-implemented iterator, just > calling fgets() (the thin layer policy) without extra 8k-blocking. > No, I believe the comparison is perfectly fair. You need the extra test for the readline version whatever you do, and you don't need it for the iterator. If you insist, you can add an identical 'if not line: break' into the iterator version as well: it adds another 10% onto the iterator runtime which is still nearly a factor of 3 faster than the readline version, but then you aren't comparing equivalent code. Alternatively you can knock a chunk off the time for the readline loop by writing it as: while f.readline(): pass or even: read = f.readline while read(): pass which gets it down from 10.3 to 9.0 seconds. It's 'fair' in your book since it avoids all the extra interpreter overhead of attribute lookup and a separate test, but it does make it a touch hard to do anything useful with the actual data. Whatever, the iterator makes the code both cleaner and faster. It is at the expense of not being suitable for interactive sessions, or in some cases pipes, but for those situations you can continue to use readline and the extra overhead in runtime will not likely be noticable. From wbrehaut at mcsnet.ca Fri Jul 13 18:20:29 2007 From: wbrehaut at mcsnet.ca (Wayne Brehaut) Date: Fri, 13 Jul 2007 16:20:29 -0600 Subject: Can a low-level programmer learn OOP? References: <4697d9f0$0$7614$426a74cc@news.free.fr> Message-ID: On Sat, 14 Jul 2007 06:01:56 +0200, Bruno Desthuilliers wrote: >Chris Carlen a ?crit : >> Hi: >> >> From what I've read of OOP, I don't get it. I have also found some >> articles profoundly critical of OOP. I tend to relate to these articles. >> === 8< === >> >> Hence, being a hardware designer rather than a computer scientist, I am >> conditioned to think like a machine. I think this is the main reason >> why OOP has always repelled me. > >OTOH, OO is about machines - at least as conceveid by Alan Key, who >invented the term and most of the concept. According to him, each object >is a (simulation of) a small machine. Oh you young'uns, not versed in The Ancient Lore, but filled with self-serving propaganda from Xerox PARC, Alan Kay, and Smalltalk adherents everywhere! As a few more enlightened have noted in more than one thread here, the Mother of All OOP was Simula (then known as SIMULA 67). All Alan Kay did was define "OOPL", but then didn't notice (apparently--though this may have been a "convenient oversight") that Simula satisfied all the criteria so was actually the first OOPL--and at least 10 years earlier than Smalltalk! So Kay actually invented NONE of the concepts that make a PL an OOPL. He only stated the concepts concisely and named the result OOP, and invented yet another implementation of the concepts-- based on a LISP-like functional syntax instead of an Algol-60 procedural syntax, and using message-passing for communication amongst objects (and assumed a GUI-based IDE) (and introduced some new terminology, especially use of the term "method" to distinguish class and instance procedures and functions, which Simula hadn't done) . As Randy Gest notes on http://www.smalltalk.org/alankay.html, "The major ideas in Smalltalk are generally credited to Alan Kay with many roots in Simula, LISP and SketchPad." Too many seem to assume that some of these other "features" of Smalltalk are part of the definition of an OOP, and so are misled into believing the claim that it was the first OOPL. Or they claim that certain deficiencies in Simula's object model--as compared to Smalltalk's--somehow disqualifies it as a "true OOPL", even though it satisfies all the criteria as stated by Kay in his definition. See http://en.wikipedia.org/wiki/Simula and related pages, and "The History of Programming Languages I (HOPL I)", for more details. Under a claim of Academic Impunity (or was that "Immunity"), here's another historical tid-bit. In a previous empolyment we once had a faculty applicant from CalTech who knew we were using Simula as our introductory and core language in our CS program, so he visited Xerox PARC before coming for his inteview. His estimate of Alan Kay and Smalltalk at that time (early 80s) was that "They wanted to implement Simula but didn't understand it--so they invented Smalltalk and now don't understand _it_!" wwwayne === 8< === From aahz at pythoncraft.com Thu Jul 19 18:52:58 2007 From: aahz at pythoncraft.com (Aahz) Date: 19 Jul 2007 15:52:58 -0700 Subject: class C: vs class C(object): References: <1184830266.181714.183320@z24g2000prh.googlegroups.com> Message-ID: In article , James Stroud wrote: >Aahz wrote: >> In article , >> Steven D'Aprano wrote: >>> >>>It isn't wrong to use the old style, but it is deprecated, [...] >> >> >> Really? Can you point to some official documentation for this? AFAIK, >> new-style classes still have not been integrated into the standard >> documentation. Maybe I missed something, though. >> >> Note very carefully that "going away eventually" is *not* the same as >> deprecation. > >How about "broke" instead of "deprecated": > > > >>> class Old: >... def __init__(self): >... self._value = 'broke' >... value = property(lambda self: self._value) >... How is this broken? Properties are not supported for old-style classes. They may not support features introduced in new-style classes, but that's hardly the same as "broken". -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ I support the RKAB